refactor: remove cloud/ billing mode and flatten to self-hosted-only

- Delete the entire cloud/ package (Stripe billing, auth/OAuth, metering, API keys,
  account erasure, lifecycle/digest emails, R2 archive, autopilot, MCP OAuth,
  proxy ledger, managed keys) and all BILLING_ENABLED branches in app.py
- Keep self-host behavior via no-op shims; /api/config now returns
  {youtubeUrlEnabled, jobRetentionSeconds, localLlm}
- Remove cloud tests (31 files), alembic/, log_view.py, requirements-billing.txt,
  docker-compose.cloud.yml; update CLI to Postiz + /api/config; clean docs/skills
- Flatten dashboard: remove auth/billing/pricing/history chrome, inert config-only AuthContext
- Fix residual test drift; lint + build + compile all green
This commit is contained in:
pedro-bento 2026-10-04 17:02:55 +01:00
parent fbabb4ec5d
commit edcfeaf9d5
131 changed files with 831 additions and 18619 deletions

View file

@ -3,19 +3,11 @@ AWS_ACCESS_KEY_ID=your_aws_access_key_here
AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here
AWS_REGION=eu-west-3
AWS_S3_BUCKET=your-bucket-name
AWS_S3_PUBLIC_BUCKET=your-public-bucket-name
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
# YOUTUBE_COOKIES=...
# Google OAuth (cloud/billing mode only). When logging in through a proxy whose
# Host header doesn't match a Google-registered URI (e.g. local dev via the Vite
# proxy), pin the callback explicitly:
# OAUTH_REDIRECT_URI=http://localhost:8000/api/auth/google/callback
# FRONTEND_URL=http://localhost:5175
# Local dev: show the full pipeline logs (yt-dlp/ffmpeg/debug) in the UI even
# when running in paid mode (BILLING_ENABLED). Cloud/prod leaves this unset.
# Local dev: show the full pipeline logs (yt-dlp/ffmpeg/debug) in the UI.
# DEBUG_LOGS=true
# Pre-flight quality gate: warn before processing a YouTube source below this
@ -75,11 +67,9 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# Privacy, retention and access control (GDPR remediation, 4-sep-2026)
# ---------------------------------------------------------------------------
# Absolute base URL of the API as the internet reaches it. Already used for the
# absolute clip URLs in webhook payloads; now also required to build the
# unsubscribe link that goes in the out-of-minutes email. Without it that email
# falls back to "reply to unsubscribe".
# PUBLIC_API_URL=https://api.openshorts.app
# Absolute base URL of the API as the internet reaches it, used for the
# absolute clip URLs in webhook payloads.
# PUBLIC_API_URL=https://your-host
# /videos and /thumbnails are authenticated endpoints, not static mounts.
# MEDIA_TOKEN_TTL_SECONDS: life of the per-user token the dashboard appends to
@ -131,19 +121,10 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# HSTS_HEADER=max-age=31536000; includeSubDomains
# Encrypted PostgreSQL backups (ops/pg_backup.sh — installed and scheduled on
# the database host, not by the app). The privacy policy promises a deletion is
# gone from every copy within 30 days, which is only true while this runs.
# the database host, not by the app).
# DATABASE_URL=postgres://user:pass@host:5432/openshorts
# BACKUP_AGE_RECIPIENT=age1...
# BACKUP_DEST=s3://openshorts-backups/pg
# BACKUP_S3_ENDPOINT=https://<accountid>.r2.cloudflarestorage.com
# RETENTION_DAYS=30
# Lifecycle emails (cloud/lifecycle.py, cloud mode only): welcome, a nudge a
# day after sign-up with nothing clipped, a win-back 2 days after the first
# free video, and the abandoned-checkout recovery link. The win-back carries
# a Stripe promotion code when one is set here (never commit the real code:
# this repository is public). LIFECYCLE_EMAILS_DISABLED=1 turns all four off.
# WINBACK_PROMO_CODE=
# WINBACK_PROMO_LABEL=50% off your first month
# LIFECYCLE_EMAILS_DISABLED=0

View file

@ -79,10 +79,9 @@ homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build ti
- Generates `sitemap.xml` and `llms.txt` from the same page list, so they cannot
drift. Do not add a static `public/sitemap.xml` back.
When editing pricing anywhere, edit `seo/data.js` too. Nothing on the site should
say "OpenShorts is free" without naming the Cloud price in the same breath: both
are true of different editions and quoting only the first one is what makes AI
answers describe the paid product as free.
When editing pricing anywhere, edit `seo/data.js` too. OpenShorts has a single
self-hosted edition: free and open source under MIT. Do not reintroduce a hosted
or paid tier into the copy.
### Free tools (/tools) and SEO attribution
@ -163,17 +162,6 @@ LLM it logs one line and keeps the transcript hook. `HOOK_GROUNDING=0`
disables it. The detail prompt itself now carries the rule "about this
moment, not the video", which is the cheap half of the same fix.
### Sign-up survey (`cloud/onboarding.py`, `OnboardingSurvey.jsx`)
`signup_attribution` says which page a user came from, not why. Accounts
younger than 7 days get one skippable screen before the clip tutorial (never
over a running job): what they want to make (multi-select: clip long videos
into shorts, publish to my socials, thumbnails...), how they heard of us, and who they are.
Closed lists mirrored in the JSX (a test checks), stored in
`onboarding_surveys` (user-owned; a skip is a row too, so it is asked once),
and tracked as `SignupSurveyAnswered` with one `goal_<x>` prop per goal so
OpenPanel can break conversion down by what people came for.
### How many clips a job returns (`clip_selection.py`)
The count is not a setting, it is derived, and every stage of the derivation
@ -381,7 +369,7 @@ vars. Because the clip file lives on the app server, the backend reads it and
uploads the bytes to Postiz (`POST /upload`, multipart), then references the
returned `{id, path}` in `POST /posts`. Provider settings (`tiktok`,
`instagram`, `youtube`) are built server-side from the clip title and caption.
Auth is the raw key, no `Bearer`. The old Upload-Post integration is gone.
Auth is the raw key, no `Bearer`.
### Webhooks
@ -428,9 +416,6 @@ checked by eye, audio identical):
- **Silero VAD on one CPU thread** (`vad_load_kwargs`): on CUDA it ran one
32 ms chunk per launch and was most of the transcription's wall time.
- **Blur at quarter size** (`ffmpeg_utils.blurred_backdrop`).
- **Watermark as a served copy** (`main.mark_delivery`, see the section
on the free plan's watermark): one NVENC pass per free clip, after
captions. It used to ride the reframe encode, which made it permanent.
- **hooked_ + subtitled_ from one ffmpeg** (`hooks.add_hook_to_video(also=)`):
the editor still needs both files (re-caption walks back to hooked_,
hook replace to the canonical), so nothing is skipped, only one decode.
@ -475,14 +460,13 @@ Failures the user should never see (`app.run_job_wrapper`):
the child is killed and the manifest + reservation are kept, so the next
instance resumes it. A manifest next to a metadata file means "stopped
mid-render" and is resumed, not recovered as completed.
- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued;
the dashboard shows it with a "paid plans skip the line" upsell (paid plans
do dispatch first: `PLAN_PRIORITY`).
- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued,
which the dashboard shows as a queue position and ETA.
### Paid proxy accounting (`cloud/proxy_ledger.py`)
### Download proxy routing and accounting (`yt_clients.py`, `metering.py`)
Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB),
and the duration probe (`cloud/metering.probe_url_minutes`) follows the same
and the duration probe (`metering.probe_url_minutes`) follows the same
order, with one extra free step before any per-GB attempt: the fallback
clients through a static (`fallback-static`). **The client list is explicit
and shared** (`yt_clients.py`: `default,mweb` + the bgutil PO token
@ -523,11 +507,8 @@ IP problem and escalated to the per-GB proxy, which carries the same cookies
and fails identically, while the download recovered for free on the same
static. `main.py` prints `PROXY_ROUTE=<json>` after
every download (winner, paid bytes across all attempts including failed
paid ones, each free attempt's error); `app.py` persists it as a
`proxy_usage` row at job end and pages Telegram when the paid proxy carried
bytes, folding a burst into one message per 5 min. The in-memory monthly
counter and the container log (rotates within the hour) cannot answer "what
cost $14 on the 28th"; the table can. Both the probe and the download pass `noplaylist`: a
paid ones, each free attempt's error); `app.py` logs `PROXY_ROUTE` at job end
and warns when the paid proxy carried bytes. Both the probe and the download pass `noplaylist`: a
`watch?v=X&list=...` or mix link is the one video the user was watching,
and without it yt-dlp walks the whole list, dies on its first private /
age-gated / bot-checked entry (a video nobody pasted), the probe reads

View file

@ -9,15 +9,11 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# Copy and install Python dependencies
# Copy and install Python dependencies
COPY requirements.txt requirements-billing.txt ./
COPY requirements.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
# GPU build (--build-arg GPU=1): user-space CUDA libs only — the NVIDIA
# container runtime injects the driver. cuBLAS 12 + cuDNN 9 for CTranslate2

View file

@ -1,41 +0,0 @@
# 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

View file

@ -1,60 +0,0 @@
"""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())

View file

@ -1,22 +0,0 @@
"""${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"}

1385
app.py

File diff suppressed because it is too large Load diff

View file

@ -1,13 +1,20 @@
# OpenShorts CLI
Clip long videos into vertical 9:16 shorts from the terminal. Zero
dependencies; talks to the same API the dashboard, the MCP server and the
webhooks use.
dependencies; talks to the same self-hosted REST API the dashboard uses.
```bash
pip install openshorts # or: uvx openshorts / pipx run openshorts
```
export OPENSHORTS_API_KEY=osk_... # from your account page at openshorts.app
## Use it against your own instance
OpenShorts is free, open source under MIT and self-hosted with Docker. There is
no hosted edition and no paid plan, so there is no account to create. Point the
CLI at your instance:
```bash
export OPENSHORTS_API_URL=http://localhost:8000
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips <job_id>
@ -15,18 +22,35 @@ openshorts publish <job_id> 0 --platforms tiktok,youtube
openshorts quota
```
Self-hosted instance? Point it at your own machine and skip the key:
Self-hosted instances are open by default and need no API key. You do need a
Google Gemini key: put it in the server's environment, or send it per call as an
`X-Gemini-Key` header. If you put your own instance behind a key, the CLI sends
`OPENSHORTS_API_KEY` (`osk_...`) as a bearer token.
## Publish through Postiz
Publishing goes through your self-hosted Postiz instance. Pass the base URL and
API key with `--postiz-url` / `--postiz-key`, or set `POSTIZ_URL` /
`POSTIZ_API_KEY`; the CLI forwards them to the server as `X-Postiz-Url` /
`X-Postiz-Key`.
```bash
export OPENSHORTS_API_URL=http://localhost:8000
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts publish <job_id> 0 --platforms tiktok,youtube \
--postiz-url https://postiz.example.com --postiz-key <key>
```
For pipelines, prefer the webhook to `--wait`: pass `--webhook` and
`--webhook-secret` and OpenShorts POSTs once (HMAC-signed,
`X-OpenShorts-Signature: sha256=<hex>`) when the job ends, with clip titles
and durable download links.
## Quota
The hosted free tier is 20 minutes/month with a watermark; paid plans from
$12/month. The self-hosted edition is MIT and has no meter. Agent-native
version of the same surface: [openshorts.app/mcp](https://www.openshorts.app/mcp).
`openshorts quota` prints the instance config it reads from `GET /api/config`:
the job-retention window, whether YouTube-URL ingest is enabled, and the
local-LLM setting. A self-hosted instance has no minute quota, so none is
reported.
## Pipelines and webhooks
Prefer the webhook to `--wait`: pass `--webhook` and `--webhook-secret` and
OpenShorts POSTs once (HMAC-signed, `X-OpenShorts-Signature: sha256=<hex>`) when
the job ends, with clip titles and durable download links.
The agent-native version of the same surface is the OpenShorts skill in
[`skills/openshorts/`](../skills/openshorts/).

View file

@ -1,14 +1,18 @@
"""OpenShorts CLI: clip long videos into vertical shorts from the terminal.
Zero dependencies by design so `uvx openshorts` and `pipx run openshorts`
start instantly. Talks to the same REST API the dashboard and the MCP server
use; nothing here can drift from what the app actually does.
start instantly. Talks to the same REST API the dashboard uses; nothing here
can drift from what the app actually does.
Auth and target come from the environment:
OPENSHORTS_API_KEY osk_... key from the account page (cloud only)
OPENSHORTS_API_KEY osk_... key for a deploy that requires one (optional;
a self-hosted instance needs none)
OPENSHORTS_API_URL defaults to https://api.openshorts.app; set to
http://localhost:8000 for a self-hosted instance,
where no key is needed.
Publishing goes through Postiz. The base URL and API key come from the
--postiz-url / --postiz-key flags, then POSTIZ_URL / POSTIZ_API_KEY.
"""
import argparse
@ -27,8 +31,10 @@ def _base():
return os.environ.get("OPENSHORTS_API_URL", DEFAULT_API).rstrip("/")
def _request(method, path, body=None):
def _request(method, path, body=None, extra_headers=None):
headers = {"Accept": "application/json"}
if extra_headers:
headers.update(extra_headers)
key = os.environ.get("OPENSHORTS_API_KEY")
if key:
headers["Authorization"] = f"Bearer {key}"
@ -154,20 +160,20 @@ def cmd_clips(args):
def cmd_quota(args):
status, payload = _request("GET", "/api/me")
# 401 anonymous, 404 self-host (the cloud router is not mounted): neither
# is an error, there is simply no minute quota to report.
if status in (401, 404):
print("no cloud account in play: self-hosted or anonymous, no minute quota")
return
# Self-host has no minute quota: the cloud /api/me router is gone. Report
# the instance config instead so the command stays useful.
status, payload = _request("GET", "/api/config")
if status >= 400:
_die(status, payload)
if args.json:
print(json.dumps(payload))
return
print(f"plan: {payload.get('plan')}")
print(f"minutes: {payload.get('minutes')}")
print(f"entitled: {payload.get('entitled')}")
print("self-hosted: no minute quota")
print(f"job retention: {payload.get('jobRetentionSeconds')}s")
print(f"youtube url: {'enabled' if payload.get('youtubeUrlEnabled') else 'disabled'}")
local_llm = payload.get("localLlm")
if local_llm:
print(f"local llm: {local_llm}")
def cmd_publish(args):
@ -182,7 +188,17 @@ def cmd_publish(args):
body["scheduled_date"] = args.schedule
if args.timezone:
body["timezone"] = args.timezone
status, payload = _request("POST", "/api/social/post", body)
postiz_key = args.postiz_key or os.environ.get("POSTIZ_API_KEY")
if not postiz_key:
print("error: no Postiz API key: pass --postiz-key or set POSTIZ_API_KEY",
file=sys.stderr)
sys.exit(1)
postiz_url = (args.postiz_url or os.environ.get("POSTIZ_URL") or "").rstrip("/")
headers = {"X-Postiz-Key": postiz_key}
if postiz_url:
headers["X-Postiz-Url"] = postiz_url
status, payload = _request("POST", "/api/postiz/post", body,
extra_headers=headers)
if status >= 400:
_die(status, payload)
print(json.dumps(payload) if args.json else f"publishing: {payload}")
@ -214,16 +230,18 @@ def main(argv=None):
p.add_argument("job_id")
p.set_defaults(func=cmd_clips)
p = sub.add_parser("quota", help="plan and remaining minutes")
p = sub.add_parser("quota", help="instance config (self-host has no quota)")
p.set_defaults(func=cmd_quota)
p = sub.add_parser("publish", help="post or schedule one clip to social platforms")
p = sub.add_parser("publish", help="post or schedule one clip through Postiz")
p.add_argument("job_id")
p.add_argument("clip_index", type=int)
p.add_argument("--platforms", required=True, help="comma list: tiktok,instagram,youtube")
p.add_argument("--title")
p.add_argument("--schedule", help="ISO datetime for scheduled posting")
p.add_argument("--timezone", help="IANA timezone for --schedule")
p.add_argument("--postiz-url", help="Postiz base URL (env POSTIZ_URL)")
p.add_argument("--postiz-key", help="Postiz API key (env POSTIZ_API_KEY)")
p.set_defaults(func=cmd_publish)
args = parser.parse_args(argv)

View file

@ -19,9 +19,9 @@ classifiers = [
]
[project.urls]
Homepage = "https://www.openshorts.app"
Homepage = "https://github.com/mutonby/openshorts"
Source = "https://github.com/mutonby/openshorts"
Documentation = "https://www.openshorts.app/mcp"
Documentation = "https://github.com/mutonby/openshorts/tree/main/cli"
[project.scripts]
openshorts = "openshorts_cli:main"

View file

@ -1,66 +0,0 @@
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.

View file

@ -1,65 +0,0 @@
"""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, api_keys,
account, mcp_oauth, marketing, autopilot, lifecycle, cancellation, onboarding) # noqa: F401
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
app.include_router(oauth.router)
app.include_router(billing.router)
# Cancel flow with reason + review (the portal can still cancel too).
app.include_router(cancellation.router)
# Sign-up survey: source, what they came to make, who they are.
app.include_router(onboarding.router)
app.include_router(social_profiles.router)
app.include_router(videos.router)
app.include_router(api_keys.router)
app.include_router(mcp_oauth.router)
app.include_router(account.router)
# Autopilot: clip new videos from the user's connected YouTube channel.
app.include_router(autopilot.router)
# Unsubscribe from commercial email (LSSI art. 21.2): the out-of-minutes
# upsell and the lifecycle emails (cloud/lifecycle.py).
app.include_router(marketing.router)
async def setup_async(app, keep_reservation_ids=None):
"""Async initialization done inside the FastAPI lifespan.
DB engine, orphaned-reservation cleanup and the metering sweeper live here.
``keep_reservation_ids`` belong to jobs being resumed after a restart and
must not be refunded (see app._resume_interrupted_jobs).
"""
from . import database, digest, metering, videos
await database.init_engine()
await metering.release_orphaned_reservations(keep_ids=keep_reservation_ids)
metering.start_sweeper()
videos.start_sweeper()
digest.start_digest()
print("☁️ Cloud billing mode ENABLED (DB ready, metering active).")

View file

@ -1,376 +0,0 @@
"""Account erasure: the GDPR Art. 17 "right to be forgotten", self-service.
The privacy policy already promises that "deleting your account from the
dashboard removes your content on the schedule above" — this is the code that
makes that sentence true. It is one endpoint, ``DELETE /api/account``, and it
is immediate and irreversible: erasure has to happen "without undue delay", and
once the account is gone there is no way left to authenticate whoever asks for
it back, so a recovery window would be a window nobody could safely use.
Two rules shape the order of operations below, and both come from asking what
happens when a step fails halfway:
1. **Stripe first, and abort if it refuses.** Deleting the user row while a
live subscription keeps charging a card we can no longer map to anyone turns
a privacy fix into a billing incident nobody can unwind. Cancelling first
means the worst case is a cancelled subscription on an account that still
exists — annoying, retryable, harmless.
2. **R2 before the database.** Those DB rows are the only index of which
objects belong to this user. Drop them first and a failed R2 delete leaves
objects that nothing in the system can ever find again; the bucket already
carries orphans from an earlier version of this reasoning.
What deliberately survives: the Stripe customer and its invoices (six-year
retention under Spanish commercial law, privacy policy §5) and one
[AccountDeletion] row proving the erasure happened — a sha256 of the email
rather than the address, and no free text anywhere in it. The confirmation
email tells the user both, because a record they were never told about is not
accountability, it is retention.
"""
import asyncio
import hashlib
from datetime import datetime, timezone, timedelta
from typing import Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select, delete, func
from .config import settings, DELETION_LOG_RETENTION_DAYS
from . import database, email_policy, storage
from .models import (
User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
Project, AccountDeletion, OAuthCode, AutopilotRun, AutopilotSettings,
LifecycleEmail, CancellationFeedback, OnboardingSurvey,
)
# Every table that holds rows belonging to a user, child-first (clip_expiry_
# warnings points at user_videos as well as at users).
#
# These are all declared ON DELETE CASCADE, so in theory deleting the user row
# is enough. We delete them by hand anyway: the schema is bootstrapped with
# ``create_all``, which never ALTERs an existing table, so a constraint added
# after a table first appeared in production exists in the models and not in
# the database. Trusting the cascade would mean the difference shows up as a
# foreign-key violation the first time a real user tries to leave.
USER_OWNED_TABLES = (
ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
Subscription, ApiKey, SignupAttribution, UploadPostProfile, OAuthCode,
AutopilotRun, AutopilotSettings, LifecycleEmail, CancellationFeedback,
OnboardingSurvey,
)
# The optional "why are you leaving" answer, as a closed list. It was a free
# text box first, and that was wrong: whatever the user types lands in a record
# that deliberately outlives their account, so a single "my name is X, please
# confirm" turns the one row meant to hold no readable identity into retained
# personal data. A fixed vocabulary cannot do that, and twenty deletions a month
# are far more legible counted than read.
DELETION_REASONS = (
"too_expensive", "not_using_it", "clip_quality", "missing_feature",
"found_alternative", "privacy", "other",
)
router = APIRouter()
# Job dirs on the API's own disk belong to app.py, which cannot be imported from
# here (the dependency runs the other way). It registers a purge callback at
# startup instead; when it hasn't, local files simply age out on their usual
# one-hour cleanup.
_local_purge = None
def register_local_purge(fn):
"""Let app.py hand us a ``(user_id) -> int`` local-file purge."""
global _local_purge
_local_purge = fn
def _now():
return datetime.now(timezone.utc)
def email_fingerprint(email: str) -> str:
"""The only trace of an address that outlives the account."""
return hashlib.sha256(email_policy.normalize_email(email).encode()).hexdigest()
async def free_plan_denial_for_signup(session, email: str) -> Optional[str]:
"""``User.free_plan_denied`` value for a brand-new account, or None.
An address whose account was erased in the last FREE_REDO_BLOCK_DAYS
comes back without the free allowance: the ledger is keyed by user id, so
a new row would otherwise start the month with a fresh 20 minutes. Paid
plans and top-ups work as for anyone. Matched on the same fingerprint the
erasure stored, so it needs no new personal data.
"""
from .config import FREE_REDO_BLOCK_DAYS
if not email or FREE_REDO_BLOCK_DAYS <= 0:
return None
since = _now() - timedelta(days=FREE_REDO_BLOCK_DAYS)
hit = (await session.execute(
select(AccountDeletion.id).where(
AccountDeletion.email_sha256 == email_fingerprint(email),
AccountDeletion.deleted_at >= since,
).limit(1)
)).scalar_one_or_none()
return "recreated_after_deletion" if hit is not None else None
async def _session_user(request: Request):
"""The signed-in user, refusing API-key auth.
Same reasoning as key management in cloud/api_keys.py: a leaked ``osk_``
token must not be able to destroy the account it was issued from.
"""
from . import api_keys
from .auth import get_current_user_required
auth = request.headers.get("Authorization", "")
if api_keys.looks_like_key(auth[7:].strip()) or api_keys.looks_like_key(
request.headers.get("X-API-Key", "")):
raise HTTPException(status_code=403, detail=(
"API keys cannot delete an account. Sign in to the dashboard."))
return await get_current_user_required(request)
# --------------------------------------------------------------------------- #
# The steps
# --------------------------------------------------------------------------- #
async def _cancel_subscriptions(user_id) -> Optional[str]:
"""Cancel every Stripe subscription on the account, immediately.
Returns the plan that was live (for the deletion record), or None. Raises
on a Stripe error so the caller can abort before anything is erased — see
rule 1 in the module docstring.
"""
import stripe
async with database.session() as session:
rows = list((await session.execute(
select(Subscription).where(Subscription.user_id == user_id)
)).scalars())
live = [r for r in rows if r.status not in ("canceled", "incomplete_expired")]
plan = live[0].plan if live else (rows[0].plan if rows else None)
for row in live:
try:
# cancel(), not cancel_at_period_end: the user is leaving now, and
# billing them again for a service whose data we just erased would
# be indefensible. Unused time is refunded as it always is.
await asyncio.to_thread(lambda sid=row.stripe_subscription_id:
stripe.Subscription.cancel(sid))
except stripe.InvalidRequestError as e:
# Stripe says this subscription is gone or already cancelled. Our
# row can be stale — a cancellation made in the portal whose webhook
# never landed leaves it reading "active" forever. Treating that as
# a hard error would trap the user: the one account that cannot be
# deleted is the one Stripe already stopped billing.
print(f"ℹ️ Subscription {row.stripe_subscription_id} already gone at Stripe: {e}")
return plan
async def _delete_upload_post_profile(user_id):
"""Remove the user's white-label profile (and its connected socials) at
Upload-Post. Best effort: a stale empty profile there holds no content of
ours, and failing the whole erasure over a third-party 500 would be worse.
"""
import httpx
from .social_profiles import API_BASE, _auth_headers
if not settings.managed_upload_post_key:
return
async with database.session() as session:
prof = await session.get(UploadPostProfile, user_id)
if prof is None:
return
username = prof.profile_username
try:
async with httpx.AsyncClient(timeout=20) as client:
resp = await client.request(
"DELETE", f"{API_BASE}/uploadposts/users",
headers={**_auth_headers(), "Content-Type": "application/json"},
json={"username": username},
)
if resp.status_code not in (200, 204, 404):
print(f"⚠️ Upload-Post profile delete returned {resp.status_code} for {username}")
except Exception as e:
print(f"⚠️ Upload-Post profile delete failed for {username}: {e}")
async def _erase_rows(user_id, email, stripe_customer_id, plan, r2_deleted, reason) -> bool:
"""Swap the account for its erasure record, in one transaction.
All-or-nothing on purpose: a half-erased account is worse than an un-erased
one, because the user is told they are gone while some of their rows are
not. Magic-link tokens are keyed by email rather than user id, so they need
their own statement on top of [USER_OWNED_TABLES].
Returns whether this call is the one that removed the account. Two requests
can race here — a double-click, or two tabs — and everything before this
point is idempotent, but the erasure record is not: writing it from the
loser would leave two rows for one deletion, possibly disagreeing about the
reason. Postgres serialises the two DELETEs, so the loser sees rowcount 0
and writes nothing.
"""
async with database.session() as session:
async with session.begin():
for model in USER_OWNED_TABLES:
await session.execute(
delete(model).where(model.user_id == user_id))
await session.execute(
delete(MagicLinkToken).where(MagicLinkToken.email == email))
result = await session.execute(delete(User).where(User.id == user_id))
if result.rowcount == 0:
return False
session.add(AccountDeletion(
former_user_id=str(user_id),
email_sha256=email_fingerprint(email),
stripe_customer_id=stripe_customer_id,
plan_at_deletion=plan,
r2_objects_deleted=r2_deleted,
reason=reason,
))
return True
# --------------------------------------------------------------------------- #
# Endpoint
# --------------------------------------------------------------------------- #
class DeleteAccountRequest(BaseModel):
# Typing the address is the confirmation step. Sessions last 30 days and
# there is no password to re-enter, so this is the strongest thing we can
# ask for without mailing a second token to a user who is leaving anyway.
confirm_email: str
reason: Optional[str] = None # one of DELETION_REASONS, or ignored
@router.delete("/api/account")
async def delete_account(payload: DeleteAccountRequest, request: Request):
user = await _session_user(request)
if email_policy.normalize_email(payload.confirm_email) != \
email_policy.normalize_email(user.email):
raise HTTPException(status_code=400, detail=(
"That doesn't match the email on this account."))
async with database.session() as session:
row = await session.get(User, user.id)
if row is None:
raise HTTPException(status_code=404, detail="Account not found.")
email, stripe_customer_id = row.email, row.stripe_customer_id
# A reserved ledger row means metered work is in flight. Erasing now
# would pull the output from under a job still writing it, and the
# reservation would never settle. Minutes are refunded on failure, so
# waiting costs the user nothing.
#
# This covers everything that costs minutes, which is everything long
# enough to matter. A free action (burning captions on an untranslated
# clip) writes no ledger row and so is not covered: worst case it fails
# on a missing file, in a tab whose session is about to end anyway.
in_flight = (await session.execute(
select(func.count(UsageLedger.id)).where(
UsageLedger.user_id == user.id, UsageLedger.status == "reserved")
)).scalar_one()
if in_flight:
raise HTTPException(status_code=409, detail=(
"A video is still processing. Wait for it to finish, then delete "
"your account."))
try:
plan = await _cancel_subscriptions(user.id)
except Exception as e:
print(f"⚠️ Account deletion aborted, Stripe cancel failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't cancel your subscription, so nothing was deleted. "
"Please try again, or email info@openshorts.app."))
# Storage before the third party: if the bucket refuses, the only thing that
# has changed so far is the cancelled subscription, and the error below can
# say so truthfully.
r2_deleted = None
if settings.r2_configured:
try:
r2_deleted = await asyncio.to_thread(
storage.delete_prefix, storage.user_prefix(user.id))
except Exception as e:
print(f"⚠️ Account deletion aborted, R2 purge failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't reach the storage that holds your clips, so your "
"account was not deleted. Your subscription has already been "
"cancelled. Please try again, or email info@openshorts.app."))
if _local_purge is not None:
try:
# rmtree over gigabytes of video: off the event loop, or every other
# request on the process waits for this user's disk to clear.
await asyncio.to_thread(_local_purge, user.id)
except Exception as e:
print(f"⚠️ Local job purge failed for {user.id}: {e}")
await _delete_upload_post_profile(user.id)
# Anything not in the closed list is dropped rather than rejected: a
# mismatched client must not be able to fail a deletion over a label.
reason = payload.reason if payload.reason in DELETION_REASONS else None
try:
erased = await _erase_rows(
user.id, email, stripe_customer_id, plan, r2_deleted, reason)
except Exception as e:
# The content is already gone; only the account row survived. Say that
# rather than a bare 500 — the user needs to know a retry is safe and
# that the account they can still sign into is now empty.
print(f"⚠️ Account row delete failed for {user.id} after purge: {e}")
raise HTTPException(status_code=500, detail=(
"Your clips were deleted but we couldn't close the account itself. "
"Please try again, or email info@openshorts.app."))
# ``email`` was read before the delete on purpose: from here on the address
# exists nowhere in our systems, and the goodbye email still has to go out.
if not erased:
# A concurrent request got there first and has already sent the email.
return {"deleted": True, "r2_objects_deleted": r2_deleted}
print(f"🗑️ Account erased: {user.id} (plan={plan}, r2_objects={r2_deleted})")
# Everything below is after-the-fact and must never fail the deletion.
try:
# OpenPanel only ever received the account uuid, never the address (see
# cloud/analytics.py), and it expires those identifiers on its own
# 13-month schedule — so this event adds no identity, it just makes the
# one churn signal we cannot otherwise see countable.
from . import analytics
analytics.track("AccountDeleted", user_id=user.id, plan=plan)
except Exception:
pass
try:
from .emails import send_account_deleted_email
await send_account_deleted_email(email)
except Exception as e:
print(f"⚠️ Goodbye email failed: {e}")
try:
from .alerts import send_telegram
await send_telegram(f"🗑️ Account deleted (plan: {plan or 'free'})")
except Exception:
pass
return {"deleted": True, "r2_objects_deleted": r2_deleted}
# --------------------------------------------------------------------------- #
# Retention
# --------------------------------------------------------------------------- #
async def purge_stale_deletion_records():
"""Drop erasure records past their own retention window.
The log exists to answer a complaint; once claims are time-barred it is
just a hashed address we have no reason to hold. Called from the video
retention sweeper.
"""
cutoff = _now() - timedelta(days=DELETION_LOG_RETENTION_DAYS)
async with database.session() as session:
async with session.begin():
await session.execute(
delete(AccountDeletion).where(AccountDeletion.deleted_at < cutoff))

View file

@ -1,438 +0,0 @@
"""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 asyncio
import os
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
# Specific signatures of a genuine proxy / download-stage failure. Kept precise
# on purpose: a bare "proxy"/"credit"/"balance" match fired on any job whose logs
# merely echoed the proxy URL (yt-dlp debug) or whose video title contained one of
# those words, producing false "out of credits" alerts for jobs that actually
# failed later in processing. These phrases only appear in real proxy failures.
_PROXY_HINTS = (
"proxyerror",
"cannot connect to proxy",
"failed to connect to proxy",
"unable to connect to proxy",
"proxy authentication required",
"407 proxy",
"http error 407",
"tunnel connection failed",
"402 payment required",
"out of credits",
"insufficient balance",
)
def _looks_like_proxy_error(err: str) -> bool:
e = (err or "").lower()
return any(k in e for k in _PROXY_HINTS)
def _classify_failure(err: str) -> str:
"""One-word category for the last error, so the alert points the right way."""
e = (err or "").lower()
if _looks_like_proxy_error(e):
return "proxy"
if "no_audio" in e or "no audio" in e:
return "no audio"
if "sign in to confirm" in e or "not a bot" in e or "http error 403" in e \
or "http error 429" in e or "video unavailable" in e or "read timed out" in e:
return "youtube download"
if "whisper" in e or "faster_whisper" in e or "transcrib" in e or "av/container" in e:
return "transcription"
# User content rejected by the AI provider's policy filter — deterministic,
# not actionable on our side. Named so the alert doesn't read as an outage.
if "prohibited_content" in e or "blocked this video" in e or "blocked its answer" in e:
return "blocked content (user video)"
# The source held nothing clip-shaped (typically an already-short video) —
# content-shaped like the policy block above, not an outage.
if "did not return usable clips" in e or "clip detection failed" in e:
return "no clips found (user video)"
if "gemini" in e or "google.genai" in e:
return "gemini"
if "ffmpeg" in e or "reframe" in e:
return "ffmpeg/render"
return "mixed"
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
# Prefix on every OpenShorts Telegram message. The chat is shared with other
# products (Upload-Post, …), so this tags which one each alert is from.
TELEGRAM_PREFIX = "OPENSHORTS ✂️ - "
def user_ref(user_id) -> str:
"""How a user is named in an operational alert: never by email address.
These alerts go to Telegram, whose Bot API is operated from outside the EEA
with no adequacy decision and no DPA available to us — so the messages must
not carry personal data. They used to read "alice@example.com bought +60
minutes". The first 8 hex of the account uuid is enough for the operator to
find the row (``select * from users where id::text like '3f9a1c2b%'``) and
is not, on its own, an identifier of a person to anyone reading the chat.
"""
ref = str(user_id or "").replace("-", "")
return f"user {ref[:8]}" if ref else "a user"
async def send_telegram(text: str, *, raise_errors: bool = False):
"""Push a plain-text message to the admin's Telegram chat. No-op if unset.
Best-effort by default: never raises — an alert failing must not break a
webhook or job. ``raise_errors=True`` is for callers with their own retry
(the daily digest), where swallowing the failure means losing the message.
"""
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": TELEGRAM_PREFIX + text,
"disable_web_page_preview": True}
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.post(url, json=payload)
resp.raise_for_status()
except Exception as e:
if raise_errors:
raise
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 AND open the
# incident so the proxy watcher keeps nagging until the balance is back
# (one alert at 3am is easy to miss; an exhausted proxy takes all
# YouTube-URL ingest down until someone tops it up).
if _looks_like_proxy_error(error_text):
if not _watch_down.get(_PAID_TARGET):
_watch_down[_PAID_TARGET] = time.time()
_watch_nag[_PAID_TARGET] = time.time()
if _cooldown_ok("proxy"):
await send_admin_alert(
"🔴 Proxy error — may be out of credits",
"A managed job failed with a proxy-related error. Check your proxy "
"balance — downloads will keep failing until it's topped up.\n"
"This repeats every 2 h until the proxy answers again.\n\n"
f"Error:\n{error_text[:1200]}",
)
return
# 2) High failure rate — report it honestly and classify the last error
# instead of always blaming the download path (it's often transcription of
# a silent upload, a bad video, etc.).
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(
f"⚠️ High job failure rate ({_classify_failure(error_text)})",
f"{fails} of the last {len(recent)} managed jobs failed.\n\n"
f"Last error:\n{error_text[:1200]}",
)
# --- Proxy watcher --------------------------------------------------------------
# A dead download route takes YouTube-URL ingest down (or silently moves it to
# per-GB billing), and a single alert at the moment it dies is easy to miss.
# The watcher probes every configured route on a schedule, keeps nagging on
# Telegram until it's fixed, and confirms recovery (incident of 19-aug-2026:
# DataImpulse 407 TRAFFIC_EXHAUSTED, found by accident hours later).
#
# Watched targets:
# - "static proxy pool" (STATIC_PROXY_URLS): flat-rate ISP IPs, the primary
# route. Ingest still works when they die (paid fallback) but every GB
# starts costing money — that's worth a nag of its own.
# - "paid proxy" (PROXY_URL): the per-GB last resort; dead = ingest at risk.
_PROXY_PROBE_INTERVAL = 1800 # seconds between probes (30 min)
_PROXY_RENOTIFY = 7200 # keep nagging every 2 h while it stays down
# 204-No-Content endpoint: the probe costs a handful of bytes of paid traffic.
# Plain HTTP on purpose: HTTPS through DataImpulse fails in httpx with an SSL
# record-layer error even when the proxy is healthy (yt-dlp's stack is fine
# with it), which would make an HTTPS probe cry wolf. An exhausted balance
# rejects the request before forwarding, so HTTP still detects the 407.
_PROXY_PROBE_URL = "http://www.google.com/generate_204"
# The static pool gets probed against YouTube itself, not google.com: on
# 28-aug-2026 YouTube refused the static IPs for hours ("Video unavailable" /
# bot-check) while google.com kept answering 204, so the watcher said UP and
# every job silently moved to the per-GB proxy ($14 that day). A healthy
# static must return the watch page with a playable player response; bytes
# through the statics are flat-rate, so the ~600 KB page is free.
_STATIC_PROBE_URL = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
_STATIC_OK_MARKERS = ('"playabilityStatus"', '"status":"OK"')
# The probe has to ask the way the DOWNLOAD asks, or it measures a question
# nobody in production is asking. Anonymously, a datacenter IP making ~400
# YouTube hits a day is rate-limited into "Sign in to confirm you're not a
# bot" — playabilityStatus comes back LOGIN_REQUIRED — while the very same IP
# serves every real download fine, because those carry these cookies.
# Measured 8-sep-2026 on all three statics: anonymous LOGIN_REQUIRED, with
# cookies OK, while proxy_usage showed 119 YouTube jobs on HD-static1 in 24 h
# and zero paid bytes. Without this the watcher cries wolf every 2 h and the
# alert tells you money is burning when none is.
_static_cookie_jar = None
_static_cookie_src = None
# The cookies themselves are a route: once Google rotates the session they
# came from, every download is anonymous whatever the file says, the statics
# get rate-limited into the bot-check one by one and jobs fall to per-GB
# billing. That is invisible to the pool probe (one IP still answering = UP)
# and to the ledger alert (it names the IPs, not the session). 30-sep-2026:
# ~900 MB paid in 70 min, cap hit, and the watcher had said nothing; yt-dlp
# had been warning "cookies are no longer valid" in every job log. The watch
# page carries the same signal yt-dlp reads: ytcfg "LOGGED_IN".
_COOKIE_TARGET = "YouTube session cookies"
_session_seen = {"logged_in": None}
def _note_session(body):
"""Record what the watch page says about the cookie session, if anything."""
import re as _re
m = _re.search(r'"LOGGED_IN":(true|false)', body or "")
if m:
_session_seen["logged_in"] = m.group(1) == "true"
def _probe_cookies():
"""The download's YOUTUBE_COOKIES as a jar httpx can send, or None.
Parsed once and cached (the probe runs every 30 minutes). Never logged:
the blob is a live YouTube session.
"""
global _static_cookie_jar, _static_cookie_src
raw = os.environ.get("YOUTUBE_COOKIES", "")
if not raw:
return None
if raw == _static_cookie_src:
return _static_cookie_jar
jar = None
try:
import tempfile
from http.cookiejar import MozillaCookieJar
# Pre-validate: handed a blob that is not a cookie file, the stdlib
# prints "http.cookiejar bug!" with a traceback before raising. That
# would land in the container log every 30 minutes, so recognise the
# shape ourselves (a Netscape record is 7 tab-separated fields).
if not any(len(ln.split("\t")) == 7
for ln in raw.splitlines() if ln and not ln.startswith("#")):
raise ValueError("not a Netscape cookie file")
body = raw if raw.lstrip().startswith("# Netscape") else \
"# Netscape HTTP Cookie File\n" + raw
path = os.path.join(tempfile.mkdtemp(), "yt_cookies.txt")
with open(path, "w") as fh:
fh.write(body if body.endswith("\n") else body + "\n")
jar = MozillaCookieJar(path)
jar.load(ignore_discard=True, ignore_expires=True)
except Exception as e:
print(f"\u26a0\ufe0f Static probe could not read YOUTUBE_COOKIES ({type(e).__name__}); "
f"probing anonymously, which YouTube bot-checks.")
jar = None
_static_cookie_src, _static_cookie_jar = raw, jar
return jar
def _playability(body):
"""The playabilityStatus value in a watch page, for the alert detail."""
import re as _re
m = _re.search(r'"playabilityStatus":\{"status":"([A-Z_]+)"', body or "")
return m.group(1) if m else "no player response"
_PROXY_STRIKES = 2 # consecutive failed probes before alerting
_watch_down = {} # target name -> down-since epoch
_watch_nag = {} # target name -> last-nag epoch
_watch_strikes = {} # target name -> consecutive failed probes
_PAID_TARGET = "paid proxy"
_STATIC_TARGET = "static proxy pool"
def _watch_targets():
"""[(name, [proxy urls])] — a target is up if ANY of its urls answers."""
targets = []
statics = [p.strip() for p in
os.environ.get("STATIC_PROXY_URLS", "").split(",") if p.strip()]
if statics:
targets.append((_STATIC_TARGET, statics))
paid = os.environ.get("PROXY_URL", "").strip()
if paid:
targets.append((_PAID_TARGET, [paid]))
return targets
async def _probe_one(proxy):
"""(ok, detail) for one request through one proxy.
The paid proxy keeps the plain-HTTP 204 probe (HTTPS through DataImpulse
breaks in httpx even when healthy). A static IP is probed against a real
YouTube watch page: answering is not enough, the page must carry a
playable player response, or the IP is flagged and every download is
about to fall through to per-GB billing.
"""
is_paid = proxy == os.environ.get("PROXY_URL", "").strip()
try:
import httpx
kwargs = {"proxy": proxy, "timeout": 20}
if not is_paid:
jar = _probe_cookies()
if jar is not None:
kwargs["cookies"] = jar
async with httpx.AsyncClient(**kwargs) as client:
resp = await client.get(_PROXY_PROBE_URL if is_paid else _STATIC_PROBE_URL,
follow_redirects=not is_paid)
if resp.status_code >= 400:
return False, f"HTTP {resp.status_code}"
if is_paid:
return True, ""
body = resp.text or ""
if "cookies" in kwargs:
_note_session(body)
if all(m in body for m in _STATIC_OK_MARKERS):
return True, ""
# Name what YouTube actually said. "LOGIN_REQUIRED" with cookies
# configured means the session expired (rotate them); the old wording
# blamed the IP for every case and sent us hunting the wrong thing.
return False, (f"YouTube answered but the video is not playable "
f"(playabilityStatus: {_playability(body)})")
except Exception as e:
return False, f"{type(e).__name__}: {e}"
def _watch_severity(name):
"""(emoji, headline, impact) for a route being down, judged by what is
actually affected. A dead fallback while the primary answers is a lost
safety net, not an outage: the first version of this alert said "jobs
will keep failing" for that case and read as the platform being down
(27-aug-2026, a single ReadTimeout on the paid proxy)."""
if name == _COOKIE_TARGET:
return "🟠", "YouTube session cookies expired", (
"YouTube no longer recognises the session in YOUTUBE_COOKIES, so every "
"download runs anonymously: the static IPs get bot-checked and jobs fall "
"to the PER-GB proxy (and fail once its daily budget is hit). Fix: log in "
"to YouTube in a private window, export the cookies, close the window "
"without logging out, update YOUTUBE_COOKIES and redeploy.")
static_down = bool(_watch_down.get(_STATIC_TARGET))
paid_down = bool(_watch_down.get(_PAID_TARGET))
other_configured = len(_watch_targets()) > 1
if not other_configured:
return "🔴", f"{name} DOWN", "It is the only YouTube route: YouTube-URL jobs are failing until it is fixed."
if static_down and paid_down:
return "🔴", "ALL YouTube proxies DOWN", "Static pool and paid proxy both fail: YouTube-URL jobs are failing. Direct file URLs are unaffected."
if name == _STATIC_TARGET:
return "🟠", "static proxy pool down, running on the paid proxy", ("YouTube jobs still work through the PER-GB paid proxy, so every download costs money until the statics are back.")
return "ℹ️", "paid proxy (fallback) not answering", ("No impact right now: the static pool is UP and carries all YouTube jobs. You only lose the safety net if the statics fail too.")
async def _watch_update(name, ok, detail):
"""Shared incident state machine: alert on down, nag, confirm recovery.
A route has to fail ``_PROXY_STRIKES`` probes in a row (30 min apart)
before anyone is paged: one ReadTimeout on a per-GB proxy is routine."""
now = time.time()
if ok:
_watch_strikes[name] = 0
if _watch_down.get(name):
mins = int((now - _watch_down[name]) / 60)
await send_admin_alert(
f"✅ {name} recovered",
f"The {name} answers again after ~{mins} min down.",
)
_watch_down[name] = None
_watch_nag[name] = 0.0
return
_watch_strikes[name] = _watch_strikes.get(name, 0) + 1
# A rotated session is deterministic (the same answer on every IP), so
# it does not get the benefit of the doubt a flaky proxy gets.
strikes = 1 if name == _COOKIE_TARGET else _PROXY_STRIKES
if not _watch_down.get(name):
if _watch_strikes[name] < strikes:
return # one miss: wait for the next probe before saying anything
_watch_down[name] = now
_watch_nag[name] = now
icon, headline, impact = _watch_severity(name)
await send_admin_alert(
f"{icon} {headline}",
f"{impact}\n\nThe {name} failed {strikes} probe(s) in a row "
f"({_PROXY_PROBE_INTERVAL // 60} min apart). This repeats every 2 h "
f"until it answers again.\n\nProbe error: {detail[:400]}",
)
elif now - _watch_nag[name] >= _PROXY_RENOTIFY:
_watch_nag[name] = now
hours = (now - _watch_down[name]) / 3600
icon, headline, impact = _watch_severity(name)
await send_admin_alert(
f"{icon} {headline} ({hours:.1f} h)",
f"{impact}\n\nProbe error: {detail[:400]}",
)
async def proxy_watch_tick():
"""One probe cycle over every configured route."""
# Paid-proxy events held back by the ledger's cooldown go out with the
# next tick at the latest (cloud/proxy_ledger.flush_alerts).
try:
from . import proxy_ledger
await proxy_ledger.flush_alerts()
except Exception:
pass
_session_seen["logged_in"] = None
for name, urls in _watch_targets():
ok, detail = False, "no urls"
for u in urls:
ok, detail = await _probe_one(u)
if ok:
break
await _watch_update(name, ok, detail)
# Judged from the watch pages the static probes just fetched with the
# cookies attached; nothing to say when no static answered at all.
if _probe_cookies() is not None and _session_seen["logged_in"] is not None:
await _watch_update(_COOKIE_TARGET, _session_seen["logged_in"],
'watch page ytcfg says "LOGGED_IN":false with the '
'configured cookies attached')
async def proxy_watch_loop():
"""Background task started from the app lifespan (managed mode only)."""
while True:
try:
await proxy_watch_tick()
except Exception as e:
print(f"⚠️ Proxy watch error: {e}")
await asyncio.sleep(_PROXY_PROBE_INTERVAL)

View file

@ -1,123 +0,0 @@
"""Server-side product events to OpenPanel.
The browser already reports the funnel (Signup, CheckoutStarted, Subscribed,
QuotaWall*, UpsellModal*). This module reports what the browser cannot be
trusted for:
* **Job outcomes.** Ad-blockers eat a chunk of client-side analytics, and the
interesting moment — a render finishing minutes later — often happens after
the tab is gone. Server-side is the only place these are complete.
* **Repeat usage.** The one number that decides whether the product retains:
on 26-jul-2026, 491 of 564 users who ever processed a video did it exactly
once. Every clip-quality fix shipped that day (1080p, captions, loudness) was
aimed at that 87%, and nothing in the stack could measure whether it moved.
``job_index`` on each event answers it directly: count distinct users at
index 1 versus index >= 2, before and after.
Fire-and-forget by design. Analytics must never slow down or break a job, so
every failure is swallowed and every send runs in the background.
"""
import asyncio
import os
import httpx
_TIMEOUT = 5.0
def _config():
"""(api_url, client_id, client_secret) or None when not configured.
Absent config is the normal state for self-hosted installs, so this stays
silent rather than warning.
"""
client_id = os.environ.get("OPENPANEL_CLIENT_ID", "").strip()
if not client_id:
return None
api = (os.environ.get("OPENPANEL_API_URL", "").strip()
or "https://api.openpanel.fotoexamen.com").rstrip("/")
return api, client_id, os.environ.get("OPENPANEL_CLIENT_SECRET", "").strip()
async def _post(payload):
cfg = _config()
if not cfg:
return
api, client_id, secret = cfg
headers = {"openpanel-client-id": client_id, "Content-Type": "application/json"}
if secret:
headers["openpanel-client-secret"] = secret
try:
async with httpx.AsyncClient(timeout=_TIMEOUT) as c:
await c.post(f"{api}/track", json=payload, headers=headers)
except Exception:
pass # analytics must never surface into a job
def track(name: str, user_id=None, **props):
"""Queue an event. Returns immediately; never raises.
``user_id`` becomes OpenPanel's profileId, which is what makes retention
and repeat-usage questions answerable per user.
"""
if not _config():
return
payload = {
"type": "track",
"payload": {
"name": name,
"properties": {k: v for k, v in props.items() if v is not None},
},
}
if user_id is not None:
payload["payload"]["profileId"] = str(user_id)
try:
asyncio.get_running_loop().create_task(_post(payload))
except RuntimeError:
pass # no loop (CLI/self-host path) — nothing to report to anyway
def track_revenue(user_id, amount_cents, currency="usd", **props):
"""Queue a ``revenue`` event in OpenPanel's native shape. Never raises.
``amount_cents`` is Stripe's integer minor-unit amount, negative for a
refund. OpenPanel stores ``__revenue`` in minor units and divides by 100 in
its own views (Overview card, revenue trend), so a $59 sale is sent as 5900;
``amount`` (major units) rides along because custom reports read raw
properties without that formatting. Same contract as every other product
on this OpenPanel instance, so revenue is comparable across them.
"""
try:
cents = int(amount_cents or 0)
except (TypeError, ValueError):
return
if cents == 0:
return
props["__revenue"] = cents
props["amount"] = round(cents / 100, 2)
props["currency"] = (currency or "usd").upper()
track("revenue", user_id=user_id, **props)
def acquisition_properties(attribution):
"""Flatten a ``SignupAttribution`` row (or any object with the same
attributes, or None) into the props a revenue event carries.
A Stripe webhook has no browser session, so the only way to know where a
paying user came from is the first-touch snapshot recorded at sign-up.
``channel`` collapses it to one label: utm_source > referring host > direct.
"""
if attribution is None:
return {"channel": "direct"}
get = lambda k: (getattr(attribution, k, None) or "").strip() or None # noqa: E731
created = getattr(attribution, "created_at", None)
props = {
"channel": get("utm_source") or get("referrer_host") or "direct",
"utm_source": get("utm_source"),
"utm_medium": get("utm_medium"),
"utm_campaign": get("utm_campaign"),
"referrer": get("referrer_host"),
"landing_path": get("landing_path"),
"signup_date": created.isoformat() if hasattr(created, "isoformat") else None,
}
return {k: v for k, v in props.items() if v}

View file

@ -1,147 +0,0 @@
"""User API keys (``osk_...``) for programmatic access: MCP clients, scripts, CI.
Two halves:
- Management endpoints (create / list / revoke). These require a SESSION JWT,
never an API key — a leaked key must not be able to mint replacement keys
for the same account.
- ``user_id_for_key``: the resolver cloud/auth.py calls so a Bearer
``osk_...`` (or ``X-API-Key``) authenticates like a session everywhere else.
Quota, entitlement and job ownership then apply unchanged.
"""
import hashlib
import secrets
from datetime import datetime, timezone, timedelta
from typing import Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select, func, and_
from . import database
from .models import ApiKey
router = APIRouter()
KEY_PREFIX = "osk_"
MAX_ACTIVE_KEYS = 10
# last_used_at is informational; refreshing it on every /api/status poll would
# write the row hundreds of times per job for no extra signal.
LAST_USED_REFRESH = timedelta(minutes=5)
def _now():
return datetime.now(timezone.utc)
def hash_key(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
def generate_key() -> tuple[str, str, str]:
"""Return (raw, sha256, display_prefix) for a fresh key."""
raw = KEY_PREFIX + secrets.token_urlsafe(32)
return raw, hash_key(raw), raw[: len(KEY_PREFIX) + 6]
def looks_like_key(token: str) -> bool:
return isinstance(token, str) and token.startswith(KEY_PREFIX)
async def user_id_for_key(raw: str) -> Optional[object]:
"""Resolve a raw ``osk_`` token to its owner's user id, or None.
Refreshes ``last_used_at`` at most every LAST_USED_REFRESH so status polls
don't turn every request into a DB write.
"""
if not looks_like_key(raw):
return None
token_hash = hash_key(raw)
async with database.session() as session:
async with session.begin():
row = (await session.execute(
select(ApiKey).where(ApiKey.key_hash == token_hash)
)).scalar_one_or_none()
if row is None or row.revoked_at is not None:
return None
if row.last_used_at is None or _now() - row.last_used_at > LAST_USED_REFRESH:
row.last_used_at = _now()
return row.user_id
# --------------------------------------------------------------------------- #
# Management endpoints (session JWT only)
# --------------------------------------------------------------------------- #
async def _session_user(request: Request):
"""The signed-in user, refusing API-key auth for key management."""
from .auth import get_current_user_required
auth = request.headers.get("Authorization", "")
if looks_like_key(auth[7:].strip()) or looks_like_key(request.headers.get("X-API-Key", "")):
raise HTTPException(status_code=403,
detail="API keys cannot manage API keys. Sign in to the dashboard.")
return await get_current_user_required(request)
class CreateKeyRequest(BaseModel):
name: Optional[str] = None
@router.post("/api/keys")
async def create_key(payload: CreateKeyRequest, request: Request):
user = await _session_user(request)
raw, token_hash, prefix = generate_key()
name = (payload.name or "").strip()[:60] or "API key"
async with database.session() as session:
async with session.begin():
active = (await session.execute(
select(func.count(ApiKey.id)).where(and_(
ApiKey.user_id == user.id, ApiKey.revoked_at.is_(None),
))
)).scalar_one()
if active >= MAX_ACTIVE_KEYS:
raise HTTPException(status_code=400,
detail=f"Limit of {MAX_ACTIVE_KEYS} active keys reached. Revoke one first.")
row = ApiKey(user_id=user.id, name=name, key_hash=token_hash, prefix=prefix)
session.add(row)
await session.flush()
key_id = row.id
# The raw key appears here once and is never retrievable again.
return {"id": str(key_id), "name": name, "prefix": prefix, "key": raw}
@router.get("/api/keys")
async def list_keys(request: Request):
user = await _session_user(request)
async with database.session() as session:
rows = list((await session.execute(
select(ApiKey).where(ApiKey.user_id == user.id)
.order_by(ApiKey.created_at.desc()).limit(100)
)).scalars())
return {"keys": [{
"id": str(k.id),
"name": k.name,
"prefix": k.prefix,
"created_at": k.created_at.isoformat() if k.created_at else None,
"last_used_at": k.last_used_at.isoformat() if k.last_used_at else None,
"revoked": k.revoked_at is not None,
} for k in rows]}
@router.delete("/api/keys/{key_id}")
async def revoke_key(key_id: str, request: Request):
user = await _session_user(request)
import uuid
try:
key_uuid = uuid.UUID(key_id)
except ValueError:
raise HTTPException(status_code=404, detail="Key not found")
async with database.session() as session:
async with session.begin():
row = (await session.execute(
select(ApiKey).where(ApiKey.id == key_uuid)
)).scalar_one_or_none()
if row is None or str(row.user_id) != str(user.id):
raise HTTPException(status_code=404, detail="Key not found")
if row.revoked_at is None:
row.revoked_at = _now()
return {"ok": True}

View file

@ -1,398 +0,0 @@
"""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
from .config import settings
from . import config, database, metering, email_policy
from .models import User, MagicLinkToken, UploadPostProfile, SignupAttribution
router = APIRouter()
JWT_ALGO = "HS256"
JWT_TTL_DAYS = 30
MAGIC_TTL_MINUTES = 15
MAGIC_RATE_LIMIT = 3 # per email
MAGIC_RATE_LIMIT_IP = 10 # per IP, any email — bots rotate addresses, not IPs
MAGIC_RATE_WINDOW_MIN = 15
# Only accept attribution for an account this young. Both sign-in flows post it
# right after the redirect, so anything older is a returning user whose "source"
# would be their re-entry, not their sign-up.
ATTRIBUTION_MAX_AGE_MIN = 60
ATTRIBUTION_FIELD_MAX = 500 # client-supplied strings are truncated to this
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 with an active plan, any top-up credit, or the
# free monthly allowance (Google-authenticated accounts only).
free = sub is None and metering.free_plan_eligible(user)
entitled = bool(sub is not None or topup_remaining > 0 or free)
return CurrentUser(
id=user.id,
email=user.email,
entitled=entitled,
plan=sub.plan if sub else ("free" if free 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.
Accepts either a session JWT (``Bearer <jwt>``) or a user API key
(``Bearer osk_...`` / ``X-API-Key``). A key authenticates as its owner, so
quota, entitlement and job ownership apply to agents exactly as to the
dashboard — no parallel auth path to keep in sync.
"""
from . import api_keys
auth = request.headers.get("Authorization", "")
token = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
api_token = token if api_keys.looks_like_key(token) else request.headers.get("X-API-Key", "")
if api_keys.looks_like_key(api_token):
user_id = await api_keys.user_id_for_key(api_token)
if user_id is None:
return None
async with database.session() as session:
return await _load_current_user(session, user_id)
if not token:
return None
payload = _decode_jwt(token)
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
disposable_msg = (
"That email provider isn't supported. Please use a permanent "
"address (Gmail, Outlook, iCloud…) or sign in with Google.")
# Block temp-mail before doing anything else — the free plan is open to
# email accounts now, so disposable domains would be a free-minute farm.
if email_policy.is_disposable(payload.email):
raise HTTPException(status_code=400, detail=disposable_msg)
# Normalize (strip +tags / Gmail dots) so aliases can't mint extra accounts.
email = email_policy.normalize_email(payload.email)
# Best-effort: uvicorn resolves this from X-Forwarded-For (trusted "*" in
# the Dockerfile), which a client can forge — good enough against the bots
# we actually see, but not a security boundary.
client_ip = request.client.host if request.client else None
raw_token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
async with database.session() as session:
async with session.begin():
window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN)
recent, recent_ip = (await session.execute(
select(
func.count(MagicLinkToken.id).filter(MagicLinkToken.email == email),
func.count(MagicLinkToken.id).filter(MagicLinkToken.request_ip == client_ip),
).where(MagicLinkToken.created_at >= window_start)
)).one()
if recent >= MAGIC_RATE_LIMIT:
raise HTTPException(status_code=429, detail="Too many login attempts. Try again in a few minutes.")
if client_ip and recent_ip >= MAGIC_RATE_LIMIT_IP:
raise HTTPException(status_code=429, detail=(
"Too many sign-in attempts from your network. Try again in a few minutes."))
# Recorded BEFORE the MX gate so rejected attempts still count
# toward both limits — otherwise a junk-domain flood never trips
# them. The raw token is only ever emailed after the gate passes.
session.add(MagicLinkToken(
email=email,
token_hash=token_hash,
expires_at=_now() + timedelta(minutes=MAGIC_TTL_MINUTES),
request_ip=client_ip,
))
account_exists = (await session.execute(
select(User.id).where(User.email == email)
)).scalar_one_or_none() is not None
# The static list can't keep up with rotating temp-mail domains, and bots
# sign up with domains that don't receive mail at all — both come back as
# bounces that flood the support inbox and burn sender reputation. The
# gate protects sign-UP only: an existing account must keep working even
# if its domain's MX later matches the disposable list or resolves badly.
if not account_exists:
verdict = await email_policy.mx_verdict(email)
if verdict == email_policy.MX_DISPOSABLE:
raise HTTPException(status_code=400, detail=disposable_msg)
if verdict == email_policy.MX_NONE:
raise HTTPException(status_code=400, detail=(
"That email domain can't receive mail. Please double-check the address."))
else:
# The account keeps signing in, but eligibility for the free minutes
# is re-checked: a temp-mail front whose MX joined disposable_mx.txt
# after the account was made would otherwise keep its free plan
# forever (568 such accounts in sep-2026).
await _deny_free_if_disposable_mx(email)
link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}"
await send_magic_link_email(email, link)
return {"ok": True}
async def _deny_free_if_disposable_mx(email: str):
"""Mark an existing account's free plan withdrawn when its mail domain's
MX is a known temp-mail host. Best effort: never blocks the sign-in."""
try:
if await email_policy.mx_verdict(email) != email_policy.MX_DISPOSABLE:
return
from sqlalchemy import update
async with database.session() as session:
async with session.begin():
await session.execute(
update(User)
.where(User.email == email, User.free_plan_denied.is_(None))
.values(free_plan_denied="disposable_mx"))
except Exception as e:
print(f"⚠️ free-plan MX re-check failed: {e}")
async def purge_stale_magic_tokens():
"""Drop token rows too old to matter for auth or rate limiting.
Called from the retention sweeper: without it the table grows with every
sign-in forever and the rate-limit counts scan an ever-larger window.
"""
from sqlalchemy import delete
cutoff = _now() - timedelta(days=30)
async with database.session() as session:
async with session.begin():
await session.execute(
delete(MagicLinkToken).where(MagicLinkToken.created_at < cutoff))
@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:
from .account import free_plan_denial_for_signup
user = User(email=email, last_login_at=_now(),
free_plan_denied=await free_plan_denial_for_signup(session, email))
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}}
# --------------------------------------------------------------------------- #
# Signup attribution
# --------------------------------------------------------------------------- #
class AttributionPayload(BaseModel):
referrer: Optional[str] = None
landing_path: Optional[str] = None
utm_source: Optional[str] = None
utm_medium: Optional[str] = None
utm_campaign: Optional[str] = None
def _clip(value: Optional[str]) -> Optional[str]:
if not value:
return None
value = value.strip()
return value[:ATTRIBUTION_FIELD_MAX] or None
def _referrer_host(referrer: Optional[str]) -> Optional[str]:
"""Bare host of the referrer, the key we actually group by."""
if not referrer:
return None
try:
from urllib.parse import urlparse
host = (urlparse(referrer).hostname or "").lower()
except Exception:
return None
return host or None
@router.post("/api/auth/attribution")
async def record_attribution(payload: AttributionPayload, request: Request):
"""Record where a brand-new account came from. First touch wins.
Fire-and-forget from the client right after sign-in: it never fails the
sign-up, it just returns ``recorded: false`` when the row already exists or
the account is too old to be a genuine sign-up.
"""
from sqlalchemy.dialects.postgresql import insert as pg_insert
user = await get_current_user_required(request)
async with database.session() as session:
async with session.begin():
row = await session.get(User, user.id)
if row is None or row.created_at is None:
return {"ok": True, "recorded": False}
if _now() - row.created_at > timedelta(minutes=ATTRIBUTION_MAX_AGE_MIN):
return {"ok": True, "recorded": False}
referrer = _clip(payload.referrer)
# ON CONFLICT DO NOTHING keeps first touch even if the client posts
# twice concurrently (two tabs finishing the same redirect).
result = await session.execute(
pg_insert(SignupAttribution).values(
user_id=user.id,
referrer=referrer,
referrer_host=_referrer_host(referrer),
landing_path=_clip(payload.landing_path),
utm_source=_clip(payload.utm_source),
utm_medium=_clip(payload.utm_medium),
utm_campaign=_clip(payload.utm_campaign),
).on_conflict_do_nothing(index_elements=["user_id"])
)
return {"ok": True, "recorded": result.rowcount > 0}
# --------------------------------------------------------------------------- #
# /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"]
from .onboarding import is_pending as _survey_pending
survey_pending = await _survey_pending(session, user)
# Report the entitling subscription when there is one; otherwise fall back to
# a row that needs the customer's attention (card declined, payment never
# finished). Without this a past_due customer sees a plain free account and
# never learns their card failed. `plan` stays as computed — the entitlement
# really is free — so the UI shows "free plan" plus the warning badge.
attention = bal["_sub_row"]
if attention is not None and attention.status not in config.BILLING_ATTENTION_STATES:
attention = None
shown = sub or attention
return {
"user": {"id": str(user.id), "email": user.email},
"entitled": user.entitled,
"plan": bal["plan"],
"status": shown.status if shown else None,
"interval": shown.interval if shown else None,
"period_end": bal["period_end"].isoformat() if bal["period_end"] else None,
"cancel_at_period_end": shown.cancel_at_period_end if shown else False,
# Drives the "Manage billing" route in the UI: any Stripe relationship,
# live or broken, must keep the portal reachable.
"has_billing_account": bool(sub or attention),
"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,
"onboarding_survey_pending": survey_pending,
}

View file

@ -1,873 +0,0 @@
"""Autopilot: clip every new video on the user's YouTube channel, by itself.
The user connects YouTube once (the same Upload-Post profile the dashboard
already uses for posting) and switches Autopilot on. From then on:
1. A poller lists the channel's latest uploads through Upload-Post
(``GET /api/uploadposts/media?platform=youtube``). That endpoint reads the
channel's uploads playlist with the user's own OAuth token, so it sees
videos uploaded straight to YouTube, not just ones posted through us, and
no scraping is involved.
2. A video published after Autopilot was switched on becomes a job on the
normal pipeline: an in-process ``POST /api/process`` with the video URL,
authenticated as the user. Metering, the minute reservation, the probe, the
per-plan job limit and the download proxies all apply exactly as when the
user pastes the link themselves, so nothing here has to be kept in sync.
3. When the job finishes, ``on_job_finished`` (called from app.py's job
wrapper) records the outcome, emails the user, and, if they asked for it,
schedules the best clips on their connected accounts, one a day.
Why this exists: most subscribers used the product on one day and never came
back (6 of 33 retained subscribers had used it on 3+ distinct days, sep-2026).
Value that arrives every week without the user doing anything is the lever.
Guard rails, each one a cost that would otherwise scale with the channel:
- only videos published after ``enabled_at`` and at most ``MAX_VIDEO_AGE`` old,
so switching it on never processes the back catalogue;
- ``DAILY_AUTO_LIMIT`` automatic jobs per user per 24 h (downloads go through
the shared proxy pool);
- ``max_minutes`` per video (the first N minutes of a long stream), so one
two-hour live does not empty the month;
- YouTube Shorts are skipped: they already are short-form.
"""
import asyncio
import os
import uuid
from datetime import datetime, timedelta, timezone
from typing import Iterable, List, Optional
import httpx
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import and_, delete, func, select, update
from sqlalchemy.exc import IntegrityError
from . import database
from .config import settings
from .models import AutopilotRun, AutopilotSettings, UploadPostProfile, User
router = APIRouter()
API_BASE = "https://api.upload-post.com/api"
PAID_PLANS = ("starter", "creator", "pro")
PUBLISH_PLATFORMS = ("tiktok", "instagram", "youtube")
MAX_MINUTES_CHOICES = (10, 20, 30, 45, 60, 90)
DEFAULT_MAX_MINUTES = 30
DEFAULT_CLIPS_TO_PUBLISH = 3
MAX_CLIPS_TO_PUBLISH = 5
DEFAULT_PUBLISH_HOUR = 17
TICK_SECONDS = 300 # how often the loop wakes up
CHECK_EVERY = timedelta(minutes=55) # per-user channel check interval
MAX_VIDEO_AGE = timedelta(days=3) # older uploads are never picked automatically
DAILY_AUTO_LIMIT = 1 # automatic jobs per user per rolling 24 h
MANUAL_DAILY_LIMIT = 5 # "clip this video" clicks per user per 24 h
STALE_RUN_AFTER = timedelta(hours=6) # a job that never reported back
CHANNEL_LIST_LIMIT = 12
# Run statuses. "queued" only exists between the INSERT that claims a video and
# the /api/process answer; "processing" means a job id exists.
QUEUED, PROCESSING, COMPLETED, FAILED, SKIPPED = (
"queued", "processing", "completed", "failed", "skipped")
_app = None # the FastAPI app, for in-process calls (set by start())
_is_active = None # callable: False while this instance drains for a deploy
_task = None # strong ref: the loop only keeps weak references to tasks
_bg_tasks = set()
# --------------------------------------------------------------------------- #
# Pure helpers (unit-tested without a database)
# --------------------------------------------------------------------------- #
def parse_ts(value) -> Optional[datetime]:
"""An Upload-Post/YouTube timestamp ('2026-09-22T10:01:35Z') as aware UTC."""
if not value:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def pick_new_videos(media: Iterable[dict], baseline: Optional[datetime],
seen_ids: set, now: datetime,
max_age: timedelta = MAX_VIDEO_AGE) -> List[dict]:
"""Channel uploads Autopilot should clip now, oldest first.
A video qualifies when it was published after the baseline (the moment
Autopilot was switched on), is not older than ``max_age``, and has not been
picked before. Items without an id or a parseable timestamp are ignored:
better to miss one than to clip the back catalogue.
"""
if baseline is None:
return []
out = []
for item in media or []:
vid = (item or {}).get("id")
published = parse_ts((item or {}).get("timestamp"))
if not vid or published is None or vid in seen_ids:
continue
if published <= baseline or now - published > max_age:
continue
out.append(item)
out.sort(key=lambda m: parse_ts(m.get("timestamp")))
return out
def rank_clips(clips: List[dict], n: int) -> List[int]:
"""Indices of the ``n`` clips worth publishing, best first.
``predicted_score`` is the second-pass virality score the selector already
computes; clips without one keep their pipeline order after the scored ones.
"""
if n <= 0 or not clips:
return []
def score(i):
try:
return float(clips[i].get("predicted_score"))
except (TypeError, ValueError):
return float("-inf")
order = sorted(range(len(clips)), key=lambda i: (-score(i), i))
return order[:n]
def schedule_slots(now: datetime, n: int, hour: int = DEFAULT_PUBLISH_HOUR,
tz_name: Optional[str] = None) -> List[str]:
"""``n`` local datetimes (ISO, no offset) at ``hour``, one per day.
Starts today if the slot is still at least an hour away, else tomorrow.
Upload-Post takes the local wall time plus an IANA ``timezone`` parameter.
"""
tz = _zone(tz_name)
local_now = now.astimezone(tz)
first = local_now.replace(hour=hour % 24, minute=0, second=0, microsecond=0)
if first - local_now < timedelta(hours=1):
first += timedelta(days=1)
return [(first + timedelta(days=k)).strftime("%Y-%m-%dT%H:%M:%S") for k in range(n)]
def _zone(tz_name: Optional[str]):
try:
from zoneinfo import ZoneInfo
return ZoneInfo(tz_name) if tz_name else timezone.utc
except Exception:
return timezone.utc
def outcome_from_process(status_code: int, body) -> dict:
"""Map an /api/process answer to what the run becomes.
Returns ``{"status", "reason", "job_id", "retry"}``. ``retry`` means the
claim should be dropped and the video tried again on a later tick (the
user is at their simultaneous-job limit, or the server hiccuped).
"""
body = body if isinstance(body, dict) else {}
detail = body.get("detail")
if status_code == 200:
if body.get("needs_confirmation"):
return {"status": SKIPPED, "reason": "low_quality", "job_id": None, "retry": False}
if body.get("job_id"):
return {"status": PROCESSING, "reason": None, "job_id": body["job_id"], "retry": False}
return {"status": FAILED, "reason": "no_job_id", "job_id": None, "retry": False}
if status_code == 402:
return {"status": SKIPPED, "reason": "out_of_minutes", "job_id": None, "retry": False}
if status_code == 429:
return {"status": QUEUED, "reason": "busy", "job_id": None, "retry": True}
if status_code == 400:
text = str(detail or "").lower()
if "short-form" in text or "only" in text and "long" in text:
return {"status": SKIPPED, "reason": "too_short", "job_id": None, "retry": False}
return {"status": SKIPPED, "reason": "unavailable", "job_id": None, "retry": False}
if status_code == 403:
return {"status": SKIPPED, "reason": "url_ingest_disabled", "job_id": None, "retry": False}
if status_code >= 500:
return {"status": QUEUED, "reason": "server_error", "job_id": None, "retry": True}
return {"status": FAILED, "reason": f"http_{status_code}", "job_id": None, "retry": False}
def clean_platforms(values) -> List[str]:
"""Keep the platforms Autopilot can publish to, in a stable order."""
wanted = {str(v).lower() for v in (values or [])}
return [p for p in PUBLISH_PLATFORMS if p in wanted]
def eligible(user) -> bool:
"""Autopilot is part of the paid plans (it spends minutes on its own)."""
return bool(user is not None and getattr(user, "entitled", False)
and getattr(user, "plan", None) in PAID_PLANS)
# --------------------------------------------------------------------------- #
# Upload-Post
# --------------------------------------------------------------------------- #
class ChannelError(Exception):
"""The channel could not be listed; ``code`` is shown to the user."""
def __init__(self, code: str):
super().__init__(code)
self.code = code
def _headers():
return {"Authorization": f"Apikey {settings.managed_upload_post_key}"}
async def fetch_channel_videos(profile: str, limit: int = CHANNEL_LIST_LIMIT) -> List[dict]:
"""The latest uploads of the YouTube channel connected to ``profile``."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API_BASE}/uploadposts/media", headers=_headers(),
params={"platform": "youtube", "user": profile, "limit": limit})
try:
data = resp.json()
except ValueError:
data = {}
if resp.status_code == 200 and data.get("success") is not False:
return [m for m in (data.get("media") or []) if isinstance(m, dict)]
message = str(data.get("error") or data.get("message") or "").lower()
if "not have a youtube" in message or "not associated" in message:
raise ChannelError("youtube_not_connected")
if "reauth" in message or "expired" in message or "revoked" in message \
or resp.status_code in (401, 403):
raise ChannelError("youtube_reauth_required")
raise ChannelError("channel_unavailable")
async def fetch_social_accounts(profile: str) -> dict:
"""``{platform: {handle, display_name, reauth_required}}`` for a profile."""
async with httpx.AsyncClient(timeout=20) as client:
resp = await client.get(f"{API_BASE}/uploadposts/users/{profile}",
headers=_headers())
if resp.status_code != 200:
return {}
try:
accounts = ((resp.json() or {}).get("profile") or {}).get("social_accounts") or {}
except ValueError:
return {}
out = {}
for platform, info in accounts.items():
if isinstance(info, dict) and info:
out[platform] = {
"handle": info.get("handle"),
"display_name": info.get("display_name"),
"reauth_required": bool(info.get("reauth_required")),
}
return out
async def is_youtube_private(video_id: str) -> bool:
"""True when the video is private on YouTube.
oEmbed answers 401/403 for a private video and 200 for a public or
unlisted one. It has to run BEFORE is_youtube_short: /shorts/<id> of a
private video also answers 200, so a private upload read as "already a
short". A private video cannot be clipped at all: yt-dlp gets "Private
video", and the YouTube Data API behind Upload-Post lists the owner's
uploads but never serves the media file.
"""
try:
async with httpx.AsyncClient(timeout=10) as client:
resp = await client.get("https://www.youtube.com/oembed", params={
"url": f"https://www.youtube.com/watch?v={video_id}", "format": "json"})
return resp.status_code in (401, 403)
except Exception:
return False
async def is_youtube_short(video_id: str) -> bool:
"""True when YouTube serves this id as a Short.
``/shorts/<id>`` answers 200 for a Short and redirects to ``/watch`` for a
regular video. From the prod servers (EU) YouTube first redirects every
request to consent.youtube.com, which read as "not a Short" and let a Short
through (22-sep-2026); the SOCS/CONSENT cookies skip that page. Any other
answer (a bot check) still reads as "not a Short" and the normal
pipeline's own too-short gate applies.
"""
try:
async with httpx.AsyncClient(timeout=10, follow_redirects=False,
cookies={"SOCS": "CAI", "CONSENT": "YES+"}) as client:
resp = await client.head(f"https://www.youtube.com/shorts/{video_id}")
return resp.status_code == 200
except Exception:
return False
async def _upload_clip(profile: str, file_path: str, clip: dict, platforms: List[str],
when: str, tz_name: str) -> bool:
"""Schedule one clip on Upload-Post. Mirrors app.post_to_socials' payload."""
loop = asyncio.get_event_loop()
content = await loop.run_in_executor(None, _read_bytes, file_path)
title = clip.get("video_title_for_youtube_short") or clip.get("title") or "New short"
description = (clip.get("video_description_for_instagram")
or clip.get("video_description_for_tiktok") or title)
data = {
"user": profile,
"title": title,
"platform[]": platforms,
"async_upload": "true",
"scheduled_date": when,
"timezone": tz_name or "UTC",
}
if "tiktok" in platforms:
data["tiktok_title"] = description
data["post_mode"] = os.environ.get("TIKTOK_POST_MODE", "MEDIA_UPLOAD").strip()
if "instagram" in platforms:
data["instagram_title"] = description
data["media_type"] = "REELS"
if "youtube" in platforms:
data["youtube_title"] = title
data["youtube_description"] = description
data["privacyStatus"] = "public"
files = {"video": (os.path.basename(file_path), content, "video/mp4")}
async with httpx.AsyncClient(timeout=300) as client:
resp = await client.post(f"{API_BASE}/upload", headers=_headers(),
data=data, files=files)
if resp.status_code not in (200, 201, 202):
print(f"⚠️ Autopilot publish failed ({resp.status_code}): {resp.text[:300]}")
return False
return True
def _read_bytes(path):
with open(path, "rb") as f:
return f.read()
# --------------------------------------------------------------------------- #
# Database helpers
# --------------------------------------------------------------------------- #
async def _load_user(user_id):
from .auth import _load_current_user
async with database.session() as s:
return await _load_current_user(s, user_id)
async def _profile_for(user_id) -> Optional[str]:
async with database.session() as s:
prof = await s.get(UploadPostProfile, user_id)
return prof.profile_username if prof else None
async def _get_settings(user_id) -> Optional[AutopilotSettings]:
async with database.session() as s:
return await s.get(AutopilotSettings, user_id)
async def _set_check_result(user_id, error: Optional[str]):
async with database.session() as s:
async with s.begin():
await s.execute(update(AutopilotSettings)
.where(AutopilotSettings.user_id == user_id)
.values(last_checked_at=func.now(), last_error=error))
async def _count_recent(user_id, trigger: str, since: datetime) -> int:
async with database.session() as s:
return (await s.execute(
select(func.count(AutopilotRun.id)).where(
AutopilotRun.user_id == user_id,
AutopilotRun.trigger == trigger,
AutopilotRun.created_at >= since,
AutopilotRun.status.in_((QUEUED, PROCESSING, COMPLETED, FAILED)),
))).scalar_one()
async def _seen_ids(user_id, video_ids) -> set:
if not video_ids:
return set()
async with database.session() as s:
rows = await s.execute(select(AutopilotRun.video_id).where(
AutopilotRun.user_id == user_id, AutopilotRun.video_id.in_(list(video_ids))))
return {r[0] for r in rows}
async def _claim(user_id, video: dict, trigger: str) -> Optional[uuid.UUID]:
"""INSERT the run row; the unique constraint makes the claim exclusive."""
run_id = uuid.uuid4()
try:
async with database.session() as s:
async with s.begin():
s.add(AutopilotRun(
id=run_id, user_id=user_id, video_id=video["id"],
video_url=video.get("permalink") or f"https://www.youtube.com/watch?v={video['id']}",
video_title=(video.get("caption") or "")[:300] or None,
thumbnail_url=video.get("thumbnail_url"),
published_at=parse_ts(video.get("timestamp")),
trigger=trigger, status=QUEUED,
))
except IntegrityError:
return None
return run_id
async def _update_run(run_id, **values):
async with database.session() as s:
async with s.begin():
await s.execute(update(AutopilotRun).where(AutopilotRun.id == run_id).values(**values))
async def _drop_run(run_id):
async with database.session() as s:
async with s.begin():
await s.execute(delete(AutopilotRun).where(AutopilotRun.id == run_id))
# --------------------------------------------------------------------------- #
# Submitting a job through the normal pipeline
# --------------------------------------------------------------------------- #
async def _submit(user_id, email, run_id, video_url: str, max_minutes: int) -> dict:
"""``POST /api/process`` in-process, as the user, and record the outcome."""
from .auth import issue_jwt
if _app is None:
raise RuntimeError("autopilot not started")
token = issue_jwt(user_id, email)
base = os.environ.get("PUBLIC_API_URL", "").rstrip("/") or "http://localhost"
body = {
"url": video_url,
# Recorded once when the user switched Autopilot on for their own
# channel (rights_ack_at); the pipeline wants it per job.
"acknowledged": True,
"max_minutes": max_minutes,
"auto_hook": "1",
"auto_hook_style": "classic",
}
try:
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=_app),
base_url=base, timeout=600) as client:
resp = await client.post(
"/api/process", json=body,
headers={"Authorization": f"Bearer {token}",
"User-Agent": "OpenShorts-Autopilot/1.0"})
try:
payload = resp.json()
except ValueError:
payload = {}
outcome = outcome_from_process(resp.status_code, payload)
except Exception as e:
print(f"⚠️ Autopilot submit error for {video_url}: {e}")
outcome = {"status": QUEUED, "reason": "server_error", "job_id": None, "retry": True}
if outcome["retry"]:
await _drop_run(run_id) # try this video again on a later tick
else:
await _update_run(run_id, status=outcome["status"], reason=outcome["reason"],
job_id=outcome["job_id"])
print(f"🤖 Autopilot {video_url} -> {outcome['status']}"
f"{' (' + outcome['reason'] + ')' if outcome['reason'] else ''}")
return outcome
async def _start_video(user, video: dict, trigger: str, max_minutes: int) -> dict:
"""Claim a channel video and push it into the pipeline."""
run_id = await _claim(user.id, video, trigger)
if run_id is None:
return {"status": "duplicate", "reason": "already_picked", "job_id": None}
if await is_youtube_private(video["id"]):
if trigger != "manual":
# Scheduled uploads are often private until they go live: let the
# next poll pick the video up again instead of skipping it for good.
async with database.session() as s:
async with s.begin():
await s.execute(delete(AutopilotRun).where(AutopilotRun.id == run_id))
return {"status": SKIPPED, "reason": "private_video", "job_id": None}
await _update_run(run_id, status=SKIPPED, reason="private_video")
return {"status": SKIPPED, "reason": "private_video", "job_id": None}
if await is_youtube_short(video["id"]):
await _update_run(run_id, status=SKIPPED, reason="youtube_short")
return {"status": SKIPPED, "reason": "youtube_short", "job_id": None}
url = video.get("permalink") or f"https://www.youtube.com/watch?v={video['id']}"
return await _submit(user.id, user.email, run_id, url, max_minutes)
# --------------------------------------------------------------------------- #
# The poller
# --------------------------------------------------------------------------- #
async def check_user(user_id) -> Optional[str]:
"""One channel check for one user. Returns an error code or None."""
prefs = await _get_settings(user_id)
if prefs is None or not prefs.enabled:
return None
user = await _load_user(user_id)
if not eligible(user):
await _set_check_result(user_id, "plan_required")
return "plan_required"
profile = await _profile_for(user_id)
if not profile:
await _set_check_result(user_id, "youtube_not_connected")
return "youtube_not_connected"
try:
media = await fetch_channel_videos(profile)
except ChannelError as e:
await _set_check_result(user_id, e.code)
return e.code
now = datetime.now(timezone.utc)
seen = await _seen_ids(user_id, [m.get("id") for m in media if m.get("id")])
fresh = pick_new_videos(media, parse_ts(prefs.enabled_at), seen, now)
budget = DAILY_AUTO_LIMIT - await _count_recent(user_id, "auto", now - timedelta(days=1))
for video in fresh:
if budget <= 0:
break # the rest stay unclaimed and are picked up on a later day
result = await _start_video(user, video, "auto", prefs.max_minutes or DEFAULT_MAX_MINUTES)
if result["status"] in (PROCESSING, FAILED):
budget -= 1
if result.get("reason") in ("out_of_minutes", "busy"):
break # nothing else will fit right now
await _set_check_result(user_id, None)
return None
async def _expire_stale_runs():
"""A job that never reported back (container killed past its resume
attempts) must not show 'processing' forever."""
cutoff = datetime.now(timezone.utc) - STALE_RUN_AFTER
async with database.session() as s:
async with s.begin():
await s.execute(update(AutopilotRun).where(
AutopilotRun.status.in_((QUEUED, PROCESSING)),
AutopilotRun.updated_at < cutoff,
).values(status=FAILED, reason="timeout"))
async def poll_once():
await _expire_stale_runs()
due_before = datetime.now(timezone.utc) - CHECK_EVERY
async with database.session() as s:
user_ids = [r[0] for r in await s.execute(
select(AutopilotSettings.user_id).where(
AutopilotSettings.enabled.is_(True),
(AutopilotSettings.last_checked_at.is_(None))
| (AutopilotSettings.last_checked_at < due_before),
).order_by(AutopilotSettings.last_checked_at.asc().nullsfirst()))]
for uid in user_ids:
if _is_active is not None and not _is_active():
return # draining for a deploy: the new instance takes over
try:
await check_user(uid)
except Exception as e:
print(f"⚠️ Autopilot check failed for {uid}: {e}")
await asyncio.sleep(1) # be gentle with Upload-Post and YouTube
async def _loop():
await asyncio.sleep(60) # let the instance finish booting and resuming jobs
while True:
try:
if _is_active is None or _is_active():
await poll_once()
except asyncio.CancelledError:
return
except Exception as e:
print(f"⚠️ Autopilot loop error: {e}")
await asyncio.sleep(TICK_SECONDS)
def start(app, is_active=None):
"""Start the poller. ``is_active`` returns False while the instance drains."""
global _app, _is_active, _task
_app = app
_is_active = is_active
if os.environ.get("AUTOPILOT_DISABLED", "").lower() in ("1", "true", "yes"):
print("🤖 Autopilot poller disabled (AUTOPILOT_DISABLED).")
return
_task = asyncio.create_task(_loop())
# --------------------------------------------------------------------------- #
# Job completion (called from app.run_job_wrapper)
# --------------------------------------------------------------------------- #
async def on_job_finished(job_id: str, job: dict, failure_reason: Optional[str] = None):
"""Settle the run for ``job_id`` if Autopilot started it; no-op otherwise.
Runs on the instance that ran the job. The status flip is a guarded
UPDATE, so a second call for the same job does nothing.
"""
if not job_id or not isinstance(job, dict):
return
ok = job.get("status") == "completed"
clips = ((job.get("result") or {}).get("clips")) or []
async with database.session() as s:
async with s.begin():
row = (await s.execute(
update(AutopilotRun)
.where(and_(AutopilotRun.job_id == job_id,
AutopilotRun.status == PROCESSING))
.values(status=COMPLETED if ok else FAILED,
reason=None if ok else (failure_reason or "processing_failed"),
clips_count=len(clips) if ok else 0)
.returning(AutopilotRun.id, AutopilotRun.user_id, AutopilotRun.video_title)
)).first()
if row is None or not ok or not clips:
return
run_id, user_id, video_title = row
prefs = await _get_settings(user_id)
platforms = clean_platforms(prefs.publish_platforms if prefs else [])
to_post = []
if prefs and prefs.autopublish and platforms:
n = max(0, min(MAX_CLIPS_TO_PUBLISH, prefs.clips_to_publish or DEFAULT_CLIPS_TO_PUBLISH))
to_post = rank_clips(clips, n)
# Our own email replaces the generic "clips ready" one for this job.
job["email_sent"] = True
try:
from .emails import send_autopilot_clips_email
async with database.session() as s:
user = await s.get(User, user_id)
if user and user.email:
await send_autopilot_clips_email(
user.email, video_title, len(clips), len(to_post),
f"{settings.frontend_url}/#app?tab=autopilot")
except Exception as e:
print(f"⚠️ Autopilot email failed for {job_id}: {e}")
if to_post:
profile = await _profile_for(user_id)
output_dir = job.get("output_dir") or ""
items = []
for i in to_post:
rel = clips[i].get("video_url") or ""
path = os.path.join(output_dir, os.path.basename(rel))
if rel and os.path.exists(path):
items.append((clips[i], path))
if profile and items:
task = asyncio.create_task(_publish(run_id, profile, items, platforms, prefs))
_bg_tasks.add(task)
task.add_done_callback(_bg_tasks.discard)
async def _publish(run_id, profile, items, platforms, prefs):
"""Schedule the chosen clips, one a day. Runs in the background so the
job slot is not held while the files upload."""
slots = schedule_slots(datetime.now(timezone.utc), len(items),
prefs.publish_hour if prefs.publish_hour is not None else DEFAULT_PUBLISH_HOUR,
prefs.timezone)
posted = 0
for (clip, path), when in zip(items, slots):
try:
if await _upload_clip(profile, path, clip, platforms, when, prefs.timezone or "UTC"):
posted += 1
except Exception as e:
print(f"⚠️ Autopilot publish error: {e}")
await _update_run(run_id, posted_count=posted,
reason=None if posted == len(items) else "publish_partial")
# --------------------------------------------------------------------------- #
# API
# --------------------------------------------------------------------------- #
class AutopilotUpdate(BaseModel):
enabled: Optional[bool] = None
rights_ack: Optional[bool] = None
autopublish: Optional[bool] = None
publish_platforms: Optional[List[str]] = None
clips_to_publish: Optional[int] = None
max_minutes: Optional[int] = None
publish_hour: Optional[int] = None
timezone: Optional[str] = None
class ManualRun(BaseModel):
video_id: str
def _settings_view(prefs: Optional[AutopilotSettings]) -> dict:
return {
"enabled": bool(prefs and prefs.enabled),
"enabled_at": prefs.enabled_at.isoformat() if prefs and prefs.enabled_at else None,
"rights_ack": bool(prefs and prefs.rights_ack_at),
"autopublish": bool(prefs and prefs.autopublish),
"publish_platforms": clean_platforms(prefs.publish_platforms) if prefs else [],
"clips_to_publish": (prefs.clips_to_publish if prefs else None) or DEFAULT_CLIPS_TO_PUBLISH,
"max_minutes": (prefs.max_minutes if prefs else None) or DEFAULT_MAX_MINUTES,
"publish_hour": prefs.publish_hour if prefs and prefs.publish_hour is not None
else DEFAULT_PUBLISH_HOUR,
"timezone": prefs.timezone if prefs else None,
"last_checked_at": prefs.last_checked_at.isoformat() if prefs and prefs.last_checked_at else None,
"last_error": prefs.last_error if prefs else None,
}
def _run_view(r: AutopilotRun) -> dict:
return {
"id": str(r.id),
"video_id": r.video_id,
"video_url": r.video_url,
"video_title": r.video_title,
"thumbnail_url": r.thumbnail_url,
"published_at": r.published_at.isoformat() if r.published_at else None,
"trigger": r.trigger,
"status": r.status,
"reason": r.reason,
"job_id": r.job_id,
"clips_count": r.clips_count,
"posted_count": r.posted_count,
"created_at": r.created_at.isoformat() if r.created_at else None,
}
async def _recent_runs(user_id, limit=20):
async with database.session() as s:
return list((await s.execute(
select(AutopilotRun).where(AutopilotRun.user_id == user_id)
.order_by(AutopilotRun.created_at.desc()).limit(limit))).scalars())
@router.get("/api/autopilot")
async def get_autopilot(request: Request):
from .auth import get_current_user_required
user = await get_current_user_required(request)
prefs = await _get_settings(user.id)
profile = await _profile_for(user.id)
accounts = {}
if profile:
try:
accounts = await fetch_social_accounts(profile)
except Exception:
accounts = {}
return {
"eligible": eligible(user),
"plan": user.plan,
"settings": _settings_view(prefs),
"accounts": accounts,
"youtube": accounts.get("youtube"),
"limits": {
"daily_auto": DAILY_AUTO_LIMIT,
"max_minutes_choices": list(MAX_MINUTES_CHOICES),
"max_clips_to_publish": MAX_CLIPS_TO_PUBLISH,
"platforms": list(PUBLISH_PLATFORMS),
},
"runs": [_run_view(r) for r in await _recent_runs(user.id)],
}
@router.put("/api/autopilot")
async def put_autopilot(payload: AutopilotUpdate, request: Request):
from .auth import get_current_user_required
user = await get_current_user_required(request)
turning_on = payload.enabled is True
if turning_on and not eligible(user):
raise HTTPException(status_code=403, detail={
"error": "plan_required",
"message": "Autopilot is included in the Starter, Creator and Pro plans."})
async with database.session() as s:
async with s.begin():
prefs = await s.get(AutopilotSettings, user.id)
if prefs is None:
prefs = AutopilotSettings(user_id=user.id, enabled=False, autopublish=False,
clips_to_publish=DEFAULT_CLIPS_TO_PUBLISH,
max_minutes=DEFAULT_MAX_MINUTES,
publish_hour=DEFAULT_PUBLISH_HOUR)
s.add(prefs)
# Connecting the channel through YouTube's own OAuth already proves it
# is theirs, so switching Autopilot on records the attestation
# instead of asking for a checkbox.
if payload.rights_ack or turning_on:
prefs.rights_ack_at = prefs.rights_ack_at or datetime.now(timezone.utc)
if turning_on:
if not prefs.enabled:
# New baseline: only videos published from now on.
prefs.enabled_at = datetime.now(timezone.utc)
prefs.last_checked_at = None
prefs.last_error = None
prefs.enabled = True
elif payload.enabled is False:
prefs.enabled = False
if payload.autopublish is not None:
prefs.autopublish = bool(payload.autopublish)
if payload.publish_platforms is not None:
prefs.publish_platforms = clean_platforms(payload.publish_platforms)
if payload.clips_to_publish is not None:
prefs.clips_to_publish = max(1, min(MAX_CLIPS_TO_PUBLISH, int(payload.clips_to_publish)))
if payload.max_minutes is not None:
if int(payload.max_minutes) not in MAX_MINUTES_CHOICES:
raise HTTPException(status_code=400, detail="Unsupported max_minutes value.")
prefs.max_minutes = int(payload.max_minutes)
if payload.publish_hour is not None:
prefs.publish_hour = max(0, min(23, int(payload.publish_hour)))
if payload.timezone is not None:
tz = payload.timezone.strip()[:64]
prefs.timezone = tz if (tz and _zone(tz) is not timezone.utc) or tz == "UTC" else prefs.timezone
return {"settings": _settings_view(await _get_settings(user.id))}
@router.get("/api/autopilot/videos")
async def list_channel_videos(request: Request):
"""The channel's latest uploads, each with what Autopilot did with it."""
from .auth import get_current_user_required
user = await get_current_user_required(request)
profile = await _profile_for(user.id)
if not profile:
return {"videos": [], "error": "youtube_not_connected"}
try:
media = await fetch_channel_videos(profile)
except ChannelError as e:
return {"videos": [], "error": e.code}
ids = [m.get("id") for m in media if m.get("id")]
runs = {}
if ids:
async with database.session() as s:
for r in (await s.execute(select(AutopilotRun).where(
AutopilotRun.user_id == user.id,
AutopilotRun.video_id.in_(ids)))).scalars():
runs[r.video_id] = _run_view(r)
return {"videos": [{
"id": m.get("id"),
"title": m.get("caption"),
"url": m.get("permalink"),
"thumbnail_url": m.get("thumbnail_url"),
"published_at": m.get("timestamp"),
"run": runs.get(m.get("id")),
} for m in media if m.get("id")], "error": None}
@router.post("/api/autopilot/run")
async def run_now(payload: ManualRun, request: Request):
"""Clip one channel video now ("clip my latest video"), outside the
automatic schedule. The video must belong to the user's own channel."""
from .auth import get_current_user_required
user = await get_current_user_required(request)
if not eligible(user):
raise HTTPException(status_code=403, detail={
"error": "plan_required",
"message": "Autopilot is included in the Starter, Creator and Pro plans."})
prefs = await _get_settings(user.id)
now = datetime.now(timezone.utc)
if await _count_recent(user.id, "manual", now - timedelta(days=1)) >= MANUAL_DAILY_LIMIT:
raise HTTPException(status_code=429, detail="Daily limit reached. Try again tomorrow.")
profile = await _profile_for(user.id)
if not profile:
raise HTTPException(status_code=400, detail={"error": "youtube_not_connected",
"message": "Connect your YouTube channel first."})
try:
media = await fetch_channel_videos(profile, limit=50)
except ChannelError as e:
raise HTTPException(status_code=400, detail={"error": e.code, "message": "Could not read your channel."})
video = next((m for m in media if m.get("id") == payload.video_id), None)
if video is None:
raise HTTPException(status_code=404, detail="That video is not on your connected channel.")
# A video that failed or was skipped earlier (out of minutes, a hiccup) can
# be retried by hand; one that is running or done cannot be doubled.
async with database.session() as s:
async with s.begin():
await s.execute(delete(AutopilotRun).where(
AutopilotRun.user_id == user.id,
AutopilotRun.video_id == payload.video_id,
AutopilotRun.status.in_((FAILED, SKIPPED))))
result = await _start_video(user, video, "manual",
(prefs.max_minutes if prefs else None) or DEFAULT_MAX_MINUTES)
if result["status"] == "duplicate":
raise HTTPException(status_code=409, detail="This video was already clipped by Autopilot.")
if result.get("retry") or result["status"] == QUEUED:
raise HTTPException(status_code=429, detail=(
"You already have the maximum number of jobs running. Try again in a few minutes."
if result.get("reason") == "busy" else "Could not start the job. Try again shortly."))
return {"status": result["status"], "reason": result.get("reason"), "job_id": result.get("job_id")}

View file

@ -1,774 +0,0 @@
"""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 httpx
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, new_subscriber_label)
from . import analytics, config, database
from .models import User, Subscription, CreditTopup, StripeEvent, SignupAttribution
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)
def _money(cents, currency="usd") -> str:
"""'$59.00' from Stripe's integer-cents + currency."""
sym = {"usd": "$", "eur": "€", "gbp": "£"}.get((currency or "usd").lower(), "")
return f"{sym}{(cents or 0) / 100:,.2f} {(currency or 'usd').upper()}"
# --------------------------------------------------------------------------- #
# 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 _blocking_sub_status(user_id):
"""Return the status of a subscription that must block a new checkout, else None."""
async with database.session() as s:
sub = (await s.execute(
select(Subscription).where(Subscription.user_id == user_id)
)).scalar_one_or_none()
# Block a second checkout while a subscription is live or actively dunning:
# past_due / unpaid / paused all have Stripe still retrying a charge, so a
# fresh subscription would double-bill (real case: annual trial -> end-trial
# -> card declined -> past_due, then a fresh monthly sub).
#
# 'incomplete' is deliberately NOT here. It means a checkout was started and
# the payment never completed (3DS abandoned, card declined at confirm) —
# nothing is being collected, and Stripe expires the row within 24h. Blocking
# it only stops the retry, exactly when the user is most willing to pay.
# Terminal states (canceled, incomplete_expired) do NOT block. Free-plan
# users have no Subscription row at all, so their upgrade checkout passes.
return sub.status if (sub and sub.status in config.CHECKOUT_BLOCKING_STATES) else None
# --------------------------------------------------------------------------- #
# Endpoints
# --------------------------------------------------------------------------- #
@router.get("/api/billing/plans")
async def list_plans():
cat = await get_catalog()
return {"plans": cat["plans"], "topups": cat["topups"]}
# Shown next to Stripe's terms checkbox. Two jobs in one tick: it makes the
# terms opposable to someone who signed up with a magic link and never opened
# them, and it is the express request for immediate performance that art. 16(m)
# of the consumer-rights directive wants before we start spending minutes
# inside the 14-day withdrawal window. Without it a withdrawal on day 13 is
# a full refund of a plan that was already used.
CONSENT_MESSAGE = (
"I accept the Terms of Service and the Privacy Policy, and I ask OpenShorts "
"to start the service immediately. EU consumers: you keep your 14-day right "
"of withdrawal, but you accept that we may charge for the minutes already "
"processed when you withdraw."
)
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":
blocked = await _blocking_sub_status(user.id)
if blocked in ("past_due", "unpaid"):
# Their card failed. Telling them "you already have a plan" is both
# false (they get no minutes) and a dead end — point at the portal.
raise HTTPException(status_code=409, detail=(
"Your last payment didn't go through, so we can't start a new plan "
"yet. Update your card under Manage billing and it resumes right away."))
if blocked:
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,
# Business customers need their legal name and VAT on the invoice to
# deduct the tax, and this is the only place they can ever type them:
# nothing in the dashboard asks for fiscal data. Without it every
# company is invoiced as an anonymous e-mail address and writes to
# support asking for a corrected invoice (ticket #4520), which cannot
# be done in place — the invoice is already issued and its customer
# data frozen, so it takes a rectificativa in the accounting.
# ``customer_update.name`` is required for Checkout to save the name
# onto an EXISTING customer (we always pass one); ``address`` saves the
# billing address the same way. Not made ``required``: it is shown only
# in supported countries and forcing it would add a field to a funnel
# that already converts at ~1%.
tax_id_collection={"enabled": True},
customer_update={"name": "auto", "address": "auto"},
# An unpaid session expires after 24 h; recovery makes Stripe hand the
# checkout.session.expired webhook a URL that reopens the same cart,
# which cloud/lifecycle.py mails once (1,011 of 1,126 sessions to
# 27-sep-2026 expired unpaid, none followed up).
after_expiration={"recovery": {"enabled": True, "allow_promotion_codes": True}},
metadata={
"user_id": str(user.id),
"kind": entry["kind"],
"minutes": str(entry.get("minutes", "")),
},
)
# Dead while TRIAL_DAYS == 0 (trials retired in favor of the free plan);
# kept as the documented grandfathering mechanism.
if mode == "subscription" and TRIAL_DAYS > 0:
kwargs["subscription_data"] = {"trial_period_days": TRIAL_DAYS}
consent = dict(
consent_collection={"terms_of_service": "required"},
custom_text={"terms_of_service_acceptance": {"message": CONSENT_MESSAGE}},
)
try:
session = await asyncio.to_thread(
lambda: stripe.checkout.Session.create(**kwargs, **consent))
except Exception as exc:
# The checkbox needs a Terms of service URL under Stripe > Settings >
# Checkout; without it Stripe rejects the whole session. Losing the
# consent record is bad, refusing the sale is worse, so fall back and
# let it switch itself on the moment the URL is configured.
#
# Caught by message rather than by exception class on purpose: which
# subclass Stripe raises is not worth betting the checkout button on.
# Anything that is not about the terms URL re-raises untouched.
# Match both prose and the parameter name: Stripe has phrased this as
# "terms of service" and as `terms_of_service_url` depending on where
# it fails, and a miss here means a 500 on the checkout button.
msg = str(exc).lower()
if "terms of service" not in msg and "terms_of_service" not in msg:
raise
print(f"[billing] checkout consent box disabled: {exc}", flush=True)
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. Kept for grandfathered trialing subscriptions — removable once
``SELECT count(*) FROM subscriptions WHERE status='trialing'`` reaches 0.
Used when a trialing user hits the trial minute cap and chooses to
activate their plan right away. The subscription webhook flips status→active
(and thus the full ``minutes_per_period`` allowance) once Stripe confirms."""
user = await get_current_user_required(request)
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}
# --------------------------------------------------------------------------- #
# Legal invoices (AgentLedger)
# --------------------------------------------------------------------------- #
# Stripe stays the payment processor; the legally valid Spanish invoice is
# issued by AgentLedger (aikount.com) and surfaced here with signed public
# links, so the customer never needs the Stripe-hosted PDF. Same flow as
# Upload-Post: read by stripe_customer_id, and when AgentLedger has nothing yet
# (just-subscribed user) ask it to import this customer's history on the spot.
_AGENTLEDGER_TIMEOUT = 8.0
_AGENTLEDGER_BACKFILL_TIMEOUT = 20.0
_AGENTLEDGER_BACKFILL_DEBOUNCE_S = 90
_agentledger_backfill_at: dict[str, float] = {} # stripe_customer_id -> unix ts
def _agentledger_headers() -> dict:
return {"Authorization": f"Bearer {settings.agentledger_api_key}"}
async def _agentledger_fetch_invoices(client: httpx.AsyncClient, customer_id: str) -> list[dict]:
"""Invoices for one Stripe customer. 404 = no contact yet → []."""
r = await client.get(f"{settings.agentledger_api_url}/contacts/{customer_id}/invoices",
headers=_agentledger_headers(), timeout=_AGENTLEDGER_TIMEOUT)
if r.status_code == 404:
return []
if r.status_code != 200:
raise HTTPException(status_code=502, detail="Could not load invoices")
raw = (r.json() or {}).get("invoices") or []
# Project to what the UI needs; tokens stay inside the pre-built URLs.
return [{
"doc_number": i.get("doc_number") or "",
"doc_date": i.get("doc_date") or "",
"total": i.get("total") or "0.00",
"currency": i.get("currency") or "EUR",
"status": i.get("status") or "",
"public_url": i.get("public_url") or "",
"pdf_url": i.get("pdf_url") or "",
} for i in raw]
async def _agentledger_backfill(client: httpx.AsyncClient, customer_id: str) -> None:
"""Best-effort: import this customer's whole paid-invoice history now."""
try:
await client.post(f"{settings.agentledger_api_url}/integrations/stripe/sync-customer",
json={"treasury_id": settings.agentledger_treasury_id,
"stripe_customer_id": customer_id},
headers=_agentledger_headers(), timeout=_AGENTLEDGER_BACKFILL_TIMEOUT)
except httpx.HTTPError:
pass
@router.get("/api/billing/invoices")
async def list_invoices(request: Request):
"""Legal invoices for the signed-in user: ``{"invoices": [{doc_number,
doc_date, total, currency, status, public_url, pdf_url}]}``. Free users
(no Stripe customer yet) get an empty list, not an error."""
user = await get_current_user_required(request)
if not settings.agentledger_api_key:
raise HTTPException(status_code=503, detail="Billing backend not configured")
async with database.session() as session:
u = await session.get(User, user.id)
customer_id = u.stripe_customer_id if u else None
if not customer_id:
return {"invoices": []}
async with httpx.AsyncClient() as client:
try:
invoices = await _agentledger_fetch_invoices(client, customer_id)
except httpx.HTTPError:
raise HTTPException(status_code=502, detail="Invoice service unreachable")
if not invoices:
import time as _time
last = _agentledger_backfill_at.get(customer_id, 0.0)
if _time.time() - last > _AGENTLEDGER_BACKFILL_DEBOUNCE_S:
_agentledger_backfill_at[customer_id] = _time.time()
await _agentledger_backfill(client, customer_id)
try:
invoices = await _agentledger_fetch_invoices(client, customer_id)
except httpx.HTTPError:
invoices = []
return {"invoices": invoices}
# --------------------------------------------------------------------------- #
# 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)
await _notify_invoice_paid(obj)
await _track_invoice_revenue(obj)
elif etype == "charge.refunded":
await _track_refund(obj)
elif etype == "checkout.session.expired":
from . import lifecycle
try:
await lifecycle.on_checkout_expired(obj)
except Exception as e: # an email must never make Stripe retry the event
print(f"⚠️ Checkout recovery email failed: {e}")
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
acquisition = {}
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
# The id rides in Stripe's metadata, so it can name an account that
# no longer exists: a checkout completed moments before the user
# erased themselves, or any webhook Stripe retries afterwards.
# Inserting it blind trips the foreign key, and because the event is
# only recorded after handle_event returns, the 500 makes Stripe
# retry the same doomed insert for three days.
user_id = (session_obj.get("metadata") or {}).get("user_id")
if user_id:
try:
user_id = (await s.execute(
select(User.id).where(User.id == user_id)
)).scalar_one_or_none()
except Exception:
user_id = None # not a uuid at all
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()
acquisition = await _acquisition_properties(s, user_id)
amount_txt = ""
total = session_obj.get("amount_total")
if total:
amount_txt = f" ({_money(total, session_obj.get('currency'))})"
from .alerts import send_admin_alert
await send_admin_alert(
f"💰 Top-up purchased{amount_txt}",
f"{buyer_email or 'A user'} bought +{minutes} minutes.",
)
# Mirror the sale into OpenPanel, on the same profile the browser identifies.
analytics.track_revenue(
user_id, total, session_obj.get("currency"),
type="topup", source="openshorts", minutes=minutes,
stripe_session_id=session_id, email=buyer_email, **acquisition,
)
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
LIVE_STATUSES = ("active", "trialing")
def became_live(prev_status, now_status) -> bool:
"""The transition that turns a free account into a paid one."""
return now_status in LIVE_STATUSES and prev_status not in LIVE_STATUSES
async def _unmark_after_upgrade(user_id):
try:
from . import videos
await videos.unmark_user_library(user_id)
except Exception as e:
print(f"⚠️ Could not unmark the library of {user_id} after upgrade: {e}")
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
# Cross-subscription guard: the table keeps one row per user, so an
# event for a *different* subscription of the same user must not clobber
# the row that represents their live plan. This is exactly what happens
# when a user has a dangling sub (e.g. a past_due annual that gets
# canceled) alongside a live one (a trialing monthly): the canceled
# sub's update would otherwise overwrite the good row. Only let another
# subscription take over when the stored one is no longer live.
if row and row.stripe_subscription_id != sub_obj["id"]:
stored_live = row.status in ("active", "trialing", "past_due", "unpaid")
incoming_live = sub_obj.get("status") in ("active", "trialing", "past_due")
if stored_live and not incoming_live:
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).
# Not for 'incomplete': Checkout creates the subscription the moment the
# user hits pay, before 3DS / the card answer, so that status only says
# someone reached the button. About half of them expire unpaid (24 of 53
# in the 30 days to 16-sep-2026), and the ones that do pay are announced
# by the 'Payment received' alert on invoice.paid, which carries the
# amount; a second message here would just be noise.
now_status = sub_obj["status"]
if became_live(prev_status, now_status):
# The clips this user already made on the free plan lose their
# watermark now (cloud/videos): the upgrade modal promised exactly
# that. Fire-and-forget: Stripe must get its 200 whatever R2 does.
asyncio.create_task(_unmark_after_upgrade(user_id))
label = new_subscriber_label(now_status) if is_new_sub else None
if label:
from .alerts import send_admin_alert
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
# Cancelled in the Stripe portal, not the dashboard flow (which flips
# the row itself and sends its own alert). The portal's reason, if it
# asked for one, is the only feedback there is. The comment is free
# text and stays out of Telegram (alerts.user_ref).
feedback = (sub_obj.get("cancellation_details") or {}).get("feedback")
await send_admin_alert(
"🔻 Subscription canceled",
f"A {plan} subscriber just canceled in the Stripe portal"
f"{f' (reason: {feedback})' if feedback else ''}.\n"
f"Access continues until {end_dt:%Y-%m-%d}. Google-authed users then "
f"drop to the free plan (clips expire after 7 days); others keep their "
f"videos {VIDEO_RETENTION_GRACE_DAYS} more days before deletion.",
)
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)
async def _notify_invoice_paid(invoice_obj: dict):
"""Real money-in alert: every paid invoice — first charge AND every monthly
renewal (renewals were previously silent). Includes the amount."""
amount = invoice_obj.get("amount_paid", 0)
if amount <= 0: # $0 invoices (e.g. legacy trial start)
return
money = _money(amount, invoice_obj.get("currency"))
reason = invoice_obj.get("billing_reason") or ""
kind = {
"subscription_create": "new subscription",
"subscription_cycle": "renewal",
"subscription_update": "plan change",
}.get(reason, reason or "payment")
email = None
async with database.session() as s:
cust = invoice_obj.get("customer")
if cust:
email = (await s.execute(
select(User.email).where(User.stripe_customer_id == cust)
)).scalar_one_or_none()
from .alerts import send_admin_alert
await send_admin_alert(
f"💵 Payment received: {money}",
f"{email or 'A customer'} — {kind}.",
)
# --------------------------------------------------------------------------- #
# OpenPanel revenue mirror
# --------------------------------------------------------------------------- #
# The browser fires ``Subscribed`` with the list price when the user comes back
# from Stripe, but that is an intent signal: it misses renewals entirely, is
# eaten by ad-blockers and can never see a refund. The webhook is the only
# place money is known for certain, so every paid invoice, top-up and refund is
# mirrored here as OpenPanel's native ``revenue`` event. ``profileId`` is the
# user's uuid — the same id the browser and the job events already use — so
# the sale lands on the profile that carries their pageviews and ``Signup``.
_INVOICE_REVENUE_TYPE = {
"subscription_create": "new",
"subscription_cycle": "renewal",
"subscription_update": "upgrade",
"subscription_threshold": "renewal",
}
async def _acquisition_properties(session, user_id) -> dict:
"""Never raises: a missing row simply reads as ``channel=direct``."""
try:
row = await session.get(SignupAttribution, user_id)
except Exception:
row = None
return analytics.acquisition_properties(row)
async def _track_invoice_revenue(invoice_obj: dict):
try:
amount = int(invoice_obj.get("amount_paid") or 0)
except (TypeError, ValueError):
return
if amount <= 0:
return
cust = invoice_obj.get("customer")
if not cust:
return
async with database.session() as s:
user = (await s.execute(
select(User.id, User.email).where(User.stripe_customer_id == cust)
)).first()
if user is None:
return
user_id, email = user
plan = interval = None
sub_id = invoice_obj.get("subscription")
if sub_id:
sub = (await s.execute(
select(Subscription.plan, Subscription.interval).where(
Subscription.stripe_subscription_id == sub_id
)
)).first()
if sub is not None:
plan, interval = sub
acquisition = await _acquisition_properties(s, user_id)
reason = invoice_obj.get("billing_reason") or ""
analytics.track_revenue(
user_id, amount, invoice_obj.get("currency"),
type=_INVOICE_REVENUE_TYPE.get(reason, "other"), source="openshorts",
plan=plan, interval=interval, billing_reason=reason or None,
stripe_invoice_id=invoice_obj.get("id"), email=email, **acquisition,
)
async def _track_refund(charge_obj: dict):
"""Negative revenue. ``amount_refunded`` is cumulative across partial
refunds, so prefer the newest entry of ``refunds.data`` when Stripe
includes it (it is not expanded by default on recent API versions)."""
refunds = ((charge_obj.get("refunds") or {}).get("data") or [])
raw = refunds[0].get("amount") if refunds else charge_obj.get("amount_refunded")
try:
amount = int(raw or 0)
except (TypeError, ValueError):
return
if amount <= 0:
return
cust = charge_obj.get("customer")
if not cust:
return
async with database.session() as s:
user = (await s.execute(
select(User.id, User.email).where(User.stripe_customer_id == cust)
)).first()
if user is None:
return
user_id, email = user
acquisition = await _acquisition_properties(s, user_id)
analytics.track_revenue(
user_id, -amount, charge_obj.get("currency"),
type="refund", source="openshorts",
stripe_charge_id=charge_obj.get("id"), email=email, **acquisition,
)

View file

@ -1,300 +0,0 @@
"""In-app cancellation: ask why, ask for a review, then cancel.
Cancelling used to happen only inside the Stripe Customer Portal, so the one
moment a paying customer tells us what went wrong produced nothing but a
"🔻 Subscription canceled" alert with no reason in it. This endpoint is the
dashboard's cancel flow: the reason (closed list, so it can be counted), an
optional free-text detail, a 1-5 rating and an optional review, stored in
``cancellation_feedback`` and then passed on to Stripe as
``cancellation_details`` so the Stripe dashboard shows the same reason.
The cancel is ``cancel_at_period_end``, never immediate: they paid for the
period and keep it. The portal stays available and can still cancel without
this form; the webhook alert carries Stripe's own ``cancellation_details`` for
those.
Before the cancel, the last step offers the retention coupon (the portal's
"Stay with us: 50% off for 3 months", ``RETENTION_COUPON``). Cancelling was
turned off in the portal on 2026-09-28 so this flow, with its offer, is the only
way out. The offer is made once per subscription (``retention_offer`` in its
Stripe metadata), only on a live monthly plan with no discount on it: on a
yearly plan it would halve a whole year. Taking it stores the same feedback row
with ``outcome="retained"``. ``/api/billing/resume`` undoes a scheduled cancel,
since the portal's "renew" goes with its cancel feature.
Unlike ``account.DELETION_REASONS``, free text is fine here: these rows belong
to the user (``account.USER_OWNED_TABLES``) and go with the account. What must
not happen is the text reaching Telegram (see ``alerts.user_ref``), so the
alert says how long the review is, never what it says.
"""
import asyncio
import os
from typing import Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from sqlalchemy import select
from . import analytics, database
from .auth import get_current_user_required
from .models import CancellationFeedback, Subscription
router = APIRouter()
# Mirrors the REASONS list in dashboard/src/components/CancelPlanModal.jsx.
# Each maps to the closest value of Stripe's own cancellation_details.feedback
# enum, so the reason also shows up on the subscription in Stripe.
CANCEL_REASONS = {
"too_expensive": "too_expensive",
"not_using_it": "unused",
"clip_quality": "low_quality",
"missing_feature": "missing_features",
"found_alternative": "switched_service",
"too_complex": "too_complex",
"support": "customer_service",
"one_off_project": "unused",
"other": "other",
}
# States in which there is a renewal to stop. past_due is included: a customer
# whose card failed and who wants out should not have to fix the card first.
CANCELLABLE_STATES = ("active", "trialing", "past_due")
MAX_TEXT = 2000
# The Stripe coupon offered before a cancel (env, like every coupon id; see
# CLAUDE.md). Unset turns the offer off and the flow is reason -> review -> cancel.
RETENTION_COUPON = os.environ.get("RETENTION_COUPON_ID", "").strip()
class CancelRequest(BaseModel):
reason: str
details: Optional[str] = Field(default=None, max_length=MAX_TEXT)
rating: Optional[int] = Field(default=None, ge=1, le=5)
review: Optional[str] = Field(default=None, max_length=MAX_TEXT)
review_public_ok: bool = False
def _stripe_cancel_at_period_end(subscription_id: str, feedback: str, comment: str):
# Imported here so the module (and its tests) load where stripe is not
# installed, as in CI.
import stripe
stripe.Subscription.modify(
subscription_id,
cancel_at_period_end=True,
cancellation_details={"feedback": feedback, "comment": comment},
)
def _stripe_offer_blocked(subscription_id: str) -> bool:
"""True when this subscription already has a discount or had the offer."""
import stripe
live = stripe.Subscription.retrieve(subscription_id)
return bool(live.get("discounts") or live.get("discount")
or (live.get("metadata") or {}).get("retention_offer"))
_coupon_terms = {}
def _stripe_coupon_terms(coupon_id: str) -> dict:
if coupon_id not in _coupon_terms:
import stripe
c = stripe.Coupon.retrieve(coupon_id)
if not c.get("valid") or not c.get("percent_off"):
return {}
_coupon_terms[coupon_id] = {"percent_off": int(c["percent_off"]),
"months": c.get("duration_in_months")}
return _coupon_terms[coupon_id]
def _stripe_apply_retention(subscription_id: str, coupon_id: str):
import stripe
stripe.Subscription.modify(
subscription_id,
discounts=[{"coupon": coupon_id}],
metadata={"retention_offer": "accepted"},
)
def _stripe_resume(subscription_id: str):
import stripe
stripe.Subscription.modify(subscription_id, cancel_at_period_end=False)
def _clean(text: Optional[str]) -> Optional[str]:
text = (text or "").strip()
return text or None
async def _renewing_sub(user_id) -> Subscription:
"""The user's subscription, if it is live and still set to renew."""
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 not in CANCELLABLE_STATES:
raise HTTPException(status_code=409, detail="There is no active subscription to cancel.")
if sub.cancel_at_period_end:
raise HTTPException(status_code=409, detail="Your subscription is already set to cancel.")
return sub
async def _offer_for(sub) -> Optional[dict]:
"""The retention offer's terms for this subscription, or None."""
if not RETENTION_COUPON or sub.status != "active" or sub.interval != "month":
return None
try:
if await asyncio.to_thread(_stripe_offer_blocked, sub.stripe_subscription_id):
return None
return await asyncio.to_thread(_stripe_coupon_terms, RETENTION_COUPON) or None
except Exception as e:
# No offer is better than a cancel flow that cannot reach its last step.
print(f"⚠️ Retention offer check failed for {sub.stripe_subscription_id}: {e}")
return None
@router.get("/api/billing/retention-offer")
async def retention_offer(request: Request):
user = await get_current_user_required(request)
sub = await _renewing_sub(user.id)
offer = await _offer_for(sub)
return {"eligible": bool(offer), **(offer or {})}
@router.post("/api/billing/retention-offer/accept")
async def accept_retention_offer(body: CancelRequest, request: Request):
user = await get_current_user_required(request)
if body.reason not in CANCEL_REASONS:
raise HTTPException(status_code=422, detail="Pick a reason from the list.")
sub = await _renewing_sub(user.id)
offer = await _offer_for(sub)
if not offer:
raise HTTPException(status_code=409, detail="This offer is no longer available.")
try:
await asyncio.to_thread(_stripe_apply_retention, sub.stripe_subscription_id,
RETENTION_COUPON)
except Exception as e:
print(f"⚠️ Retention coupon failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't apply the discount right now. Please try again, "
"or email info@openshorts.app."))
details, review = _clean(body.details), _clean(body.review)
async with database.session() as session:
async with session.begin():
session.add(CancellationFeedback(
user_id=user.id,
stripe_subscription_id=sub.stripe_subscription_id,
plan=sub.plan, interval=sub.interval,
reason=body.reason, details=details,
rating=body.rating, review=review,
review_public_ok=bool(body.review_public_ok and review),
outcome="retained",
))
analytics.track("RetentionOfferAccepted", user_id=user.id, plan=sub.plan,
reason=body.reason, rating=body.rating)
from .alerts import send_admin_alert, user_ref
term = f" for {offer['months']} months" if offer.get("months") else ""
await send_admin_alert(
"🛟 Cancel saved",
f"{user_ref(user.id)} was about to cancel the {sub.plan} plan "
f"(reason: {body.reason}) and took {offer['percent_off']}% off{term}.",
)
return {"ok": True, **offer}
@router.post("/api/billing/resume")
async def resume_subscription(request: Request):
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 not in CANCELLABLE_STATES or not sub.cancel_at_period_end:
raise HTTPException(status_code=409, detail="There is no scheduled cancellation to undo.")
try:
await asyncio.to_thread(_stripe_resume, sub.stripe_subscription_id)
except Exception as e:
print(f"⚠️ Stripe resume failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't resume your subscription right now. Please try again, "
"or email info@openshorts.app."))
async with database.session() as session:
async with session.begin():
row = (await session.execute(
select(Subscription).where(Subscription.id == sub.id).with_for_update()
)).scalar_one_or_none()
if row is not None:
row.cancel_at_period_end = False
analytics.track("SubscriptionResumed", user_id=user.id, plan=sub.plan)
from .alerts import send_admin_alert, user_ref
await send_admin_alert("🔺 Cancel undone",
f"{user_ref(user.id)} resumed the {sub.plan} plan.")
return {"ok": True}
@router.post("/api/billing/cancel")
async def cancel_subscription(body: CancelRequest, request: Request):
user = await get_current_user_required(request)
if body.reason not in CANCEL_REASONS:
raise HTTPException(status_code=422, detail="Pick a reason from the list.")
sub = await _renewing_sub(user.id)
details, review = _clean(body.details), _clean(body.review)
# Stripe caps the comment at 5000 chars; ours are 2000 each.
comment = " | ".join(x for x in (details, review) if x) or None
try:
await asyncio.to_thread(
_stripe_cancel_at_period_end, sub.stripe_subscription_id,
CANCEL_REASONS[body.reason], comment or "")
except Exception as e:
print(f"⚠️ Stripe cancel failed for {user.id}: {e}")
raise HTTPException(status_code=502, detail=(
"We couldn't cancel your subscription right now. Please try again, "
"or email info@openshorts.app."))
# Written after Stripe accepted the cancel, so a failed call leaves no
# feedback row claiming a cancellation that never happened. Flipping
# cancel_at_period_end here (instead of waiting for the webhook) makes the
# account page show it at once, and makes the webhook see no False -> True
# transition, so the generic churn alert does not fire on top of this one.
async with database.session() as session:
async with session.begin():
session.add(CancellationFeedback(
user_id=user.id,
stripe_subscription_id=sub.stripe_subscription_id,
plan=sub.plan, interval=sub.interval,
reason=body.reason, details=details,
rating=body.rating, review=review,
review_public_ok=bool(body.review_public_ok and review),
outcome="canceled",
))
row = (await session.execute(
select(Subscription).where(Subscription.id == sub.id).with_for_update()
)).scalar_one_or_none()
if row is not None:
row.cancel_at_period_end = True
analytics.track("SubscriptionCanceled", user_id=user.id, plan=sub.plan,
interval=sub.interval, reason=body.reason, rating=body.rating,
has_review=bool(review))
from .alerts import send_admin_alert, user_ref
stars = f"{body.rating}/5" if body.rating else "no rating"
written = []
if details:
written.append(f"detail {len(details)} chars")
if review:
written.append(f"review {len(review)} chars"
+ (", OK to quote" if body.review_public_ok else ""))
await send_admin_alert(
"🔻 Subscription canceled",
f"{user_ref(user.id)} canceled the {sub.plan} ({sub.interval}) plan.\n"
f"Reason: {body.reason}. Rating: {stars}.\n"
f"{'; '.join(written) or 'No written feedback'} (cancellation_feedback table).\n"
f"Access continues until {sub.current_period_end:%Y-%m-%d}.",
)
return {"ok": True, "period_end": sub.current_period_end.isoformat()}

View file

@ -1,374 +0,0 @@
"""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 plan: monthly allowance for Google-authenticated users with no
# subscription. No Stripe object exists for it — it is resolved entirely in
# cloud/metering.py against a synthetic calendar-month period. Setting
# FREE_PLAN_MINUTES = 0 disables the free plan.
FREE_PLAN_MINUTES = 20
# An address erased (DELETE /api/account) within this many days gets no free
# minutes when it signs up again: deleting and re-registering was a way to
# reset the monthly allowance (15 re-registrations by 6 accounts, sep-2026).
FREE_REDO_BLOCK_DAYS = 90
# Free is open to Google accounts AND permanent email accounts; disposable /
# temp-mail domains are blocked at sign-up (cloud/email_policy) and aliases are
# normalized, so the plan isn't a multi-account faucet.
# The 20-minute monthly quota is the only bound on free usage — no daily job
# cap (it confused users and the minute ledger already caps real cost).
# Free users' clips expire from R2 after this many days (paid libraries are
# durable). Also an upgrade lever, mirroring OpusClip's 3-day free exports.
FREE_CLIP_RETENTION_DAYS = 7
# Free trial length (days) for new subscriptions. Trials are retired in favor
# of the free plan; the checkout only injects trial_period_days when > 0, and
# existing 'trialing' subscriptions are still honored until they convert or
# cancel (grandfathering).
TRIAL_DAYS = 0
# Subscription states that grant no minutes but still need the customer to act
# (fix a card, finish a payment). They must stay VISIBLE in /api/me and keep the
# billing-portal route reachable — otherwise the account silently reads as free
# and the user has no way out. Terminal states (canceled, incomplete_expired)
# are deliberately absent: nothing to fix, so nothing to nag about.
BILLING_ATTENTION_STATES = ("past_due", "unpaid", "incomplete", "paused")
# Subscription states that must block a NEW subscription checkout. Narrower than
# BILLING_ATTENTION_STATES on purpose: Stripe is still trying to collect on
# past_due/unpaid/paused, so a second subscription would double-bill. It is NOT
# collecting on 'incomplete' (payment abandoned at 3DS/confirm, expired by Stripe
# within 24h), so blocking that would only stop the retry.
CHECKOUT_BLOCKING_STATES = ("active", "trialing", "past_due", "unpaid", "paused")
def new_subscriber_label(status: str):
"""Admin-alert text for a brand-new subscription row, or None to stay silent.
Only states where a payment method actually went through count. Stripe
creates the row as 'incomplete' seconds after the Checkout page opens,
before the user types anything; announcing that is announcing a click.
Lives here (not in billing.py) so the test runs without the stripe SDK.
"""
if status == "trialing":
return "trial started — card on file"
if status == "active":
return status
return None
# Smallest slice of a long video worth offering instead of the quota wall.
# A user whose remaining minutes cannot cover the whole source is offered its
# first N minutes (N = what they have left) so they see clips before paying:
# 93 of the 99 walls sampled to 16-sep-2026 were shown to accounts with their
# 20 free minutes untouched, pasting a 21-90 min video, and most left Stripe
# without paying. Below this many minutes the slice cannot hold a few 15-60 s
# clips, so the wall stays as it was.
PARTIAL_MIN_MINUTES = 5
# A free account's FIRST video is clipped whole when it runs up to this many
# minutes, even past the 20-minute balance: the balance goes to zero and the
# user sees every clip of the video they came with. Once per account (any
# reserved/committed process job disqualifies it), and the free plan itself is
# already gated (Google or permanent email, re-registration blocked 90 days).
# Longer first videos, and every later one past the balance, are clipped to
# the first N minutes automatically instead of hitting the wall.
# 0 disables the grant.
FIRST_VIDEO_MAX_MINUTES = 60
# ...and once per client IP in this many days, whatever the account: a pile of
# Google accounts from one network gets one whole first video, and the rest
# fall back to the first-N-minutes cut. The IP is kept only as an HMAC
# (cloud/metering.ip_fingerprint) and rows older than the window are deleted.
FIRST_VIDEO_IP_WINDOW_DAYS = 30
# Minute cap DURING the trial (across all plans). Kept for grandfathered
# 'trialing' subscriptions; removable once no subscription has status
# 'trialing'.
TRIAL_MINUTE_CAP = 20
# Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call
# (~$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
def subtitle_minutes_for(filename: str) -> int:
"""Minutes charged for burning captions onto ``filename``.
Zero for the normal path: the SRT comes from the transcript already stored
in metadata.json and the burn is one short FFmpeg pass, so there is nothing
to recover. Captions are also table stakes for short-form — charging 2 min
(10% of the free monthly quota) per clip priced them out of the product and
only 9% of delivered clips ever had them (prod audit, 25-jul-2026).
Dubbed clips are the exception: subtitling them re-runs Whisper over the
translated audio, which is real compute, so they keep the charge.
"""
return SUBTITLE_MINUTES if str(filename).startswith("translated_") else 0
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,
"free": 2,
}
# Max simultaneous managed jobs per user, by plan.
PLAN_JOB_LIMIT = {
"pro": 3,
"creator": 2,
"starter": 2,
"free": 1,
}
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 public_api_url(self) -> str:
"""Absolute base of this API as the internet sees it.
Needed by anything that has to put a working API link inside a message
that leaves the browser — the unsubscribe link in an email, for one.
Same variable app.py uses for the webhook payload's absolute URLs.
"""
return os.environ.get("PUBLIC_API_URL", "").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", "")
# AgentLedger (aikount.com) — issues the legally valid Spanish invoice for
# every Stripe charge; the account page lists them via /api/billing/invoices.
@property
def agentledger_api_url(self) -> str:
return os.environ.get("AGENTLEDGER_API_URL", "https://api.aikount.com/api/v1").rstrip("/")
@property
def agentledger_api_key(self) -> str:
return os.environ.get("AGENTLEDGER_API_KEY", "")
@property
def agentledger_treasury_id(self) -> str:
# The Stripe Connect treasury in AgentLedger that holds OpenShorts' customers.
return os.environ.get("AGENTLEDGER_TREASURY_ID", "720d3b70-3806-4c59-8729-2495b489a771")
# 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_public_base(self) -> str:
"""Base URL of a custom domain bound to the R2 bucket, e.g.
https://cdn.openshorts.app — unset means keep signing S3 URLs.
The S3 endpoint (*.r2.cloudflarestorage.com) is not a browser-facing
endpoint: measured 22-ago-2026, a presigned GET from Chrome on a Spanish
residential line returns 503 on every attempt while the same URL with the
same headers returns 206 at 11 MB/s from a datacenter. A custom domain
serves the same objects through the normal Cloudflare edge, which both
fixes that and puts the bytes on Cloudflare's network instead of a single
long path out of Hetzner (measured to the same client: 90 KB/s).
Objects under it are public. That matches the capability model already in
production for /videos/{job_id}/... (unauthenticated, the UUID is the
capability); anything stricter needs a Worker checking a signed token.
"""
return os.environ.get("R2_PUBLIC_BASE", "").strip().rstrip("/")
@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
# How long the erasure log (cloud/models.AccountDeletion) is kept. Matches the
# "rights declarations and related logs: up to 5 years" line in the privacy
# policy, which in turn matches the statute of limitations for civil claims.
DELETION_LOG_RETENTION_DAYS = 5 * 365
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."
)

View file

@ -1,72 +0,0 @@
"""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
# Columns added to tables that already exist in production. ADD COLUMN IF NOT
# EXISTS is a no-op on a database that already has them and on a fresh one that
# create_all just built.
_ADDITIVE_COLUMNS = (
"ALTER TABLE users ADD COLUMN IF NOT EXISTS "
"marketing_opt_out BOOLEAN NOT NULL DEFAULT false",
# Nullable, no default: a catalog-only change, no table rewrite.
"ALTER TABLE users ADD COLUMN IF NOT EXISTS free_plan_denied VARCHAR(32)",
# The per-network first-video check joins first_video_grants on job_id.
"CREATE INDEX IF NOT EXISTS ix_usage_job_id ON usage_ledger (job_id)",
# cancellation_feedback shipped without it; rows before it are all cancels.
"ALTER TABLE cancellation_feedback ADD COLUMN IF NOT EXISTS outcome VARCHAR(16)",
)
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)
# create_all creates missing TABLES and never ALTERs an existing one, so
# a column added to a model that already shipped exists in the code and
# not in the database. Each statement here is additive and idempotent;
# keep them that way, and prefer Alembic once one of them is not.
for statement in _ADDITIVE_COLUMNS:
try:
await conn.execute(text(statement))
except Exception as e: # pragma: no cover - depends on the server
print(f"⚠️ Additive schema step failed ({statement}): {e}")
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

View file

@ -1,138 +0,0 @@
"""Daily ops digest to Telegram: one message per day with the pulse of the
product (signups, processing activity, clips, revenue events), replacing
per-event pings that turned into spam as free usage grew.
Everything is computed from the DB at send time, so redeploys lose no data.
The send is scheduled by wall clock (sleep until the next 06:00 UTC): a deploy
in the middle of the day just re-arms the same next send, so there is no
duplicate-send window to guard with state. The one accepted loss: a deploy
that lands exactly across the send minute skips that day's message (the data
still shows up in DB queries; only the ping is lost). Transient failures at
send time are retried in-process rather than skipped.
"""
import asyncio
from datetime import datetime, timedelta, timezone
from sqlalchemy import distinct, func, select
from . import database
from .models import StripeEvent, UsageLedger, User, UserVideo
_SEND_HOUR_UTC = 6 # 08:00 Madrid in summer — with the first coffee
# Stripe event types worth a line in the digest, with a human label.
# invoice.payment_succeeded is deliberately absent: it is a near-alias of
# invoice.paid and counting both would double-report every payment.
_STRIPE_LABELS = {
"checkout.session.completed": "checkout completed",
"invoice.paid": "payment",
"invoice.payment_failed": "PAYMENT FAILED",
"customer.subscription.created": "new subscription",
"customer.subscription.deleted": "subscription ended",
}
async def _window_stats(start, end):
async with database.session() as s:
signups = (await s.execute(
select(func.count(User.id))
.where(User.created_at >= start, User.created_at < end)
)).scalar_one()
jobs, processors, refunded, minutes = (await s.execute(
select(
func.count(UsageLedger.id),
func.count(distinct(UsageLedger.user_id)),
func.count(UsageLedger.id).filter(UsageLedger.status == "released"),
func.coalesce(func.sum(UsageLedger.minutes), 0),
).where(UsageLedger.job_type == "process",
UsageLedger.created_at >= start,
UsageLedger.created_at < end)
)).one()
clips = (await s.execute(
select(func.count(UserVideo.id))
.where(UserVideo.created_at >= start, UserVideo.created_at < end)
)).scalar_one()
# processed_at (server-side), NOT StripeEvent.created: Stripe keeps the
# original event timestamp across delivery retries, so an event
# delivered late after an outage would land inside an already-digested
# window and never be reported. New subscriptions are counted from the
# customer.subscription.created event rather than Subscription rows:
# the DB upserts re-subscribing churned users into their existing row,
# whose created_at never refreshes.
stripe_rows = (await s.execute(
select(StripeEvent.type, func.count(StripeEvent.id))
.where(StripeEvent.processed_at >= start,
StripeEvent.processed_at < end)
.group_by(StripeEvent.type)
)).all()
return {
"signups": signups,
"jobs": jobs,
"processors": processors,
"refunded": refunded,
"minutes": float(minutes or 0),
"clips": clips,
"stripe": {t: n for t, n in stripe_rows if t in _STRIPE_LABELS},
}
def _format(stats) -> str:
lines = [
"📊 Daily digest (last 24h)",
f"Signups: {stats['signups']}",
f"Processing: {stats['processors']} user(s), {stats['jobs']} job(s), "
f"{stats['minutes']:.0f} min"
+ (f" — {stats['refunded']} refunded" if stats['refunded'] else ""),
f"Clips created: {stats['clips']}",
]
for etype, n in sorted(stats["stripe"].items()):
lines.append(f"Stripe: {n}× {_STRIPE_LABELS[etype]}")
if stats["signups"] == 0 and stats["jobs"] == 0 and stats["clips"] == 0:
lines.append("(quiet day)")
return "\n".join(lines)
async def send_daily_digest():
from .alerts import send_telegram
end = datetime.now(timezone.utc)
start = end - timedelta(hours=24)
stats = await _window_stats(start, end)
await send_telegram(_format(stats), raise_errors=True)
print("📊 Daily digest sent.")
_SEND_RETRIES = 6 # transient DB/Telegram trouble at send time...
_RETRY_DELAY_SECONDS = 300 # ...retries for up to 30 min instead of skipping
async def _digest_loop():
while True:
now = datetime.now(timezone.utc)
target = now.replace(hour=_SEND_HOUR_UTC, minute=0, second=0,
microsecond=0)
if target <= now:
target += timedelta(days=1)
await asyncio.sleep((target - now).total_seconds())
# Retry in place rather than falling through to tomorrow's target —
# otherwise one DB blip at 06:00 silently swallows the whole day.
for attempt in range(_SEND_RETRIES):
try:
await send_daily_digest()
break
except asyncio.CancelledError:
return
except Exception as e:
print(f"⚠️ Daily digest error (attempt {attempt + 1}): {e}")
await asyncio.sleep(_RETRY_DELAY_SECONDS)
_task = None # keep a strong reference: the loop only holds weak task refs
def start_digest():
global _task
_task = asyncio.create_task(_digest_loop())

View file

@ -1,166 +0,0 @@
# Disposable / temp-mail domains blocked from sign-up (one per line, lowercase).
# Comments (#) and blank lines ignored. Refreshable from the upstream project
# https://github.com/disposable-email-domains/disposable-email-domains
# — this is a strong curated subset plus every abusive domain seen in our own
# sign-ups. Add new ones here as they appear.
# --- Observed in our own DB ---
onldm.net
web-library.net
diarshop.com
hidepost.net
luckfeed.com
vltmail.com
buyreview.us
xhseeds.com
kdpsl.org
lasttea.com
gicont.com
# --- Classic temp-mail providers (and common aliases) ---
10minutemail.com
10minutemail.net
20minutemail.com
33mail.com
guerrillamail.com
guerrillamail.net
guerrillamail.org
guerrillamail.biz
guerrillamail.de
guerrillamailblock.com
sharklasers.com
grr.la
spam4.me
mailinator.com
mailinator.net
mailinator2.com
notmailinator.com
reconmail.com
tempmail.com
temp-mail.org
temp-mail.io
tempmail.net
tempmailo.com
tempr.email
tempmailaddress.com
tempinbox.com
throwawaymail.com
throwam.com
trashmail.com
trashmail.net
trashmail.io
trashmail.de
trash-mail.com
getnada.com
nada.email
maildrop.cc
mailnesia.com
mailcatch.com
dispostable.com
fakeinbox.com
fakemailgenerator.com
mytemp.email
tmail.com
tmails.net
mohmal.com
emailondeck.com
yopmail.com
yopmail.net
yopmail.fr
cool.fr.nf
jetable.fr.nf
nospam.ze.tc
nomail.xl.cx
mega.zik.dj
speed.1s.fr
courriel.fr.nf
moncourrier.fr.nf
monemail.fr.nf
monmail.fr.nf
inboxbear.com
inboxkitten.com
burnermail.io
33mail.com
anonaddy.com
anonaddy.me
mozmail.com
duck.com
relay.firefox.com
mailslurp.com
harakirimail.com
mailhog.io
mailtemp.net
mailexpire.com
spambox.us
spamgourmet.com
spamex.com
mailnull.com
spamherelots.com
tempemail.co
disposablemail.com
disposable.com
emailfake.com
fakemail.net
tempemails.io
1secmail.com
1secmail.net
1secmail.org
esiix.com
wwjmp.com
xojxe.com
vjuum.com
laafd.com
txcct.com
dpptd.com
oosln.com
bbmail.uk
byom.de
mailcuk.com
smailpro.com
tmpmail.org
tmpmail.net
tmpbox.net
minuteinbox.com
mailpoof.com
tempmailer.com
tempmailer.de
tempmailgen.com
tempail.com
altmails.com
altinbox.net
inboxes.com
easytrashmail.com
crazymailing.com
mailtothis.com
mailimate.com
etempmail.net
teleworm.us
armyspy.com
cuvox.de
dayrep.com
einrot.com
fleckens.hu
gustr.com
jourrapide.com
rhyta.com
superrito.com
teleg.eu
throaway.net
mailbox52.ga
tempmail.plus
tempmailbox.net
disbox.net
disbox.org
tmpeml.com
tmpeml.info
mail-temp.com
mailtm.com
mail.tm
linshiyouxiang.net
mailscrap.com
robot-mail.com
givmail.com
zetmail.com
mailtrap.io
correotemporal.org
correotemporal.com

View file

@ -1,26 +0,0 @@
# MX-target domains of disposable/temp-mail providers (one per line, lowercase).
# Comments (#) and blank lines ignored. Matched as a suffix against the MX
# hostnames of a sign-up domain: front domains rotate (onldm.net was one of
# 10minutemail's) but they all point MX at the provider's real SMTP hosts,
# which stay put. Add the MX target here when a new front domain shows up in
# the bounces (dig +short MX <domain>).
10minutemail.com
1secmail.com
dropmail.me
generator.email
guerrillamail.com
harakirimail.com
mail.tm
maildrop.cc
mailinator.com
mohmal.com
temp-mail.org
yopmail.com
# Sep-2026 free-minute farm: ~100 rotating front domains (airychen.com,
# meonvr.com, findize.com, ...) all MX to these two hosts; 567 accounts.
wabblywabble.com
wallywatts.com
# Fronts forexzig.com, fxzig.com, denipl.net -> mx2.den.yt
den.yt
# Fronts aminating.com, mailshan.com, draughtier.com -> temp-mail-pro.com
temp-mail-pro.com

View file

@ -1,176 +0,0 @@
"""Email hygiene for sign-up: block disposable domains, normalize aliases,
verify the domain can actually receive mail.
Three abuse vectors this closes, now that the free plan is open to email (not
just Google) accounts:
* temp-mail domains → free-minute farms (blocklist below, plus MX-target
matching for the rotating front domains the blocklist can't keep up with).
* provider aliases (gmail dots / +tags) → one address becomes infinite
accounts → normalized to a single canonical form.
* nonexistent addresses/domains → every magic link bounces back into the
support inbox and burns sender reputation with PrivateEmail.
"""
import os
import time
_DOMAINS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"disposable_domains.txt")
# Providers where a "+tag" suffix and (for Google) dots are ignored by the
# mail server, so foo+1@ and f.oo@ all deliver to the same inbox.
_DOT_INSENSITIVE = {"gmail.com", "googlemail.com"}
_PLUS_ALIASING = _DOT_INSENSITIVE | {
"outlook.com", "hotmail.com", "live.com", "icloud.com", "me.com",
"fastmail.com", "protonmail.com", "proton.me", "yahoo.com",
}
def _load_list(path: str) -> set:
domains = set()
try:
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip().lower()
if line and not line.startswith("#"):
domains.add(line)
except FileNotFoundError:
pass
return domains
_DISPOSABLE = _load_list(_DOMAINS_FILE)
def is_disposable(email: str) -> bool:
"""True if the address's domain is a known disposable/temp-mail provider."""
domain = (email or "").rsplit("@", 1)[-1].strip().lower()
return domain in _DISPOSABLE
def normalize_email(email: str) -> str:
"""Canonical form used as the account key.
Lowercases; strips a +tag from providers that ignore it; strips dots from
the Gmail local part. Non-aliasing providers keep their local part intact
so we never merge two genuinely different addresses.
"""
email = (email or "").strip().lower()
if "@" not in email:
return email
local, domain = email.rsplit("@", 1)
if domain in _PLUS_ALIASING and "+" in local:
local = local.split("+", 1)[0]
if domain in _DOT_INSENSITIVE:
local = local.replace(".", "")
return f"{local}@{domain}"
def disposable_count() -> int:
return len(_DISPOSABLE)
# --------------------------------------------------------------------------- #
# MX verification
# --------------------------------------------------------------------------- #
# Disposable providers rotate their front domains faster than any blocklist
# (onldm.net was one of 10minutemail's), but every front domain points its MX
# at the provider's real SMTP hosts, which stay put. Matching the MX target
# catches the whole rotation at once. Suffix match against the domains in
# disposable_mx.txt — same ops workflow as the sign-up blocklist above.
_MX_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"disposable_mx.txt")
_DISPOSABLE_MX = _load_list(_MX_FILE)
MX_OK = "ok"
MX_NONE = "no_mx"
MX_DISPOSABLE = "disposable_mx"
_MX_TIMEOUT = 4.0 # seconds; a slow resolver must not stall sign-in
_MX_CACHE_TTL = 3600.0 # verdicts computed from an actual DNS answer
_MX_ERROR_TTL = 60.0 # error-derived verdicts: a blip must not stick for 1h
_MX_CACHE_MAX = 10_000 # bots probing random domains must not grow it unbounded
_mx_cache = {} # domain -> (verdict, monotonic expiry)
_resolver = None
def classify_mx_hosts(hosts) -> str:
"""Verdict from a domain's MX target hostnames."""
hosts = [str(h).rstrip(".").lower() for h in hosts]
# RFC 7505 null MX (a single "." target): the domain declares it takes no mail.
if not any(hosts):
return MX_NONE
for host in hosts:
if any(host == d or host.endswith("." + d) for d in _DISPOSABLE_MX):
return MX_DISPOSABLE
return MX_OK
def _get_resolver():
# One shared resolver: reads resolv.conf once, and its LRU cache honors
# each record's real TTL, so a junk-domain flood can't force live lookups
# for the hot legit domains (gmail, outlook, …).
global _resolver
import dns.asyncresolver
import dns.resolver
if _resolver is None:
r = dns.asyncresolver.Resolver()
r.lifetime = _MX_TIMEOUT
r.cache = dns.resolver.LRUCache()
_resolver = r
return _resolver
async def _resolve(domain: str, rtype: str):
return await _get_resolver().resolve(domain, rtype)
async def _implicit_mx(domain: str):
"""RFC 5321 implicit MX: no MX record → deliverable if A or AAAA exists."""
import dns.resolver
for rtype in ("A", "AAAA"):
try:
await _resolve(domain, rtype)
return MX_OK, _MX_CACHE_TTL
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
continue
except Exception:
return MX_OK, _MX_ERROR_TTL
return MX_NONE, _MX_ERROR_TTL
async def mx_verdict(email: str) -> str:
"""MX_OK / MX_NONE / MX_DISPOSABLE for the address's domain.
Fails open (MX_OK) on resolver trouble — a DNS blip must never lock real
users out of sign-in — and error-derived verdicts are cached only briefly
so a transient NXDOMAIN can't pin a lockout for an hour.
"""
import dns.resolver
domain = (email or "").rsplit("@", 1)[-1].strip().lower()
if not domain:
return MX_NONE
now = time.monotonic()
hit = _mx_cache.get(domain)
if hit and hit[1] > now:
return hit[0]
ttl = _MX_CACHE_TTL
try:
answers = await _resolve(domain, "MX")
verdict = classify_mx_hosts(r.exchange for r in answers)
except dns.resolver.NXDOMAIN:
verdict, ttl = MX_NONE, _MX_ERROR_TTL
except dns.resolver.NoAnswer:
verdict, ttl = await _implicit_mx(domain)
except Exception:
verdict, ttl = MX_OK, _MX_ERROR_TTL
# FIFO-evict one entry when full (dicts keep insertion order) — a flood of
# junk domains must not wipe the whole cache at once.
while len(_mx_cache) >= _MX_CACHE_MAX:
_mx_cache.pop(next(iter(_mx_cache)))
_mx_cache[domain] = (verdict, now + ttl)
return verdict

View file

@ -1,326 +0,0 @@
"""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, headers: dict | None = None):
msg = EmailMessage()
msg["From"] = settings.email_from
msg["To"] = to
msg["Subject"] = subject
for name, value in (headers or {}).items():
msg[name] = value
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, headers: dict | None = None):
"""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, headers)
except Exception as e:
print(f"⚠️ Failed to send email to {to}: {e}")
async def send_commercial_email(user_id, to: str, subject: str, html: str) -> bool:
"""Send a commercial communication (LSSI art. 21): never to an account that
unsubscribed, and always with a one-click way out (footer link plus the
``List-Unsubscribe`` header, see cloud/marketing.py). Returns False when
the account had opted out and nothing was sent.
"""
from . import marketing
if user_id is not None and await marketing.is_opted_out(user_id):
return False
unsub = marketing.unsubscribe_url(user_id) if user_id is not None else ""
headers = {}
if unsub:
footer = (f'<a href="{unsub}" style="color:#666">Unsubscribe</a> from '
"upgrade and tips emails.")
headers = {"List-Unsubscribe": f"<{unsub}>",
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click"}
else:
footer = "Reply to this email if you'd rather not get upgrade and tips emails."
html = (f'{html}<p style="font-family:system-ui,sans-serif;max-width:480px;'
f'margin:24px auto 0;color:#666;font-size:12px">{footer}</p>')
await send_email(to, subject, html, headers)
return True
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)
GITHUB_REPO_URL = "https://github.com/mutonby/openshorts"
async def send_clips_ready_email(email: str, job_title: str, clip_count: int,
dashboard_url: str):
"""Job-completion notice: lets the user close the tab during processing."""
title = (job_title or "Your video").strip()
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Your clips are ready 🎬</h2>
<p><strong>{title}</strong> produced {clip_count} viral-ready
clip{'s' if clip_count != 1 else ''}. They're waiting in your dashboard.</p>
<p><a href="{dashboard_url}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">View my clips</a></p>
<p style="color:#666;font-size:13px">Enjoying OpenShorts? A
<a href="{GITHUB_REPO_URL}" style="color:#666">star on GitHub</a> helps a lot ⭐</p>
</div>
"""
await send_email(email, f"Your clips are ready — {title}", html)
async def send_autopilot_clips_email(email: str, video_title: str, clip_count: int,
scheduled_count: int, dashboard_url: str):
"""Autopilot finished clipping a new channel video on its own.
This is the email that makes Autopilot visible: the user did nothing, and
this is where they find out the work got done anyway.
"""
import html as _html
title = _html.escape((video_title or "your new video").strip())
plural = "s" if clip_count != 1 else ""
if scheduled_count:
posting = (f"<p>The best {scheduled_count} {'is' if scheduled_count == 1 else 'are'} "
f"scheduled to publish, one a day, on the accounts you picked.</p>")
else:
posting = "<p>Review them, tweak anything you like, and post the ones you want.</p>"
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Autopilot clipped your new video 🎬</h2>
<p>You published <strong>{title}</strong> and OpenShorts already turned it
into {clip_count} short{plural}.</p>
{posting}
<p><a href="{dashboard_url}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">See my clips</a></p>
<p style="color:#666;font-size:13px">You can pause Autopilot anytime from the
Autopilot page in your dashboard.</p>
</div>
"""
await send_email(email, f"Autopilot: {clip_count} new short{plural} from your video", html)
async def send_clips_expiring_email(email: str, clip_count: int):
"""Free clips enter their last day before deletion — honest loss aversion.
The deadline is real (FREE_CLIP_RETENTION_DAYS); this simply makes it
visible instead of deleting silently. Doubles as re-engagement for users
who clipped once and went quiet.
"""
# The app has no /dashboard route and never has: it is a single-page app
# routed entirely through the hash, and #app is what opens it (see
# dashboard/src/main.jsx). /dashboard used to land on the SPA fallback, so
# the button quietly showed the marketing page; now that unknown paths
# return a real 404 it fails visibly.
dash = f"{settings.frontend_url}/#app"
n = clip_count
clips = f"{n} clip" + ("s" if n != 1 else "")
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Your {clips} will be deleted tomorrow ⏳</h2>
<p>Free clips are stored for 7 days, and {('these' if n != 1 else 'this one')}
{'are' if n != 1 else 'is'} about to expire. Two ways to keep them:</p>
<ul style="line-height:1.9;padding-left:20px">
<li><strong>Download them now</strong> from your dashboard, or</li>
<li><strong>Upgrade to Starter ($12/mo)</strong> &mdash; clips stored forever,
no watermark, and 100 minutes every month.</li>
</ul>
<p><a href="{dash}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">Save my clips</a></p>
<p style="color:#666;font-size:13px">After tomorrow they're gone for good
&mdash; we can't recover deleted clips.</p>
</div>
"""
print(f"⏳ Clips-expiring email → {email} ({clips})")
await send_email(email, f"Your {clips} will be deleted tomorrow", html)
async def send_out_of_minutes_email(email: str, upgrade_url: str, user_id=None):
"""Free user hit their monthly quota — the natural upgrade moment.
Mirrors the in-app upgrade modal: lead with what they lose by staying free
(watermark, clips deleted after 7 days) and one concrete plan, not a
generic pricing link.
"""
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Your video is still waiting 🎬</h2>
<p>You've used this month's 20 free minutes — which usually means the
clips are working for you. Here's what <strong>Starter ($12/mo)</strong>
changes today:</p>
<ul style="line-height:1.9;padding-left:20px">
<li><strong>100 minutes</strong> every month (5&times; your free quota)</li>
<li><strong>No watermark</strong> on your clips</li>
<li>Clips stored <strong>forever</strong> &mdash; free clips are deleted after 7 days</li>
</ul>
<p><a href="{upgrade_url}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">Upgrade and finish your video</a></p>
<p style="color:#666;font-size:13px">Cancel anytime. Your free minutes
reset on the 1st of every month.</p>
</div>
"""
if await send_commercial_email(user_id, email,
"Your video is waiting — you're out of free minutes", html):
print(f"✉️ Out-of-minutes upsell email → {email}")
async def send_account_deleted_email(email: str):
"""Confirmation that an account was erased. Sent last, to an address we no
longer hold: this is the only notice the user will ever get, and it is also
the only signal they would have if the deletion had not been theirs.
"""
html = """
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Your OpenShorts account has been deleted</h2>
<p>Everything is gone: your account, your projects, your clips and their
transcripts, your API keys, and the connection to any social accounts
you had linked. Any active subscription was cancelled.</p>
<p>Two things we keep, and why:</p>
<ul style="line-height:1.7;padding-left:20px">
<li><strong>Your invoices</strong>, for six years &mdash; Spanish
commercial law requires it, and the Stripe customer reference
that finds them goes with it.</li>
<li><strong>A record that this deletion happened</strong>, for five
years, holding a one-way hash of your email address instead of
the address itself.</li>
</ul>
<p>You can sign up again any time with the same address; it will be a
brand-new, empty account.</p>
<p style="color:#666;font-size:13px">If this wasn't you, reply to this
email straight away &mdash; info@openshorts.app.</p>
</div>
"""
print(f"✉️ Account-deleted confirmation → {email}")
await send_email(email, "Your OpenShorts account has been deleted", html)
# --------------------------------------------------------------------------- #
# Lifecycle emails (cloud/lifecycle.py decides who gets which, and when).
# All of them are commercial communications: send_commercial_email skips
# accounts that unsubscribed and adds the unsubscribe footer and header.
# --------------------------------------------------------------------------- #
def _cta(url: str, label: str) -> str:
return (f'<p><a href="{url}" style="display:inline-block;background:#111;color:#fff;'
f'padding:12px 20px;border-radius:8px;text-decoration:none">{label}</a></p>')
def _first_video_line(first_video_minutes: int) -> str:
if first_video_minutes > 0:
return (f"<p><strong>Your first video is on us:</strong> anything up to "
f"{first_video_minutes} minutes is clipped whole, free.</p>")
return "<p>You get 20 free minutes every month.</p>"
async def send_welcome_email(user_id, email: str, first_video_minutes: int) -> bool:
"""Right after sign-up: one concrete next step, not a feature tour."""
app_url = f"{settings.frontend_url}/#app"
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Welcome to OpenShorts 👋</h2>
<p>Paste a YouTube link (or upload a video) and you get vertical clips
with captions, ready for TikTok, Reels and Shorts, in a few minutes.</p>
{_first_video_line(first_video_minutes)}
{_cta(app_url, "Clip my first video")}
<p style="color:#666;font-size:13px">Works best with people talking:
podcasts, interviews, streams, tutorials.</p>
</div>
"""
return await send_commercial_email(user_id, email, "Your first video is on us", html)
async def send_first_clip_email(user_id, email: str, first_video_minutes: int) -> bool:
"""A day after sign-up with no video processed yet."""
app_url = f"{settings.frontend_url}/#app"
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Your clips are one link away</h2>
<p>You signed up yesterday but haven't clipped anything yet. It takes
one step: paste the link of a video you already published.</p>
{_first_video_line(first_video_minutes)}
{_cta(app_url, "Paste a link")}
<p style="color:#666;font-size:13px">Stuck on something? Just reply to
this email.</p>
</div>
"""
return await send_commercial_email(user_id, email, "Your first video is still free", html)
async def send_winback_email(user_id, email: str, promo_code: str = "",
promo_label: str = "") -> bool:
"""Two days after the first free video, still no plan."""
pricing = f"{settings.frontend_url}/#/pricing"
if promo_code:
offer = (f"<p>Here's <strong>{promo_label or 'a discount'}</strong>: use code "
f"<strong style=\"font-family:monospace;font-size:16px\">{promo_code}</strong> "
f"at checkout.</p>")
subject = f"{promo_label or 'A discount'} on OpenShorts, for you"
else:
offer = ""
subject = "Keep your clips, lose the watermark"
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Liked your clips?</h2>
<p>Free clips carry a watermark and are deleted after 7 days. Starter
($12/mo) gives you 100 minutes a month, no watermark, and clips
stored forever. The clips you already made lose the mark the
moment you upgrade.</p>
{offer}
{_cta(pricing, "See plans")}
<p style="color:#666;font-size:13px">Cancel anytime.</p>
</div>
"""
return await send_commercial_email(user_id, email, subject, html)
async def send_checkout_recovery_email(user_id, email: str, recovery_url: str,
amount_label: str = "") -> bool:
"""A Stripe Checkout expired unpaid. ``recovery_url`` reopens the same cart
(valid 30 days, Stripe's ``after_expiration.recovery``)."""
what = f"your OpenShorts plan ({amount_label})" if amount_label else "your OpenShorts plan"
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>You didn't finish checking out</h2>
<p>You started upgrading to {what} but the payment wasn't completed.
Your cart is saved: one click takes you back to it.</p>
{_cta(recovery_url, "Finish checkout")}
<p style="color:#666;font-size:13px">Card declined? PayPal and other
methods are on the same page. Reply to this email if something
didn't work.</p>
</div>
"""
return await send_commercial_email(user_id, email, "Your OpenShorts checkout is saved", html)

View file

@ -1,232 +0,0 @@
"""Lifecycle emails: the follow-ups a free sign-up gets on the way to a plan.
Measured on the 30 days to 27-sep-2026: 8.5k sign-ups, ~4.3k with clips, ~400
checkouts started, ~90 paid, and until now not one email in between: no
welcome, no nudge for the half that never clipped anything, nothing after an
abandoned Stripe Checkout (1,011 expired sessions since launch). Four emails,
each at most once per account:
* ``welcome`` — minutes after sign-up.
* ``first_clip`` — 24-72 h after sign-up, nothing processed yet.
* ``winback`` — 2-7 days after the first processed video, no plan.
Carries ``WINBACK_PROMO_CODE`` when it is set (a
Stripe promotion code; lives in the env, not here,
because this repository is public).
* ``checkout_recovery`` — on ``checkout.session.expired`` (billing webhook),
with Stripe's recovery URL for the same cart.
The first three come from a loop (``TICK_SECONDS``) that sends at most
``BATCH`` per tick, so the backlog on the first deploy drains slowly instead
of hammering the SMTP relay. A ``LifecycleEmail`` row is inserted before each
send; its (user_id, kind) unique constraint is what stops a second container
(during a rolling deploy) or a second tick from sending the same email.
All four are commercial communications: they go through
``emails.send_commercial_email`` (skips unsubscribed accounts, adds the
unsubscribe footer and header). ``LIFECYCLE_EMAILS_DISABLED=1`` turns the loop
and the recovery email off.
"""
import asyncio
import os
from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, exists, func, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from . import config, database, emails, metering
from .models import LifecycleEmail, Subscription, UsageLedger, User
TICK_SECONDS = 10 * 60
BATCH = 30 # emails per tick, all kinds together (~180/h at most)
WELCOME_AFTER = timedelta(minutes=5)
WELCOME_UNTIL = timedelta(hours=24)
FIRST_CLIP_AFTER = timedelta(hours=24)
FIRST_CLIP_UNTIL = timedelta(hours=72)
WINBACK_AFTER = timedelta(hours=48)
WINBACK_UNTIL = timedelta(days=7)
# Subscription states that mean "already a customer": no upsell, no nudges.
# ``incomplete`` is left out on purpose: that is a Checkout whose first
# payment failed, exactly who the recovery email is for.
_CUSTOMER_STATES = ("active", "trialing", "past_due", "unpaid")
_is_active = None
_task = None
def disabled() -> bool:
return os.environ.get("LIFECYCLE_EMAILS_DISABLED", "").lower() in ("1", "true", "yes")
def _now():
return datetime.now(timezone.utc)
def promo() -> tuple[str, str]:
"""(code, label) of the win-back discount, or ("", "") when unset."""
code = os.environ.get("WINBACK_PROMO_CODE", "").strip()
label = os.environ.get("WINBACK_PROMO_LABEL", "").strip()
return code, (label if code else "")
def amount_label(session_obj: dict) -> str:
""""$12.00" style label for a Checkout Session, or ""."""
amount = session_obj.get("amount_total")
currency = (session_obj.get("currency") or "").upper()
if not amount or not currency:
return ""
value = f"{amount / 100:.2f}"
return f"${value}" if currency == "USD" else f"{value} {currency}"
async def claim(user_id, kind: str) -> bool:
"""Reserve the right to send ``kind`` to this account. True exactly once."""
async with database.session() as s:
async with s.begin():
row = (await s.execute(
pg_insert(LifecycleEmail).values(user_id=user_id, kind=kind)
.on_conflict_do_nothing(constraint="uq_lifecycle_user_kind")
.returning(LifecycleEmail.id)
)).first()
return row is not None
def _not_sent(kind):
return ~exists().where(and_(LifecycleEmail.user_id == User.id,
LifecycleEmail.kind == kind))
def _not_customer():
return ~exists().where(and_(Subscription.user_id == User.id,
Subscription.status.in_(_CUSTOMER_STATES)))
def _processed():
return exists().where(and_(UsageLedger.user_id == User.id,
UsageLedger.job_type == "process",
UsageLedger.status.in_(("reserved", "committed"))))
async def _candidates(kind: str, limit: int, now=None):
"""User rows due for ``kind`` right now (oldest first)."""
now = now or _now()
q = select(User).where(_not_sent(kind), _not_customer(),
User.marketing_opt_out.is_(False))
if kind == "welcome":
q = q.where(User.created_at <= now - WELCOME_AFTER,
User.created_at >= now - WELCOME_UNTIL)
elif kind == "first_clip":
q = q.where(User.created_at <= now - FIRST_CLIP_AFTER,
User.created_at >= now - FIRST_CLIP_UNTIL,
~_processed())
elif kind == "winback":
first_job = (select(func.min(UsageLedger.created_at))
.where(and_(UsageLedger.user_id == User.id,
UsageLedger.job_type == "process",
UsageLedger.status == "committed"))
.scalar_subquery())
q = q.where(first_job <= now - WINBACK_AFTER, first_job >= now - WINBACK_UNTIL)
else:
raise ValueError(kind)
async with database.session() as s:
return list((await s.execute(q.order_by(User.created_at.asc()).limit(limit))).scalars())
async def _send(kind: str, user) -> bool:
# The welcome and first-clip emails promise free minutes: only to accounts
# that actually have them (not temp-mail, not re-registered after erasure).
# Claimed first even when skipped, so an ineligible account is not picked
# up (and does not eat the batch) again on every tick.
if not await claim(user.id, kind):
return False
first_video = config.FIRST_VIDEO_MAX_MINUTES
if kind in ("welcome", "first_clip"):
if not metering.free_plan_eligible(user):
return False
# A first video already processed (welcome sent late) has no grant left.
if await metering.has_processed_before(user.id):
first_video = 0
if kind == "welcome":
return await emails.send_welcome_email(user.id, user.email, first_video)
if kind == "first_clip":
return await emails.send_first_clip_email(user.id, user.email, first_video)
code, label = promo()
return await emails.send_winback_email(user.id, user.email, code, label)
async def run_once(now=None) -> int:
"""One tick: send up to ``BATCH`` due emails. Returns how many went out."""
budget = BATCH
sent = 0
for kind in ("welcome", "first_clip", "winback"):
if budget <= 0:
break
for user in await _candidates(kind, budget, now):
if _is_active is not None and not _is_active():
return sent # draining for a deploy: the new instance takes over
try:
if await _send(kind, user):
sent += 1
except Exception as e:
print(f"⚠️ Lifecycle {kind} email failed for {user.id}: {e}")
budget -= 1
await asyncio.sleep(1) # be gentle with the SMTP relay
if sent:
print(f"✉️ Lifecycle emails sent this tick: {sent}")
return sent
async def _recovery_target(user_id):
"""The account behind an expired checkout, unless it is gone or already
paying (it may have paid in another session meanwhile)."""
async with database.session() as s:
user = await s.get(User, user_id)
if user is None:
return None
customer = (await s.execute(select(Subscription.id).where(and_(
Subscription.user_id == user.id,
Subscription.status.in_(_CUSTOMER_STATES))))).first()
return None if customer is not None else user
async def on_checkout_expired(session_obj: dict) -> bool:
"""``checkout.session.expired``: mail the recovery link, once per account."""
if disabled():
return False
recovery = ((session_obj.get("after_expiration") or {}).get("recovery") or {})
url = recovery.get("url")
user_id = (session_obj.get("client_reference_id")
or (session_obj.get("metadata") or {}).get("user_id"))
if not url or not user_id:
return False
user = await _recovery_target(user_id)
if user is None:
return False
if not await claim(user.id, "checkout_recovery"):
return False
return await emails.send_checkout_recovery_email(
user.id, user.email, url, amount_label(session_obj))
async def _loop():
await asyncio.sleep(90) # let the instance finish booting and resuming jobs
while True:
try:
if _is_active is None or _is_active():
await run_once()
except asyncio.CancelledError:
return
except Exception as e:
print(f"⚠️ Lifecycle loop error: {e}")
await asyncio.sleep(TICK_SECONDS)
def start(is_active=None):
"""Start the loop. ``is_active`` returns False while the instance drains."""
global _is_active, _task
_is_active = is_active
if disabled():
print("✉️ Lifecycle emails disabled (LIFECYCLE_EMAILS_DISABLED).")
return
_task = asyncio.create_task(_loop())

View file

@ -1,25 +0,0 @@
"""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

View file

@ -1,107 +0,0 @@
"""Opting out of the emails we send that are commercial communications.
Most messages OpenShorts sends are service notices: a sign-in link, "your
clips are ready", "your free clips are deleted tomorrow", "your account has been
deleted". ``send_out_of_minutes_email`` and the lifecycle emails
(cloud/lifecycle.py) are not — they sell a plan, which makes them a
comunicación comercial under LSSI art. 21. Art. 21.2 permits them to an
existing customer for a similar product, but only if *every single message*
offers a simple, free way to refuse: ``emails.send_commercial_email`` adds the
footer link and the ``List-Unsubscribe`` header, and skips opted-out accounts.
The link has to work with no session (the reader is in their mail client, not
the app) and must never expire, so it carries an HMAC of the user id keyed on
the app's JWT secret. That token proves nothing except "the holder was sent an
email addressed to this account", and the only thing it can do is set the flag
— it cannot read anything, and it cannot re-subscribe anyone.
"""
import hashlib
import hmac
from fastapi import APIRouter
from fastapi.responses import HTMLResponse
from sqlalchemy import update
from . import database
from .config import settings
from .models import User
router = APIRouter(prefix="/api/marketing", tags=["marketing"])
def unsubscribe_token(user_id) -> str:
return hmac.new(settings.jwt_secret.encode(), f"unsub:{user_id}".encode(),
hashlib.sha256).hexdigest()[:32]
def unsubscribe_url(user_id) -> str:
"""The absolute link that goes in the email body and the header.
Empty when PUBLIC_API_URL is unset, and ``emails.py`` then falls back to a
plain "reply to this email" line rather than printing a broken link.
"""
base = settings.public_api_url
if not base or not settings.jwt_secret:
return ""
return (f"{base}/api/marketing/unsubscribe"
f"?u={user_id}&t={unsubscribe_token(user_id)}")
async def is_opted_out(user_id) -> bool:
"""True when this account has refused commercial email."""
from sqlalchemy import select
async with database.session() as s:
value = (await s.execute(
select(User.marketing_opt_out).where(User.id == user_id)
)).scalar_one_or_none()
return bool(value)
_PAGE = """<!doctype html><meta charset="utf-8">
<title>%(title)s</title>
<style>body{font:16px/1.6 system-ui,sans-serif;max-width:34rem;margin:12vh auto;
padding:0 1.5rem;color:#111}h1{font-size:1.35rem}a{color:#111}</style>
<h1>%(title)s</h1><p>%(body)s</p>"""
def _page(title, body, status=200):
return HTMLResponse(_PAGE % {"title": title, "body": body}, status_code=status)
async def _opt_out(u: str, t: str):
if not u or not t or not settings.jwt_secret:
return _page("That link didn't work",
"The unsubscribe link is incomplete. Email "
"<a href='mailto:info@openshorts.app'>info@openshorts.app</a> "
"and we'll do it by hand.", status=400)
if not hmac.compare_digest(t, unsubscribe_token(u)):
return _page("That link didn't work",
"We couldn't verify this unsubscribe link. Email "
"<a href='mailto:info@openshorts.app'>info@openshorts.app</a> "
"and we'll do it by hand.", status=400)
try:
async with database.session() as s:
async with s.begin():
await s.execute(update(User).where(User.id == u)
.values(marketing_opt_out=True))
except Exception:
# A malformed uuid, or the account is already gone. Both mean there is
# nothing left to mail, so the honest answer is still "done".
pass
return _page("You're unsubscribed",
"We won't send you upgrade emails again. You will still get "
"the messages the service itself needs to send you — your "
"sign-in link, and a warning before clips are deleted. You can "
"delete your account entirely from Account → Delete account.")
@router.get("/unsubscribe", response_class=HTMLResponse)
async def unsubscribe_get(u: str = "", t: str = ""):
return await _opt_out(u, t)
@router.post("/unsubscribe", response_class=HTMLResponse)
async def unsubscribe_post(u: str = "", t: str = ""):
"""RFC 8058 one-click. Gmail and Outlook POST this URL from their own
"Unsubscribe" button, without ever showing the user our page."""
return await _opt_out(u, t)

View file

@ -1,357 +0,0 @@
"""OAuth 2.1 authorization server for the MCP endpoint (cloud mode).
claude.ai and ChatGPT connect to a remote MCP server by URL alone: the user
pastes ``https://mcp.openshorts.app/mcp`` and the client discovers how to log
in from the server's metadata. That takes the pieces those clients actually
use, and nothing else:
* RFC 9728 protected-resource metadata (``/.well-known/oauth-protected-resource``),
which the ``/mcp`` 401 points at via ``WWW-Authenticate``;
* RFC 8414 authorization-server metadata (``/.well-known/oauth-authorization-server``);
* RFC 7591 dynamic client registration (``POST /oauth/register``), because
neither client ships a pre-shared client id;
* the authorization-code grant with PKCE S256 and **no client secret**: these
are public clients, PKCE is what binds the code to whoever started the flow.
The consent screen lives in the dashboard (``#/oauth/authorize``), not here:
the session is a bearer JWT in localStorage on www.openshorts.app, which a
plain browser GET to the API cannot see. So ``GET /oauth/authorize`` validates
the request and bounces to the dashboard, the dashboard signs the user in if
needed and asks "connect Claude to your account?", and ``POST /api/oauth/authorize``
(session-authenticated) mints the code and hands back the redirect.
Redeeming the code mints an ordinary ``osk_`` API key named after the client
and returns it as the access token. That is deliberate: every existing auth,
quota and ownership rule already understands those keys, the connection shows
up in the account page next to hand-made keys, and revoking it there is how
the user disconnects the client. No refresh tokens: the key does not expire.
"""
import base64
import hashlib
import json
import secrets
from datetime import datetime, timedelta, timezone
from typing import Optional
from urllib.parse import urlencode, urlsplit, urlunsplit, parse_qsl
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse, RedirectResponse
from pydantic import BaseModel
from sqlalchemy import select
from . import database, api_keys
from .config import settings
from .models import OAuthClient, OAuthCode, ApiKey
router = APIRouter()
SCOPE = "openshorts"
CODE_TTL = timedelta(minutes=10)
MAX_REDIRECT_URIS = 10
def _now():
return datetime.now(timezone.utc)
# --------------------------------------------------------------------------- #
# Pure helpers (unit-tested without a database)
# --------------------------------------------------------------------------- #
def base_url(request: Request) -> str:
"""The origin the client is talking to, so the metadata names the host the
client actually used (mcp.openshorts.app or api.openshorts.app both route
here). uvicorn runs with --proxy-headers, so the scheme is the public one."""
u = request.base_url
return f"{u.scheme}://{u.netloc}"
def resource_metadata(base: str) -> dict:
return {
"resource": f"{base}/mcp",
"authorization_servers": [base],
"bearer_methods_supported": ["header"],
"scopes_supported": [SCOPE],
"resource_name": "OpenShorts",
"resource_documentation": "https://www.openshorts.app/mcp",
}
def server_metadata(base: str) -> dict:
return {
"issuer": base,
"authorization_endpoint": f"{base}/oauth/authorize",
"token_endpoint": f"{base}/oauth/token",
"registration_endpoint": f"{base}/oauth/register",
"response_types_supported": ["code"],
"response_modes_supported": ["query"],
"grant_types_supported": ["authorization_code"],
"code_challenge_methods_supported": ["S256"],
"token_endpoint_auth_methods_supported": ["none"],
"scopes_supported": [SCOPE],
"service_documentation": "https://www.openshorts.app/mcp",
}
def valid_redirect_uri(uri: str) -> bool:
"""https anywhere, or plain http only on the loopback (CLI clients open a
local listener to catch the redirect). No fragments, no wildcards."""
try:
p = urlsplit(uri)
except ValueError:
return False
if p.fragment or not p.netloc:
return False
host = (p.hostname or "").lower()
if p.scheme == "https":
return True
if p.scheme == "http":
return host in ("localhost", "127.0.0.1", "::1")
return False
def pkce_matches(code_verifier: str, code_challenge: str) -> bool:
if not code_verifier or not code_challenge:
return False
if not (43 <= len(code_verifier) <= 128):
return False
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
expected = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
return secrets.compare_digest(expected, code_challenge)
def add_query(uri: str, **params) -> str:
"""Append params to a redirect URI, keeping any query it already has."""
p = urlsplit(uri)
q = parse_qsl(p.query, keep_blank_values=True)
q.extend((k, v) for k, v in params.items() if v is not None)
return urlunsplit((p.scheme, p.netloc, p.path, urlencode(q), ""))
def hash_code(code: str) -> str:
return hashlib.sha256(code.encode()).hexdigest()
def consent_url(base_frontend: str, params: dict) -> str:
"""Where the dashboard renders the consent screen. The params ride in the
hash's query so the SPA (hash router) can read them."""
return f"{base_frontend.rstrip('/')}/#/oauth/authorize?{urlencode(params)}"
def _oauth_error(status: int, error: str, description: str):
return JSONResponse({"error": error, "error_description": description}, status_code=status)
# --------------------------------------------------------------------------- #
# Discovery
# --------------------------------------------------------------------------- #
@router.get("/.well-known/oauth-protected-resource")
@router.get("/.well-known/oauth-protected-resource/mcp")
async def protected_resource(request: Request):
return JSONResponse(resource_metadata(base_url(request)),
headers={"Access-Control-Allow-Origin": "*"})
@router.get("/.well-known/oauth-authorization-server")
@router.get("/.well-known/oauth-authorization-server/mcp")
async def authorization_server(request: Request):
return JSONResponse(server_metadata(base_url(request)),
headers={"Access-Control-Allow-Origin": "*"})
# --------------------------------------------------------------------------- #
# Dynamic client registration (RFC 7591)
# --------------------------------------------------------------------------- #
@router.post("/oauth/register", status_code=201)
async def register_client(request: Request):
try:
body = json.loads(await request.body() or b"{}")
except ValueError:
return _oauth_error(400, "invalid_client_metadata", "Body must be JSON.")
if not isinstance(body, dict):
return _oauth_error(400, "invalid_client_metadata", "Body must be a JSON object.")
uris = body.get("redirect_uris")
if not isinstance(uris, list) or not uris or len(uris) > MAX_REDIRECT_URIS:
return _oauth_error(400, "invalid_redirect_uri",
f"redirect_uris must list 1 to {MAX_REDIRECT_URIS} URIs.")
uris = [str(u) for u in uris]
bad = [u for u in uris if not valid_redirect_uri(u)]
if bad:
return _oauth_error(400, "invalid_redirect_uri",
f"redirect_uris must be https (or http on localhost): {bad[0]}")
auth_method = body.get("token_endpoint_auth_method") or "none"
if auth_method != "none":
return _oauth_error(400, "invalid_client_metadata",
"Only public clients (token_endpoint_auth_method=none) are supported.")
grants = body.get("grant_types") or ["authorization_code"]
if any(g not in ("authorization_code", "refresh_token") for g in grants):
return _oauth_error(400, "invalid_client_metadata",
"Only the authorization_code grant is supported.")
name = str(body.get("client_name") or "MCP client").strip()[:80] or "MCP client"
client_id = secrets.token_urlsafe(24)
async with database.session() as session:
session.add(OAuthClient(id=client_id, client_name=name, redirect_uris=json.dumps(uris)))
await session.commit()
return JSONResponse({
"client_id": client_id,
"client_id_issued_at": int(_now().timestamp()),
"client_name": name,
"redirect_uris": uris,
"token_endpoint_auth_method": "none",
"grant_types": ["authorization_code"],
"response_types": ["code"],
"scope": SCOPE,
}, status_code=201, headers={"Access-Control-Allow-Origin": "*"})
async def _load_client(client_id: str) -> Optional[OAuthClient]:
if not client_id:
return None
async with database.session() as session:
return (await session.execute(
select(OAuthClient).where(OAuthClient.id == client_id))).scalar_one_or_none()
def _client_allows(client: OAuthClient, redirect_uri: str) -> bool:
try:
return redirect_uri in json.loads(client.redirect_uris)
except ValueError:
return False
# --------------------------------------------------------------------------- #
# Authorization: browser GET bounces to the dashboard consent screen
# --------------------------------------------------------------------------- #
AUTHORIZE_PARAMS = ("client_id", "redirect_uri", "response_type", "state",
"code_challenge", "code_challenge_method", "scope", "resource")
async def _validate_authorize(params: dict):
"""Returns (client, error) where error is (code, description). A bad
client_id / redirect_uri is reported to the user, never redirected: the
spec forbids sending the browser to an unverified URI."""
client = await _load_client(params.get("client_id", ""))
if client is None:
raise HTTPException(status_code=400, detail="Unknown client_id.")
redirect_uri = params.get("redirect_uri", "")
if not redirect_uri or not _client_allows(client, redirect_uri):
raise HTTPException(status_code=400, detail="redirect_uri is not registered for this client.")
if params.get("response_type") != "code":
return client, ("unsupported_response_type", "Only response_type=code is supported.")
if not params.get("code_challenge"):
return client, ("invalid_request", "PKCE code_challenge is required.")
if (params.get("code_challenge_method") or "S256") != "S256":
return client, ("invalid_request", "Only code_challenge_method=S256 is supported.")
return client, None
@router.get("/oauth/authorize")
async def authorize(request: Request):
params = {k: request.query_params.get(k) for k in AUTHORIZE_PARAMS if request.query_params.get(k)}
client, err = await _validate_authorize(params)
if err:
return RedirectResponse(add_query(params["redirect_uri"], error=err[0],
error_description=err[1], state=params.get("state")),
status_code=302)
return RedirectResponse(consent_url(settings.frontend_url, params), status_code=302)
@router.get("/api/oauth/client/{client_id}")
async def client_info(client_id: str):
"""What the consent screen shows: the name the client registered with."""
client = await _load_client(client_id)
if client is None:
raise HTTPException(status_code=404, detail="Unknown client_id.")
return {"client_id": client.id, "client_name": client.client_name}
class ConsentRequest(BaseModel):
client_id: str
redirect_uri: str
state: Optional[str] = None
code_challenge: str
code_challenge_method: Optional[str] = "S256"
scope: Optional[str] = None
response_type: Optional[str] = "code"
@router.post("/api/oauth/authorize")
async def consent(payload: ConsentRequest, request: Request):
"""The user said yes on the dashboard: mint the code, return where to go."""
from .auth import get_current_user_required
user = await get_current_user_required(request)
params = payload.model_dump(exclude_none=True)
client, err = await _validate_authorize(params)
if err:
return {"redirect": add_query(payload.redirect_uri, error=err[0],
error_description=err[1], state=payload.state)}
code = secrets.token_urlsafe(32)
async with database.session() as session:
session.add(OAuthCode(
code_hash=hash_code(code), client_id=client.id, user_id=user.id,
redirect_uri=payload.redirect_uri, code_challenge=payload.code_challenge,
scope=payload.scope or SCOPE, expires_at=_now() + CODE_TTL))
await session.commit()
return {"redirect": add_query(payload.redirect_uri, code=code, state=payload.state)}
# --------------------------------------------------------------------------- #
# Token
# --------------------------------------------------------------------------- #
@router.post("/oauth/token")
async def token(request: Request):
ctype = request.headers.get("content-type", "")
if "application/json" in ctype:
try:
form = json.loads(await request.body() or b"{}")
except ValueError:
return _oauth_error(400, "invalid_request", "Malformed JSON body.")
else:
form = dict(await request.form())
grant = form.get("grant_type")
if grant != "authorization_code":
return _oauth_error(400, "unsupported_grant_type",
"Only authorization_code is supported (tokens do not expire).")
code = str(form.get("code") or "")
verifier = str(form.get("code_verifier") or "")
client_id = str(form.get("client_id") or "")
redirect_uri = str(form.get("redirect_uri") or "")
async with database.session() as session:
row = (await session.execute(
select(OAuthCode).where(OAuthCode.code_hash == hash_code(code)))).scalar_one_or_none()
if row is None or row.used_at is not None or row.expires_at < _now():
return _oauth_error(400, "invalid_grant", "Unknown, used or expired code.")
if row.client_id != client_id or (redirect_uri and row.redirect_uri != redirect_uri):
return _oauth_error(400, "invalid_grant", "Code was issued to another client or redirect_uri.")
if not pkce_matches(verifier, row.code_challenge):
return _oauth_error(400, "invalid_grant", "PKCE verification failed.")
client = (await session.execute(
select(OAuthClient).where(OAuthClient.id == client_id))).scalar_one_or_none()
row.used_at = _now()
raw, key_hash, prefix = api_keys.generate_key()
session.add(ApiKey(user_id=row.user_id, key_hash=key_hash, prefix=prefix,
name=f"{(client.client_name if client else 'MCP client')[:50]} · connected via OAuth"))
await session.commit()
return JSONResponse({"access_token": raw, "token_type": "bearer", "scope": row.scope or SCOPE},
headers={"Cache-Control": "no-store", "Access-Control-Allow-Origin": "*"})
@router.options("/oauth/register")
@router.options("/oauth/token")
async def preflight():
return JSONResponse({}, headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
})
def www_authenticate(base: str) -> str:
"""Value for the 401 on /mcp: tells an OAuth-capable client where to look."""
return f'Bearer resource_metadata="{base}/.well-known/oauth-protected-resource"'

View file

@ -1,727 +0,0 @@
"""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
from urllib.parse import urlparse
import random
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, FirstVideoGrant
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
# Errors on a free (static) route that a different IP could fix. Only these
# justify spending the per-GB proxy on the same URL; a private, removed or
# members-only video fails the same on every IP, and a live stream has no
# duration anywhere. Before this list every one of those went to the paid
# proxy twice (both extractors), ~1.7 MB a time — the "1.76 MB, 2 requests"
# rows that filled the DataImpulse panel on 31-aug-2026.
_IP_SPECIFIC_HINTS = (
"sign in to confirm you", "not a bot", "http error 403", "http error 429",
"http error 407", "http error 502", "http error 503", "proxyerror",
"tunnel connection failed", "connection reset", "timed out", "timeout",
"unable to download webpage", "unable to download api page",
# "Video unavailable" looks like a content error but is NOT reliable on
# the static pool: on 1-sep-2026 five videos "unavailable" on all three
# Decodo IPs downloaded fine through the residential proxy (proxy_usage
# rows 19:33-07:07). YouTube serves a fake unavailable to IPs it dislikes
# — the same symptom as the 19-aug server-IP ban. A truly dead link costs
# ~3 MB to re-check; a real video wrongly refused costs the job.
"video unavailable",
"remote end closed", "connection refused", "network is unreachable",
"name or service not known", "eof occurred",
)
_CONTENT_HINTS = (
"private video", "has been removed", "members-only",
"join this channel", "not available on this app", "is not a valid url",
"unsupported url", "no video formats found", "premieres in", "will begin in",
"this live event", "no duration in metadata", "requested format is not available",
"account has been terminated", "video is age", "confirm your age",
# An uploader's country block: the residential pool exits from the same
# blocked countries, so the paid probe failed with the identical error in
# 5 of the 6 cases between 3-sep and 5-sep-2026 (3.6 MB each, and the
# Telegram alert claimed the paid proxy "answered").
"available in your country", "in your country", "geo-restricted", "geoblock",
"blocked it in your country",
)
def static_failure_warrants_paid(err) -> bool:
"""Does this failure on a free route justify retrying through the paid proxy?"""
e = str(err or "").lower()
if any(h in e for h in _CONTENT_HINTS):
return False
return any(h in e for h in _IP_SPECIFIC_HINTS)
# Paid-probe events queued for app.py (thread-safe enough: appended from the
# executor thread that runs the probe, drained on the event loop).
_paid_probe_events: list = []
# URLs whose probe saw EVERY static IP answer the bot-check and the paid proxy
# answer the video. Since 30-sep-2026 that verdict is per video and identical
# on every one of our IPs (measured: 9 of 10 videos, 3 statics + the server's
# own IP, twice each), so the download repeating the four anonymous attempts
# costs ~8 s and four more hits on IPs YouTube is already scoring, for the
# same answer. app.py pops the verdict when it builds the job.
_static_bot_verdicts: set = set()
def pop_statics_bot_checked(url) -> bool:
"""True (once) when the probe of ``url`` found the static pool bot-checked
for this video and had to use the paid proxy."""
try:
_static_bot_verdicts.remove(url)
return True
except KeyError:
return False
def _all_bot_checked(static_errors) -> bool:
return bool(static_errors) and all(
"not a bot" in (e or "") for e in static_errors.values())
def pop_paid_probe_events() -> list:
out, _paid_probe_events[:] = list(_paid_probe_events), []
return out
def plan_probe_proxies(direct_first, statics, paid):
"""Ordered proxies for a metadata probe — pure, unit-tested.
Same cheapest-first order as the download plan (``main.plan_download_attempts``):
the server's own IP when the operator allows it, then the flat-rate static ISP
pool, then the per-GB paid proxy. ``None`` means "no proxy" (direct).
This probe used to read ``PROXY_URL`` only, which it kept doing after the
static pool landed (dfa3124, 19-aug-2026) because that commit never touched
this file. Every managed YouTube submission then paid the per-GB proxy for
~0.2-1 MB of metadata while the download itself went out free over the
statics — and invisibly, since ``PROXY_BYTES`` (main.py) only counts the
bytes of the winning *download* attempt.
"""
order = []
if direct_first or not (statics or paid):
order.append(None)
order.extend(statics)
if paid:
order.append(paid)
return order
def is_youtube_url(url: str) -> bool:
host = (urlparse(url or "").hostname or "").lower()
return host in ("youtube.com", "www.youtube.com", "m.youtube.com", "youtu.be",
"music.youtube.com") or host.endswith(".youtube.com")
def probe_url_minutes(url: str, allow_paid: bool = True) -> float:
"""Return the video duration in minutes from yt-dlp metadata (no download).
Uses the same proxy order + extractor settings as the actual download
(main.py) so the probe behaves consistently with it and bills the same way.
Raises ValueError if the duration is unknown (e.g. live streams).
"""
# SSRF guard: reject non-http(s) / private / metadata hosts before probing.
from security_utils import assert_public_url
assert_public_url(url)
# Throwaway hosts (tmpfiles.org) sign links with a short-lived stamp; take
# the live one so the probe sees the file and not an HTML page.
import file_hosts
url = file_hosts.resolve(url)
# Free and first: a search / playlist / channel page is walked entry by
# entry by yt-dlp and never yields a duration (yt_clients.youtube_non_video_reason).
from yt_clients import NotASingleVideo, youtube_non_video_reason
reason = youtube_non_video_reason(url)
if reason:
raise NotASingleVideo(f"This link is {reason}.")
bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
# Same client lists as the download (yt_clients.py): the authed defaults
# alone answer "Video unavailable" for a share of videos on every IP, and
# each of those probes then paid the per-GB proxy for nothing.
from yt_clients import hd_extractor_args, fallback_extractor_args
hd_args = hd_extractor_args(bgutil_http, bgutil_script)
# (extractor args, send the account cookies). The second attempt on each
# route drops the cookies, exactly like the download's 'fallback-static'
# step (main.py): with the cookies attached YouTube answers UNPLAYABLE for
# every client — web_embedded, tv_downgraded, web AND mweb — on a share of
# videos, and yt-dlp reports that as "Video unavailable" (measured in prod
# 9-sep-2026, all three statics, same video anonymous → 1080p 137+140).
# Without this step the probe read that as an IP problem and escalated to
# the per-GB proxy, which carries the same cookies and fails identically,
# while the download quietly recovered anonymously on the same static.
# With no HD path at all (self-host, no PO token provider) the fallback is
# the only attempt, so it keeps the cookies the operator configured.
strategies = ([(hd_args, True)] if hd_args else []) + [
(fallback_extractor_args(bgutil_http, bgutil_script), not hd_args)]
# Rotated per probe to spread load across the pool, like the download does.
statics = [p.strip() for p in
os.environ.get("STATIC_PROXY_URLS", "").split(",") if p.strip()]
if statics:
k = random.randrange(len(statics))
statics = statics[k:] + statics[:k]
paid = os.environ.get("PROXY_URL", "").strip()
if not allow_paid:
paid = "" # daily budget hit (cloud/proxy_ledger.budget_exceeded)
# Same rule as the download plan: a non-YouTube URL never touches the
# per-GB proxy (main.plan_download_attempts, youtube=False). Twitch, Kick,
# Rumble, product pages and drive links were all reaching it here.
if not is_youtube_url(url):
paid = ""
proxies = plan_probe_proxies(
os.environ.get("DIRECT_FIRST", "").strip() == "1",
statics,
paid,
)
static_errors: dict = {}
# Same cookies + PO token the download uses: an anonymous probe gets
# "Sign in to confirm you're not a bot" from the static IPs (4-sep-2026,
# all three, ~10 probes/day paying 1.8 MB each on the per-GB proxy)
# while the authenticated download sails through the same IPs.
cookies_env = os.environ.get("YOUTUBE_COOKIES")
ck_path = None
if cookies_env:
import tempfile
fd, ck_path = tempfile.mkstemp(prefix="probe_ck_", suffix=".txt")
with os.fdopen(fd, "w") as f:
f.write(cookies_env)
try:
return _probe_with_proxies(url, proxies, strategies, static_errors,
paid, ck_path)
finally:
if ck_path:
try:
os.remove(ck_path)
except OSError:
pass
def _probe_with_proxies(url, proxies, strategies, static_errors, paid, ck_path):
"""Walk the proxy chain (outer) x extractor strategies (inner) until one
reports a duration. Split out of ``probe_url_minutes`` so the temporary
cookie file has one obvious lifetime.
A dead route in the chain is routine (the proxy watcher is what reports it,
on Telegram); yt-dlp printing a full ERROR block per failed proxy per
strategy would just flood the API log, hence the quiet logger. The reason
still reaches the caller through ``last_err``.
"""
import yt_dlp
class _QuietLogger:
def debug(self, msg): pass
def info(self, msg): pass
def warning(self, msg): pass
def error(self, msg): pass
last_err = None
for proxy in proxies:
is_paid = bool(paid) and proxy == paid
# Every attempt's error on this route, not just the last one. The
# anonymous retry (see probe_url_minutes) on a static IP routinely
# ends in "Sign in to confirm you're not a bot"; if the attempt with
# the cookies had already said "confirm your age" / "Private video",
# that is the verdict, and the bot-check must not turn it into an IP
# problem worth the paid proxy (17-sep-2026, 3QFAEqE9-Kk, twice).
route_errors = []
if is_paid:
# Only spend the per-GB proxy when a free route failed for a
# reason another IP can fix. Content errors and "no duration"
# (live streams) are the same on every IP.
if not static_errors or not any(static_failure_warrants_paid(e)
for e in static_errors.values()):
break
for step, (extractor_args, use_cookies) in enumerate(strategies):
# noplaylist: a URL pasted from a playing playlist or a mix
# (`watch?v=X&list=...`) is that ONE video. Without this yt-dlp
# walks the whole list and fails on its first private / age-gated
# / bot-checked entry, a video the user never asked for; the probe
# then escalated to the per-GB proxy, which walked the same list
# and failed the same way, and the user got a 400 for a valid
# link. 26 of the 37 paid probes between 7 and 17-sep-2026 were
# exactly this (proxy_usage: `list=` and `results?search_query`).
opts = {"skip_download": True, "quiet": True, "no_warnings": True,
"noplaylist": True,
"logger": _QuietLogger(), "extractor_args": extractor_args}
if ck_path and use_cookies:
opts["cookiefile"] = ck_path
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:
if is_paid:
_paid_probe_events.append({
"url": url, "static_errors": dict(static_errors),
"bytes_estimate": 1_800_000 * (1 + step)})
if _all_bot_checked(static_errors):
_static_bot_verdicts.add(url)
return float(duration) / 60.0
last_err = ValueError("no duration in metadata")
if info.get("extractor") == "generic":
# A direct media file: yt-dlp's generic extractor never
# reports a duration, so stop trying proxies and read the
# container header over HTTP instead.
break
except Exception as e:
last_err = e
route_errors.append(str(e)[:300])
else:
if not is_paid:
static_errors[_route_name(proxy, proxies)] = (
" || ".join(route_errors) if route_errors else str(last_err)[:300])
continue
break
if paid and any(p == paid for p in proxies) and static_errors and \
any(static_failure_warrants_paid(e) for e in static_errors.values()) and last_err is not None \
and not isinstance(last_err, ValueError):
# The paid route was tried and failed too: still worth a trail line.
_paid_probe_events.append({"url": url, "static_errors": dict(static_errors),
"bytes_estimate": 3_600_000, "paid_failed": str(last_err)[:200]})
# Direct file URLs (agent uploads on tmpfiles/uguu/R2, a CDN mp4): ffprobe
# fetches just the moov atom via range requests. Also the last resort for
# any URL yt-dlp could not size.
try:
seconds = _ffprobe_url_seconds(url)
if seconds > 0:
return seconds / 60.0
except Exception as e:
last_err = e
raise ValueError(f"Could not determine video duration ({last_err})")
def _route_name(proxy, proxies) -> str:
if proxy is None:
return "direct"
statics = [p for p in proxies if p is not None]
try:
return f"static{statics.index(proxy) + 1}"
except ValueError:
return "proxy"
def _ffprobe_url_seconds(url: str, timeout: int = 30) -> float:
out = subprocess.check_output(
["ffprobe", "-v", "error", "-rw_timeout", str(timeout * 1_000_000),
"-user_agent", "Mozilla/5.0 (OpenShorts probe)",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", url],
stderr=subprocess.STDOUT, timeout=timeout + 5,
)
return float(out.decode().strip() or 0)
# --------------------------------------------------------------------------- #
# Balance computation (assumes caller holds the user lock when mutating)
# --------------------------------------------------------------------------- #
async def _subscription_row(session, user_id):
"""The user's subscription row whatever its status (None if never subscribed).
Distinct from ``_active_subscription``: a row in a state that grants no
minutes (past_due, incomplete, ...) still has to be visible to the UI, or a
customer whose card failed silently reads as a plain free account with no
way to fix it. Entitlement decisions must use ``_active_subscription``.
"""
return (await session.execute(
select(Subscription).where(Subscription.user_id == user_id)
)).scalar_one_or_none()
def _entitles(row) -> bool:
"""True if this subscription row grants plan minutes right now."""
return bool(row and row.status in ("active", "trialing")
and row.current_period_end > _now())
async def _active_subscription(session, user_id):
row = await _subscription_row(session, user_id)
return row if _entitles(row) else None
def free_plan_eligible(user) -> bool:
"""True if this ``User`` row qualifies for the free monthly allowance.
Google accounts always qualify. Email (magic-link) accounts qualify too,
as long as the address isn't a disposable/temp-mail domain — sign-up already
blocks those (cloud/email_policy), and this is the defense-in-depth check so
an old disposable account can't slip through. FREE_PLAN_MINUTES = 0 disables
the free plan entirely.
"""
if user is None or config.FREE_PLAN_MINUTES <= 0:
return False
# Denied accounts (re-registered after an erasure, temp-mail MX): no free
# minutes whatever the sign-in method. getattr: test doubles and rows
# loaded before the column existed.
if getattr(user, "free_plan_denied", None):
return False
if user.google_sub:
return True
# Email account: eligible unless the domain is disposable.
from . import email_policy
return not email_policy.is_disposable(user.email or "")
def free_period_end(now: datetime | None = None) -> datetime:
"""First instant of the next UTC calendar month.
Free-plan ledger rows are tagged with this synthetic ``period_end`` so the
existing period accounting resets them monthly with no cron, exactly like
Stripe periods. A real subscription's ``current_period_end`` is anchored to
the checkout instant, so it can only collide with this value if it lands on
a month start to the second — accepted as negligible.
"""
now = now or _now()
if now.month == 12:
return datetime(now.year + 1, 1, 1, tzinfo=timezone.utc)
return datetime(now.year, now.month + 1, 1, tzinfo=timezone.utc)
async def is_free_user(session, user_id) -> bool:
"""User currently on the free tier (no active/trialing sub).
Used by the retention sweeps: an account whose free minutes were withdrawn
(``free_plan_denied``) still keeps its library on the free 7-day expiry,
not forever.
"""
if await _active_subscription(session, user_id):
return False
user = await session.get(User, user_id)
if user is not None and getattr(user, "free_plan_denied", None):
return True
return free_plan_eligible(user)
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 has_processed_before(user_id) -> bool:
"""True once the account has any live (reserved/committed) process job.
Released reservations (a job that failed or never started) don't count, so
a first video that errors out keeps the first-video grant for the retry.
"""
async with database.session() as session:
row = (await session.execute(
select(UsageLedger.id).where(and_(
UsageLedger.user_id == user_id,
UsageLedger.job_type == "process",
UsageLedger.status.in_(("reserved", "committed")),
)).limit(1)
)).first()
return row is not None
def ip_fingerprint(ip) -> str:
"""HMAC of a client IP (keyed on the app secret), or "" when unknown."""
import hashlib
import hmac
if not ip or ip == "unknown":
return ""
key = (config.settings.jwt_secret or "openshorts").encode()
return hmac.new(key, f"ip:{ip}".encode(), hashlib.sha256).hexdigest()
async def ip_had_first_video(ip_hash: str) -> bool:
"""True when this network already got a live first-video grant inside
``FIRST_VIDEO_IP_WINDOW_DAYS``."""
if not ip_hash:
return False
since = _now() - timedelta(days=config.FIRST_VIDEO_IP_WINDOW_DAYS)
async with database.session() as session:
row = (await session.execute(
select(FirstVideoGrant.id)
.join(UsageLedger, UsageLedger.job_id == FirstVideoGrant.job_id)
.where(and_(
FirstVideoGrant.ip_hash == ip_hash,
FirstVideoGrant.created_at >= since,
UsageLedger.status.in_(("reserved", "committed")),
)).limit(1)
)).first()
return row is not None
async def record_first_video(ip_hash: str, job_id: str):
"""Remember a first-video grant for this network; prune expired rows."""
if not ip_hash:
return
from sqlalchemy import delete
since = _now() - timedelta(days=config.FIRST_VIDEO_IP_WINDOW_DAYS)
async with database.session() as session:
async with session.begin():
await session.execute(delete(FirstVideoGrant).where(FirstVideoGrant.created_at < since))
session.add(FirstVideoGrant(ip_hash=ip_hash, job_id=job_id))
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, user=None):
"""Return a dict of the user's current minute balance (read-only).
``user`` may be a pre-fetched ``User`` row to save a lookup; it is only
consulted on the subscription-less path (free-plan eligibility).
"""
sub_row = await _subscription_row(session, user_id)
sub = sub_row if _entitles(sub_row) else None
if sub:
plan_name = sub.plan
plan_allowance = _D(sub.minutes_per_period)
# During the trial, cap the allowance so a cancel-before-charge account
# can't burn a whole plan's worth of managed minutes. Kept for
# grandfathered 'trialing' subscriptions.
if sub.status == "trialing":
plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP))
period_end = sub.current_period_end
plan_used = await _plan_used_this_period(session, user_id, period_end)
else:
if user is None:
user = await session.get(User, user_id)
if free_plan_eligible(user):
plan_name = "free"
plan_allowance = _D(config.FREE_PLAN_MINUTES)
period_end = free_period_end()
plan_used = await _plan_used_this_period(session, user_id, period_end)
else:
plan_name = None
plan_allowance = _D(0)
period_end = None
plan_used = _D(0)
plan_remaining = max(_D(0), plan_allowance - plan_used)
topups = await _topups_fifo(session, user_id)
topup_remaining = sum((_D(t.minutes_total) - _D(t.minutes_consumed) for t in topups), _D(0))
return {
"plan": plan_name,
"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,
"_sub_row": sub_row,
"_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. Selecting the full row
# (same lock semantics) lets _balance skip a second User lookup.
locked_user = (await session.execute(
select(User).where(User.id == user_id).with_for_update()
)).scalar_one_or_none()
b = await _balance(session, user_id, user=locked_user)
plan_remaining = b["_plan_remaining_d"]
remaining_total = _D(b["remaining"])
if minutes > remaining_total:
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(keep_ids=None):
"""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.
``keep_ids`` are reservations for jobs being *resumed* after the restart —
those keep running and will settle themselves, so they must not be refunded.
"""
keep = {str(k) for k in (keep_ids or ())}
async with database.session() as session:
ids = list((await session.execute(
select(UsageLedger.id).where(UsageLedger.status == "reserved")
)).scalars())
released = 0
for lid in ids:
if str(lid) in keep:
continue
await release_reservation(str(lid))
released += 1
if released:
print(f"☁️ Released {released} 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())

View file

@ -1,467 +0,0 @@
"""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,
UniqueConstraint,
)
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)
# Set by the unsubscribe link in the emails that are commercial
# communications rather than service notices (the out-of-minutes upsell and
# the lifecycle emails). LSSI art. 21.2 lets us mail our own customers about
# a similar product, but only if every message carries a way out — so this
# column is what that link writes, and emails.send_commercial_email refuses
# to send when it is set.
# Schema bootstrap is create_all, which never ALTERs: see
# cloud/database.init_engine for the additive statement that adds it to an
# existing database.
marketing_opt_out = Column(Boolean, nullable=False, server_default="false",
default=False)
# Why this account gets no free monthly minutes, or NULL (the normal case).
# Set at sign-up for an address erased in the last FREE_REDO_BLOCK_DAYS
# ("recreated_after_deletion": deleting and re-registering handed out a
# fresh 20 minutes), and for accounts whose mail domain turns out to be a
# temp-mail front ("disposable_mx"), which the domain list alone cannot
# see. Paid plans and top-ups are untouched; clearing it restores the free
# plan. Added to existing databases by cloud/database._ADDITIVE_COLUMNS.
free_plan_denied = Column(String(32), 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"),
# NOTE: schema is create_all-only; on an existing DB this index must be
# applied by hand: CREATE INDEX IF NOT EXISTS ix_magic_ip_created
# ON magic_link_tokens (request_ip, created_at);
Index("ix_magic_ip_created", "request_ip", "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"),
Index("ix_usage_job_id", "job_id"),
)
class SignupAttribution(Base):
"""Where a user came from, captured once at sign-up (first touch wins).
Its own table rather than columns on ``users`` because the schema bootstrap
is ``create_all`` (see cloud/database.py), which creates missing tables but
never ALTERs an existing one — a new table lands on deploy with no migration.
``referrer_host`` is the grouping key ("github.com", "www.youtube.com",
"google"); the full ``referrer`` is kept for the long tail. Rows are only
written for users whose account is minutes old, so returning users from
before this shipped never get a misleading "signup" source.
"""
__tablename__ = "signup_attribution"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
referrer = Column(Text, nullable=True)
referrer_host = Column(Text, nullable=True)
landing_path = Column(Text, nullable=True)
utm_source = Column(Text, nullable=True)
utm_medium = Column(Text, nullable=True)
utm_campaign = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (
Index("ix_attrib_host", "referrer_host"),
Index("ix_attrib_utm_source", "utm_source"),
)
class ApiKey(Base):
"""A user-issued ``osk_...`` token for programmatic access (MCP, scripts, CI).
Only the sha256 of the raw token is stored — the raw value is shown once at
creation and never again. ``prefix`` keeps the first characters so the UI
can tell keys apart. Revocation is a timestamp rather than a delete so a
leaked-then-revoked key stays visible in the user's list with its history.
Its own table (not columns on ``users``) because the schema bootstrap is
``create_all`` — see [SignupAttribution] above for the same reasoning.
"""
__tablename__ = "api_keys"
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)
name = Column(Text, nullable=False)
key_hash = Column(Text, unique=True, nullable=False) # sha256 of the raw osk_ token
prefix = Column(Text, nullable=False) # e.g. "osk_a1b2c3" (display only)
created_at = Column(DateTime(timezone=True), server_default=func.now())
last_used_at = Column(DateTime(timezone=True), nullable=True)
revoked_at = Column(DateTime(timezone=True), nullable=True)
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 ClipExpiryWarning(Base):
"""One row per clip already covered by an expiry-warning email.
De-duplication for ``videos.warn_free_expiring`` used to be a process-local
set, which meant every API restart re-armed the warning for clips that had
already been warned about. The warning window is a full day and the sweep
runs every six hours, so any deploy inside that window sent the same user a
second "your clips will be deleted tomorrow" email. Persisting the state
fixes that: a restart no longer forgets who has been told.
Its own table rather than a column on ``user_videos`` because the schema
bootstrap is ``create_all`` (see cloud/database.py), which creates missing
tables but never ALTERs an existing one — see [SignupAttribution] above for
the same reasoning. The CASCADE means rows disappear on their own when
``purge_free_expired`` deletes the clip they refer to, so this never needs
its own cleanup pass.
"""
__tablename__ = "clip_expiry_warnings"
video_id = Column(UUID(as_uuid=True),
ForeignKey("user_videos.id", ondelete="CASCADE"),
primary_key=True)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
warned_at = Column(DateTime(timezone=True), server_default=func.now())
class Project(Base):
"""One re-openable project per completed job.
The metadata JSON in R2 (``metadata_r2_key``) is the source of truth for the
clips + transcript; ``state`` holds only what lives outside that file: the
browser-side Remotion layers and the current server file per clip.
``state`` schema: {"v": 1, "clips": [{"index", "original_file",
"server_file", "active_layers"}]}.
"""
__tablename__ = "projects"
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, unique=True, nullable=False)
title = Column(Text, nullable=True)
metadata_r2_key = Column(Text, nullable=False)
state = Column(JSONB, nullable=True)
size_bytes = Column(Integer, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=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())
class AccountDeletion(Base):
"""Proof that an account was erased, kept after the user row is gone.
GDPR Art. 17 erasure has an accountability twin (Art. 5.2): if a former user
later claims we never deleted their account, the only way to answer is a
record that outlives the deletion. The identifying field is therefore a
sha256 of the account email, which confirms "yes, this address was deleted
on this date" without storing the address itself.
``reason`` is one label from ``account.DELETION_REASONS``, never free text:
anything the user could type would land in a row that deliberately outlives
their account, which is the opposite of what this row is for.
``stripe_customer_id`` is the one exception and it is deliberate: the
invoices behind it must be kept for six years under Spanish commercial law,
so the reference that lets us find them survives too (privacy policy §5).
There is no FK to ``users`` — the whole point is that the row it would
reference no longer exists.
Rows are dropped after DELETION_LOG_RETENTION_DAYS by the retention sweeper,
matching the "rights declarations and related logs: up to 5 years" line in
the privacy policy.
"""
__tablename__ = "account_deletions"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
former_user_id = Column(Text, nullable=False) # the old uuid, resolves to nothing now
email_sha256 = Column(Text, nullable=False, index=True)
stripe_customer_id = Column(Text, nullable=True)
plan_at_deletion = Column(String(20), nullable=True)
r2_objects_deleted = Column(Integer, nullable=True)
reason = Column(String(32), nullable=True) # one of account.DELETION_REASONS
deleted_at = Column(DateTime(timezone=True), server_default=func.now())
class OAuthClient(Base):
"""An MCP client registered through OAuth dynamic client registration
(RFC 7591): claude.ai, ChatGPT, Cursor... They are public clients (no
secret): PKCE is what ties the authorization code to the party that
started the flow. Rows are not user-owned — one registration serves every
user of that client — so they survive account erasure."""
__tablename__ = "oauth_clients"
id = Column(Text, primary_key=True) # client_id
client_name = Column(Text, nullable=False)
redirect_uris = Column(Text, nullable=False) # JSON list
created_at = Column(DateTime(timezone=True), server_default=func.now())
class OAuthCode(Base):
"""A short-lived authorization code (10 min, single use). Only its sha256
is stored; the code itself travels once, in the redirect back to the
client. Redeeming it mints an ``osk_`` API key for the user, which is what
the client keeps as its access token: the key shows up in the account
page like any other, and revoking it there disconnects the client."""
__tablename__ = "oauth_codes"
code_hash = Column(Text, primary_key=True)
client_id = Column(Text, ForeignKey("oauth_clients.id", ondelete="CASCADE"), nullable=False)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
redirect_uri = Column(Text, nullable=False)
code_challenge = Column(Text, nullable=False)
scope = Column(Text, nullable=True)
expires_at = Column(DateTime(timezone=True), nullable=False)
used_at = Column(DateTime(timezone=True), nullable=True)
class ProxyUsage(Base):
"""One row per event that put bytes through the per-GB paid proxy, or per
download route decision worth keeping (the winner and why the free routes
failed).
The monthly proxy counter in app.py is in-memory and the container log
rotates within the hour, so on 28-aug-2026 a $14 DataImpulse day could not
be reconstructed at all. This is the durable trail: which job, which route
won, how many paid bytes, and the failure text of every free attempt that
was tried first. Not user-owned data (no FK to users): it is operational
accounting and survives account erasure on purpose.
"""
__tablename__ = "proxy_usage"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
source = Column(String(16), nullable=False) # download | probe
job_id = Column(String(64), nullable=True, index=True)
url_host = Column(String(120), nullable=True)
route = Column(String(32), nullable=True) # winning attempt label, or "none"
paid_bytes = Column(Integer, nullable=False, default=0)
detail = Column(JSONB, nullable=True) # attempts: [{label, ok, bytes, error}]
class AutopilotSettings(Base):
"""Per-user switch for Autopilot: clip every new video on the user's
connected YouTube channel, and optionally publish the best clips.
The channel itself is not stored here. It is whatever YouTube account the
user connected to their Upload-Post profile, read at poll time, so
reconnecting a different channel just works and disconnecting stops it.
``enabled_at`` is the baseline: only videos published after it are clipped
automatically, so switching Autopilot on never burns the month on the back
catalogue. Older videos can still be clipped by hand from the same page.
"""
__tablename__ = "autopilot_settings"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
enabled = Column(Boolean, nullable=False, default=False)
enabled_at = Column(DateTime(timezone=True), nullable=True)
# The user confirmed they own (or have rights to) the channel's content.
# /api/process requires that attestation per job; Autopilot records it once.
rights_ack_at = Column(DateTime(timezone=True), nullable=True)
autopublish = Column(Boolean, nullable=False, default=False)
publish_platforms = Column(JSONB, nullable=True) # ["tiktok", "instagram", "youtube"]
clips_to_publish = Column(Integer, nullable=False, default=3)
max_minutes = Column(Integer, nullable=False, default=30)
# Autopublish slot: one clip a day at this local hour, in this IANA zone.
publish_hour = Column(Integer, nullable=False, default=17)
timezone = Column(Text, nullable=True)
last_checked_at = Column(DateTime(timezone=True), nullable=True)
last_error = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
class AutopilotRun(Base):
"""One channel video Autopilot picked up, and what happened to it.
The (user_id, video_id) unique constraint is the dedupe: during a deploy two
API containers run the poller at once, and only the one whose INSERT wins
submits the job.
"""
__tablename__ = "autopilot_runs"
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)
video_id = Column(Text, nullable=False)
video_url = Column(Text, nullable=True)
video_title = Column(Text, nullable=True)
thumbnail_url = Column(Text, nullable=True)
published_at = Column(DateTime(timezone=True), nullable=True)
trigger = Column(String(12), nullable=False, default="auto") # auto | manual
status = Column(String(16), nullable=False, default="queued") # queued | processing | completed | failed | skipped
reason = Column(Text, nullable=True)
job_id = Column(Text, nullable=True, index=True)
clips_count = Column(Integer, nullable=True)
posted_count = Column(Integer, nullable=True)
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__ = (
UniqueConstraint("user_id", "video_id", name="uq_autopilot_user_video"),
)
class LifecycleEmail(Base):
"""One lifecycle email sent to one account (cloud/lifecycle.py).
The (user_id, kind) unique constraint is the dedupe and the claim: the row
is inserted BEFORE the email goes out, so two API containers running the
loop during a deploy never both send it, and an account never gets the
same kind twice.
"""
__tablename__ = "lifecycle_emails"
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)
kind = Column(String(32), nullable=False) # welcome | first_clip | winback | checkout_recovery
created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (
UniqueConstraint("user_id", "kind", name="uq_lifecycle_user_kind"),
)
class CancellationFeedback(Base):
"""Why a subscriber cancelled, and their review (cloud/cancellation.py).
One row per pass through the dashboard flow that ended in a cancel or in
the retention offer being taken (``outcome``). User-owned: the
free text belongs to the account and is erased with it, which is why it is
allowed here and not in ``account_deletions``.
"""
__tablename__ = "cancellation_feedback"
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_subscription_id = Column(Text, nullable=True)
plan = Column(String(20), nullable=True)
interval = Column(String(10), nullable=True)
reason = Column(String(32), nullable=False) # one of cancellation.CANCEL_REASONS
details = Column(Text, nullable=True)
rating = Column(Integer, nullable=True) # 1-5
review = Column(Text, nullable=True)
review_public_ok = Column(Boolean, nullable=False, default=False)
outcome = Column(String(16), nullable=True) # canceled | retained
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
class OnboardingSurvey(Base):
"""The sign-up survey (cloud/onboarding.py): where they heard of us, what
they came to make, who they are. One row per account, a skip included."""
__tablename__ = "onboarding_surveys"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
skipped = Column(Boolean, nullable=False, default=False)
source = Column(String(32), nullable=True, index=True) # one of onboarding.SOURCES
source_other = Column(Text, nullable=True)
goals = Column(JSONB, nullable=True) # list of onboarding.GOALS
role = Column(String(32), nullable=True, index=True) # one of onboarding.ROLES
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
class FirstVideoGrant(Base):
"""One free first video clipped whole (app.free_overflow), by client IP.
Keyed on an HMAC of the IP, not the IP, and deliberately NOT tied to the
user row: deleting an account must not hand its network a fresh grant.
Rows past ``FIRST_VIDEO_IP_WINDOW_DAYS`` are deleted on the next grant.
A grant only counts while its job's reservation is live, so a first video
that fails does not use up the network's grant.
"""
__tablename__ = "first_video_grants"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
ip_hash = Column(String(64), nullable=False, index=True)
job_id = Column(Text, nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)

View file

@ -1,111 +0,0 @@
"""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.
"""
import os
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, email_policy
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")
# Explicit override for setups where the Host header doesn't match a
# Google-registered URI (e.g. local dev through the Vite proxy, where the
# backend sees the internal Docker host "backend:8000").
redirect_uri = os.environ.get("OAUTH_REDIRECT_URI", "").strip()
if not redirect_uri:
redirect_uri = str(request.url_for("google_callback"))
# Behind a TLS-terminating reverse proxy the app sees the request as http, so
# url_for builds an http:// redirect_uri — but Google requires the exact
# registered https URI for public hosts (→ redirect_uri_mismatch otherwise).
# Force https except on localhost (where there's no proxy and http is used).
if redirect_uri.startswith("http://") and not any(
h in redirect_uri for h in ("localhost", "127.0.0.1")
):
redirect_uri = "https://" + redirect_uri[len("http://"):]
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)
# Normalize (Gmail dots / +tags) so a Google login and a magic-link account
# for the same real inbox key to one account.
email = email_policy.normalize_email(userinfo.get("email") or "")
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:
from .account import free_plan_denial_for_signup
user = User(email=email, google_sub=google_sub, last_login_at=_now(),
free_plan_denied=await free_plan_denial_for_signup(session, email))
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}")

View file

@ -1,113 +0,0 @@
"""Sign-up survey: where the user heard of us and what they came to make.
``signup_attribution`` records the referrer, and 94% of it is brand traffic
from the GitHub repo or a direct visit, which says nothing about *why*: a
creator who wants clips from a podcast and one who wants AI avatar ads land on
the same page. Three closed questions asked once, right after sign-up, answer
that. One screen, skippable; a skip is stored too so it is never asked twice
and the skip rate is itself measurable.
Closed lists so the answers can be counted; the only free text is the "other"
source, capped short. The row is user-owned and goes with the account.
"""
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
from sqlalchemy import select
from . import analytics, database
from .auth import get_current_user_required
from .models import OnboardingSurvey, User
router = APIRouter()
# Mirror the lists in dashboard/src/components/OnboardingSurvey.jsx.
SOURCES = (
"google", "ai_assistant", "youtube", "tiktok_instagram", "x_twitter", "reddit",
"github", "friend", "directory", "newsletter_blog", "other",
)
GOALS = (
"clips_from_long_videos", "ai_avatar_videos", "autopilot_posting", "thumbnails",
"subtitles", "dubbing", "api_agents", "self_host",
)
ROLES = (
"creator", "podcaster", "streamer_gamer", "agency", "business_marketing",
"educator", "developer", "other",
)
# Only accounts this young are asked. Everyone who signed up before the survey
# shipped would otherwise get it on their next visit, and a returning user's
# "how did you hear about us" is a memory, not an attribution.
SURVEY_MAX_ACCOUNT_AGE = timedelta(days=7)
OTHER_MAX = 120
class SurveyAnswer(BaseModel):
skipped: bool = False
source: Optional[str] = None
source_other: Optional[str] = Field(default=None, max_length=OTHER_MAX)
goals: List[str] = Field(default_factory=list, max_length=len(GOALS))
role: Optional[str] = None
def _validate(a: SurveyAnswer):
if a.skipped:
return
if a.source is not None and a.source not in SOURCES:
raise HTTPException(status_code=422, detail="Unknown source.")
if a.role is not None and a.role not in ROLES:
raise HTTPException(status_code=422, detail="Unknown role.")
if any(g not in GOALS for g in a.goals):
raise HTTPException(status_code=422, detail="Unknown goal.")
if not (a.source or a.goals or a.role):
raise HTTPException(status_code=422, detail="Answer at least one question, or skip.")
def survey_pending(user_created_at: Optional[datetime], answered: bool) -> bool:
"""Whether /api/me should ask the dashboard to show the survey."""
if answered or user_created_at is None:
return False
return datetime.now(timezone.utc) - user_created_at <= SURVEY_MAX_ACCOUNT_AGE
async def is_pending(session, user) -> bool:
answered = (await session.execute(
select(OnboardingSurvey.user_id).where(OnboardingSurvey.user_id == user.id)
)).scalar_one_or_none() is not None
created = (await session.execute(
select(User.created_at).where(User.id == user.id)
)).scalar_one_or_none()
return survey_pending(created, answered)
@router.post("/api/onboarding/survey")
async def answer_survey(body: SurveyAnswer, request: Request):
from sqlalchemy.dialects.postgresql import insert as pg_insert
user = await get_current_user_required(request)
_validate(body)
goals = [] if body.skipped else list(dict.fromkeys(body.goals))
source = None if body.skipped else body.source
other = (body.source_other or "").strip()[:OTHER_MAX] or None
if source != "other":
other = None
role = None if body.skipped else body.role
async with database.session() as session:
async with session.begin():
# First answer wins: two tabs, or a double click, must not overwrite.
await session.execute(pg_insert(OnboardingSurvey).values(
user_id=user.id, skipped=body.skipped, source=source,
source_other=other, goals=goals, role=role,
).on_conflict_do_nothing(index_elements=["user_id"]))
if body.skipped:
analytics.track("SignupSurveySkipped", user_id=user.id)
else:
# One flat prop per goal so OpenPanel can break the event down by each,
# which it cannot do with a list.
analytics.track("SignupSurveyAnswered", user_id=user.id, source=source,
role=role, goals=",".join(goals) or None,
**{f"goal_{g}": True for g in goals})
return {"ok": True}

View file

@ -1,236 +0,0 @@
"""Durable trail + Telegram alert for every byte sent through the paid proxy.
Two producers:
- ``main.py`` prints ``PROXY_ROUTE=<json>`` after a download (winner label,
paid bytes summed over every attempt that used the per-GB proxy, and the
error text of each free attempt that failed first). ``app.py``'s log reader
parses it and calls :func:`record_download` when the job ends.
- ``cloud.metering.probe_url_minutes`` appends an event when the duration
probe had to reach the paid proxy; ``app.py`` drains those right after the
probe with :func:`drain_probe_events`.
Both persist a ``proxy_usage`` row (best effort) and page the admin. The
alert has a short cooldown that folds a burst into one message: on a day like
28-aug-2026, when every job fell to the paid proxy, one Telegram line per
job would have been 180 messages saying the same thing.
"""
from __future__ import annotations
import asyncio
import datetime as _dt
import json
import os
import time
from typing import Optional
from urllib.parse import urlparse
PAID_LABELS = {"HD", "fallback"} # download attempts billed per GB (main.plan_download_attempts)
ALERT_COOLDOWN_SECONDS = 300
# Hard ceiling on paid-proxy traffic per UTC day. Above it the paid proxy is
# taken out of every chain until midnight: jobs that need it fail with a clear
# message instead of bleeding money. 28-aug-2026 was $14 in one day because
# nothing capped the fallback while the static IPs were being refused by
# YouTube for hours. 0 disables the cap.
DAILY_BUDGET_MB = float(os.environ.get("PAID_PROXY_DAILY_MB", "500"))
_budget_cache = {"at": 0.0, "bytes": -1}
_budget_alerted = {"day": None}
_pending = {"count": 0, "bytes": 0, "lines": [], "last_sent": 0.0}
_lock = asyncio.Lock()
def host_of(url: Optional[str]) -> Optional[str]:
try:
return urlparse(url or "").hostname or None
except Exception:
return None
def parse_route_line(line: str) -> Optional[dict]:
"""``PROXY_ROUTE={...}`` -> dict, or None for anything malformed."""
if not line.startswith("PROXY_ROUTE="):
return None
try:
data = json.loads(line.split("=", 1)[1])
except ValueError:
return None
return data if isinstance(data, dict) else None
def paid_bytes_of(route: Optional[dict]) -> int:
try:
return int((route or {}).get("paid_bytes") or 0)
except (TypeError, ValueError):
return 0
def used_paid(route: Optional[dict]) -> bool:
"""True when the paid proxy carried bytes or won the download."""
if not route:
return False
return paid_bytes_of(route) > 0 or str(route.get("winner") or "") in PAID_LABELS
def describe_failures(route: Optional[dict], limit: int = 3) -> str:
"""The free attempts that failed before the paid one, one per line."""
out = []
for a in (route or {}).get("attempts") or []:
if a.get("ok") or a.get("label") in PAID_LABELS:
continue
err = str(a.get("error") or "").strip().replace("\n", " ")
if err:
out.append(f" {a.get('label')}: {err[:140]}")
if len(out) >= limit:
break
return "\n".join(out)
async def _persist(source: str, job_id: Optional[str], url_host: Optional[str],
route_label: Optional[str], paid_bytes: int, detail: Optional[dict]):
try:
from . import database as _db
from .models import ProxyUsage
async with _db.session() as s:
s.add(ProxyUsage(source=source, job_id=job_id, url_host=url_host,
route=route_label, paid_bytes=int(paid_bytes or 0),
detail=detail))
await s.commit()
except Exception as e: # accounting must never break a job
print(f"⚠️ proxy_usage row not written: {e}")
async def _alert(line: str, nbytes: int):
"""Page the admin, folding events inside the cooldown into one message."""
try:
from . import alerts
except Exception:
return
async with _lock:
_pending["count"] += 1
_pending["bytes"] += int(nbytes or 0)
if len(_pending["lines"]) < 5:
_pending["lines"].append(line)
now = time.time()
if now - _pending["last_sent"] < ALERT_COOLDOWN_SECONDS:
return
count, total = _pending["count"], _pending["bytes"]
lines = list(_pending["lines"])
_pending.update(count=0, bytes=0, lines=[], last_sent=now)
head = ("💸 Paid proxy (DataImpulse) used"
+ (f": {count} events, {total / 1e6:.1f} MB in the last {ALERT_COOLDOWN_SECONDS // 60} min"
if count > 1 else ""))
await alerts.send_telegram(head + "\n" + "\n".join(lines))
async def flush_alerts():
"""Send whatever the cooldown is still holding (called by a periodic tick)."""
async with _lock:
if not _pending["count"] or time.time() - _pending["last_sent"] < ALERT_COOLDOWN_SECONDS:
return
count, total = _pending["count"], _pending["bytes"]
lines = list(_pending["lines"])
_pending.update(count=0, bytes=0, lines=[], last_sent=time.time())
try:
from . import alerts
await alerts.send_telegram(
f"💸 Paid proxy (DataImpulse) used: {count} events, {total / 1e6:.1f} MB\n" + "\n".join(lines))
except Exception:
pass
async def paid_bytes_today() -> int:
"""Paid bytes recorded since UTC midnight (60 s cache; -1 -> unknown)."""
now = time.time()
if now - _budget_cache["at"] < 60 and _budget_cache["bytes"] >= 0:
return _budget_cache["bytes"]
try:
from sqlalchemy import func, select
from . import database as _db
from .models import ProxyUsage
day_start = _dt.datetime.now(_dt.timezone.utc).replace(hour=0, minute=0,
second=0, microsecond=0)
async with _db.session() as sess:
total = (await sess.execute(
select(func.coalesce(func.sum(ProxyUsage.paid_bytes), 0))
.where(ProxyUsage.created_at >= day_start))).scalar_one()
_budget_cache.update(at=now, bytes=int(total or 0))
return _budget_cache["bytes"]
except Exception as e:
print(f"⚠️ paid_bytes_today failed ({e}); treating budget as not exceeded")
return 0
async def budget_exceeded() -> bool:
"""True when today's paid traffic is over PAID_PROXY_DAILY_MB.
Fails open (False) when the DB is unreachable: refusing every YouTube job
because the accounting query broke would be the worse failure. Alerts
once per UTC day when the cap trips.
"""
if DAILY_BUDGET_MB <= 0:
return False
used = await paid_bytes_today()
if used < DAILY_BUDGET_MB * 1e6:
return False
day = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%d")
if _budget_alerted["day"] != day:
_budget_alerted["day"] = day
try:
from . import alerts
await alerts.send_telegram(
f"⛔ Paid proxy daily budget hit: {used / 1e6:.0f} MB of "
f"{DAILY_BUDGET_MB:.0f} MB used today. DataImpulse is disabled "
"until UTC midnight; jobs that need it will fail with a clear error. "
"Raise PAID_PROXY_DAILY_MB if this is expected.")
except Exception:
pass
return True
def budget_exceeded_sync() -> bool:
"""Non-blocking view for sync callers (the resume scan): last cached
value only, unknown counts as not exceeded."""
if DAILY_BUDGET_MB <= 0:
return False
cached = _budget_cache["bytes"]
return cached >= 0 and cached >= DAILY_BUDGET_MB * 1e6
async def record_download(job_id: str, route: Optional[dict], source_url: Optional[str] = None):
"""Persist a download's route; alert when the paid proxy was involved."""
if not route:
return
nbytes = paid_bytes_of(route)
paid = used_paid(route)
await _persist("download", job_id, host_of(source_url), str(route.get("winner") or "none"),
nbytes if paid else 0, route)
if paid:
why = describe_failures(route)
await _alert(f"download job {job_id[:8]}: {nbytes / 1e6:.1f} MB via '{route.get('winner')}'"
+ (f"\n{why}" if why else ""), nbytes)
async def record_probe(event: dict):
"""A duration probe that reached the paid proxy (see cloud.metering)."""
url_host = host_of(event.get("url"))
await _persist("probe", event.get("job_id"), url_host, "paid-probe",
int(event.get("bytes_estimate") or 0), event)
fails = "\n".join(f" {k}: {str(v)[:140]}" for k, v in (event.get("static_errors") or {}).items())
paid_failed = event.get("paid_failed")
outcome = (f"paid proxy failed too: {str(paid_failed)[:140]}" if paid_failed
else "paid proxy answered")
await _alert(f"probe {url_host or '?'}: statics failed, {outcome}"
+ (f"\n{fails}" if fails else ""), int(event.get("bytes_estimate") or 0))
async def drain_probe_events():
"""Record every paid probe the metering module queued since the last call."""
try:
from . import metering
events = metering.pop_paid_probe_events()
except Exception:
return
for ev in events:
await record_probe(ev)

View file

@ -1,112 +0,0 @@
"""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
# Where the connect page sends the user back to. A closed list: the value
# comes from the client and ends up in a redirect.
RETURN_TARGETS = {
"account": "/#/account?connected=1",
"autopilot": "/#app?tab=autopilot&connected=1",
}
async def get_connect_url(username: str, return_to: str = "account") -> str:
"""Generate a branded, single-use connection URL (~1h) for the user's socials."""
back = RETURN_TARGETS.get(return_to, RETURN_TARGETS["account"])
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}{back}",
"redirectButtonText": "Back to OpenShorts",
"platforms": CONNECT_PLATFORMS,
"showCalendar": True, # keep the scheduling calendar available in the page
}
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, request.query_params.get("return_to") or "account")
return {"access_url": access_url}

View file

@ -1,116 +0,0 @@
"""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.
"""
from urllib.parse import quote
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 download_file(key, local_path):
client().download_file(settings.r2_bucket, key, local_path)
def object_size(key):
"""Size in bytes of one object, or None when it is not there."""
try:
return int(client().head_object(Bucket=settings.r2_bucket, Key=key)["ContentLength"])
except client().exceptions.ClientError as e:
code = str((e.response or {}).get("Error", {}).get("Code", ""))
if code in ("404", "NoSuchKey", "NotFound"):
return None
raise
def delete_key(key):
client().delete_object(Bucket=settings.r2_bucket, Key=key)
def list_keys(prefix) -> list:
"""List every object key under a prefix."""
c = client()
keys = []
token = None
while True:
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
if token:
kw["ContinuationToken"] = token
resp = c.list_objects_v2(**kw)
keys.extend(o["Key"] for o in resp.get("Contents", []))
if not resp.get("IsTruncated"):
break
token = resp.get("NextContinuationToken")
return keys
def presigned_get(key, expires=3600, download_name=None) -> str:
"""A URL a client can GET. Signed against the S3 endpoint by default; a plain
URL on the bucket's custom domain when R2_PUBLIC_BASE is set.
Switching here rather than at each call site on purpose: every caller hands
the result to a browser, and the S3 endpoint is the one variant browsers
cannot reliably fetch (see settings.r2_public_base). The custom domain has no
equivalent of ResponseContentDisposition, so a download keeps the object's
own name, which is already the clip filename.
"""
base = settings.r2_public_base
if base:
return f"{base}/{quote(key, safe='/')}"
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

View file

@ -1,650 +0,0 @@
"""Users' durable video library on R2: archive on completion, list for history,
purge after the subscription grace period.
"""
import asyncio
import glob
import os
import re
from datetime import timedelta
from fastapi import APIRouter, HTTPException, Request
from sqlalchemy import select, delete
from .config import settings, VIDEO_RETENTION_GRACE_DAYS, FREE_CLIP_RETENTION_DAYS
from . import database, storage, metering
from .models import UserVideo, Subscription, Project, User, ClipExpiryWarning
from .auth import get_current_user_required
import watermarked
router = APIRouter()
def _clip_title(clip) -> str:
return clip.get("title") or clip.get("video_title_for_youtube_short") or "Short"
_HOOK_CHAIN_RE = re.compile(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$')
def _canonical_name(base_name, clip_index):
return f"{base_name}_clip_{clip_index + 1}.mp4" if base_name else None
def _twins_to_archive(served, base_name, clip_index):
"""The files that must ride to R2 next to a served clip file, in order.
* its clean twin when it is a free-plan ``wm_`` copy (an upgrade re-points
at it: ``unmark_user_library``), unless that twin is the canonical,
which the caller archives on its own;
* the ``hooked_`` intermediate of a captioned hook chain, resolved on the
clean name, or a restored project's caption restyle cannot walk back to
the hook-only file and would silently drop or stack layers.
"""
out = []
clean = watermarked.clean_name(served)
canonical = _canonical_name(base_name, clip_index)
if clean != served and clean != canonical:
out.append(clean)
m = _HOOK_CHAIN_RE.match(clean)
if m and m.group(1) != canonical:
out.append(m.group(1))
return out
def _superseded_names(prev, original_file, new_filename, base_name, clip_index):
"""R2 objects an edit leaves behind: the previous served file and, when
that was a ``wm_`` copy, its clean twin. Never the pristine original (or
its twin), never the canonical, never the file just written."""
if not prev:
return []
keep = {new_filename, watermarked.clean_name(new_filename),
original_file or "", watermarked.clean_name(original_file or ""),
_canonical_name(base_name, clip_index) or ""}
out = []
for name in (prev, watermarked.clean_name(prev)):
if name and name not in keep and name not in out:
out.append(name)
return out
def unmarked_clip_state(state):
"""Pure half of ``unmark_user_library``: the project state with every
``wm_`` name replaced by its clean twin, plus ``[(index, wm, clean)]`` for
the clips whose served file changed."""
new_state = dict(state or {"v": 1, "clips": []})
changes, clips = [], []
for c in new_state.get("clips", []):
c = dict(c)
served = c.get("server_file") or ""
if watermarked.is_marked(served):
clean = watermarked.clean_name(served)
changes.append((c.get("index"), served, clean))
c["server_file"] = clean
original = c.get("original_file") or ""
if watermarked.is_marked(original):
c["original_file"] = watermarked.clean_name(original)
clips.append(c)
new_state["clips"] = clips
return new_state, changes
# app.py owns the working files and the in-memory job table; like the erasure
# purge (cloud/account.py) it registers a callback at startup rather than being
# imported from here.
_local_unmark = None
def register_local_unmark(fn):
"""Let app.py hand us a ``(job_id, clip_index, clean_filename)`` callback."""
global _local_unmark
_local_unmark = fn
async def unmark_user_library(user_id) -> int:
"""After an upgrade: serve every clip this user has through its clean twin.
The free plan burns the mark into a ``wm_`` copy and archives the clean
final next to it (``_twins_to_archive``), so losing the mark is a
re-pointing, not a render: the history row and the project state move to
the twin, the marked object is deleted, and app.py is told so a dashboard
that is open on the job follows. A clip whose twin is not in R2 keeps its
marked file: a dead link would be worse than the mark. Returns the number
of clips re-pointed.
"""
if not settings.r2_configured:
return 0
async with database.session() as s:
projects = list((await s.execute(
select(Project).where(Project.user_id == user_id)
)).scalars())
done = 0
for proj in projects:
new_state, changes = unmarked_clip_state(proj.state)
if not changes:
continue
applied = []
for index, wm_name, clean in changes:
clean_key = storage.job_key(user_id, proj.job_id, clean)
try:
size = await asyncio.to_thread(storage.object_size, clean_key)
except Exception as e:
print(f"⚠️ R2 head failed for {clean_key}: {e}")
size = None
if size is None:
continue
applied.append((index, wm_name, clean, clean_key, size))
if not applied:
continue
applied_idx = {a[0] for a in applied}
# Clips whose twin is missing keep their marked entry.
prior = {c.get("index"): c for c in (proj.state or {}).get("clips", [])}
new_state["clips"] = [
c if c.get("index") in applied_idx else dict(prior.get(c.get("index"), c))
for c in new_state["clips"]]
async with database.session() as s:
async with s.begin():
row = (await s.execute(
select(Project).where(Project.id == proj.id)
)).scalar_one_or_none()
if row is not None:
row.state = new_state
for index, _wm, _clean, clean_key, size in applied:
vid = (await s.execute(
select(UserVideo).where(UserVideo.user_id == user_id,
UserVideo.job_id == proj.job_id,
UserVideo.clip_index == index)
)).scalars().first()
if vid is not None:
vid.r2_key, vid.size_bytes = clean_key, size
for index, wm_name, clean, _key, _size in applied:
try:
await asyncio.to_thread(
storage.delete_key, storage.job_key(user_id, proj.job_id, wm_name))
except Exception as e:
print(f"⚠️ Could not delete marked R2 object {wm_name}: {e}")
if _local_unmark is not None:
try:
_local_unmark(proj.job_id, index, clean)
except Exception as e:
print(f"⚠️ Local unmark failed for {proj.job_id}: {e}")
done += 1
if done:
print(f"🏷️ Watermark removed from {done} clip(s) of user {user_id} after upgrade.")
return done
async def archive_job(user_id, job_id, clips, output_dir, attestation=None):
"""Upload a completed managed job's clips + metadata JSON to R2 and record
them for history. The metadata (transcript included) plus the Project row
make the whole job re-openable and editable later, not just viewable.
``attestation`` is the "I hold the rights to this video" declaration the
submitter ticked (truncated IP, user agent, timestamp, which input path).
The privacy policy promises to keep it; the Project row is where it lives,
so it is deleted with the account like everything else that names a user.
"""
if not settings.r2_configured or not clips:
return
metadata_r2_key = None
meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
if meta_files:
key = storage.job_key(user_id, job_id, os.path.basename(meta_files[0]))
try:
await asyncio.to_thread(storage.upload_file, meta_files[0], key, "application/json")
metadata_r2_key = key
except Exception as e:
print(f"⚠️ R2 upload failed for {key}: {e}")
base_name = (os.path.basename(meta_files[0]).replace("_metadata.json", "")
if meta_files else None)
uploaded = [] # (clip_index, filename, key, title, size_bytes)
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
uploaded.append((i, filename, key, _clip_title(clip), os.path.getsize(local_path)))
# Also archive the clean canonical when the served file is a derived
# one (captioned/recut): it is the editable master — the clip editor's
# fast path and /api/subtitle re-styles cut from it, so a project
# restored after a redeploy is only editable if it comes back too.
# Restore downloads every key under the job prefix, so no change is
# needed on that side; the free-retention purge deletes by prefix.
if base_name:
clean = f"{base_name}_clip_{i + 1}.mp4"
clean_path = os.path.join(output_dir, clean)
if clean != filename and os.path.exists(clean_path):
clean_key = storage.job_key(user_id, job_id, clean)
try:
await asyncio.to_thread(storage.upload_file, clean_path, clean_key)
except Exception as e:
print(f"⚠️ R2 upload failed for {clean_key}: {e}")
# Free plan: the served file is the wm_ copy of the final one, and the
# clean final rides along so an upgrade can re-point at it without a
# render (unmark_user_library). The canonical is handled just above.
for twin_name in _twins_to_archive(filename, base_name, i):
twin_path = os.path.join(output_dir, twin_name)
if os.path.exists(twin_path):
twin_key = storage.job_key(user_id, job_id, twin_name)
try:
await asyncio.to_thread(storage.upload_file, twin_path, twin_key)
except Exception as e:
print(f"⚠️ R2 upload failed for {twin_key}: {e}")
if not uploaded:
return
async with database.session() as s:
async with s.begin():
# Upsert per-clip history rows: re-archiving a job must repoint the
# existing rows, never duplicate them.
existing = {
v.clip_index: v for v in (await s.execute(
select(UserVideo).where(UserVideo.user_id == user_id,
UserVideo.job_id == job_id)
)).scalars()
}
for i, _filename, key, title, size in uploaded:
row = existing.get(i)
if row is not None:
row.r2_key, row.title, row.size_bytes = key, title, size
else:
s.add(UserVideo(user_id=user_id, job_id=job_id, clip_index=i,
r2_key=key, title=title, size_bytes=size))
# Upsert the Project row (only re-openable with the metadata in R2).
if metadata_r2_key:
proj = (await s.execute(
select(Project).where(Project.job_id == job_id)
)).scalar_one_or_none()
state = {"v": 1, "clips": [
{"index": i, "original_file": filename, "server_file": filename,
"active_layers": None}
for i, filename, _key, _title, _size in uploaded
]}
if attestation:
state["rights_attestation"] = {
"acknowledged": bool(attestation.get("acknowledged")),
# Already truncated to a /24 (or /48) by app.py.
"ip_network": attestation.get("ip"),
"user_agent": (attestation.get("user_agent") or "")[:300],
"timestamp": attestation.get("timestamp"),
"source": attestation.get("source"),
}
elif proj is not None and isinstance(proj.state, dict):
# Re-archiving must not erase the original declaration.
prior = proj.state.get("rights_attestation")
if prior:
state["rights_attestation"] = prior
total = sum(u[4] for u in uploaded)
if proj is None:
s.add(Project(user_id=user_id, job_id=job_id, title=uploaded[0][3],
metadata_r2_key=metadata_r2_key, state=state,
size_bytes=total))
else:
proj.metadata_r2_key = metadata_r2_key
proj.state = state
proj.size_bytes = total
print(f"☁️ Archived {len(uploaded)} clip(s) to R2 for user {user_id}.")
async def archive_clip_edit(user_id, job_id, clip_index, output_dir, new_filename):
"""Re-archive one clip after a server-side edit (subtitles/hook/effects/dub).
Uploads the new current file plus the refreshed metadata JSON, repoints the
history row and the project state, and deletes the superseded R2 object —
per clip only the pristine original and the current version are kept.
"""
if not settings.r2_configured or not user_id:
return
local_path = os.path.join(output_dir, new_filename)
if not os.path.exists(local_path):
return
new_key = storage.job_key(user_id, job_id, new_filename)
await asyncio.to_thread(storage.upload_file, local_path, new_key)
metadata_r2_key = None
meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
base_name = (os.path.basename(meta_files[0]).replace("_metadata.json", "")
if meta_files else None)
# Same chain rule as archive_job: a captioned hook needs its hooked_
# intermediate archived too, or the restored project cannot re-style; and
# a wm_ copy needs its clean twin, or an upgrade cannot drop the mark.
for twin_name in _twins_to_archive(new_filename, base_name, clip_index):
twin_path = os.path.join(output_dir, twin_name)
if os.path.exists(twin_path):
try:
await asyncio.to_thread(
storage.upload_file, twin_path,
storage.job_key(user_id, job_id, twin_name))
except Exception as e:
print(f"⚠️ R2 upload failed for {twin_name} of {job_id}: {e}")
if meta_files:
metadata_r2_key = storage.job_key(user_id, job_id, os.path.basename(meta_files[0]))
try:
await asyncio.to_thread(storage.upload_file, meta_files[0], metadata_r2_key,
"application/json")
except Exception as e:
print(f"⚠️ R2 metadata refresh failed for {job_id}: {e}")
metadata_r2_key = None
size = os.path.getsize(local_path)
superseded = []
async with database.session() as s:
async with s.begin():
proj = (await s.execute(
select(Project).where(Project.job_id == job_id)
)).scalar_one_or_none()
if proj is not None:
state = dict(proj.state or {"v": 1, "clips": []})
clips_state = [dict(c) for c in state.get("clips", [])]
entry = next((c for c in clips_state if c.get("index") == clip_index), None)
if entry is None:
entry = {"index": clip_index, "original_file": new_filename,
"active_layers": None}
clips_state.append(entry)
prev = entry.get("server_file")
superseded = [
storage.job_key(user_id, job_id, name) for name in
_superseded_names(prev, entry.get("original_file"), new_filename,
base_name, clip_index)]
entry["server_file"] = new_filename
state["clips"] = clips_state
proj.state = state
if metadata_r2_key:
proj.metadata_r2_key = metadata_r2_key
vid = (await s.execute(
select(UserVideo).where(UserVideo.user_id == user_id,
UserVideo.job_id == job_id,
UserVideo.clip_index == clip_index)
)).scalars().first()
if vid is not None:
vid.r2_key, vid.size_bytes = new_key, size
else:
s.add(UserVideo(user_id=user_id, job_id=job_id, clip_index=clip_index,
r2_key=new_key, size_bytes=size))
for superseded_key in superseded:
if superseded_key == new_key:
continue
try:
await asyncio.to_thread(storage.delete_key, superseded_key)
except Exception as e:
print(f"⚠️ Could not delete superseded R2 object {superseded_key}: {e}")
@router.get("/api/projects")
async def list_projects(request: Request):
"""List the signed-in user's re-openable projects."""
user = await get_current_user_required(request)
async with database.session() as s:
projs = list((await s.execute(
select(Project).where(Project.user_id == user.id)
.order_by(Project.created_at.desc()).limit(200)
)).scalars())
return {"projects": [{
"job_id": p.job_id,
"title": p.title,
"clip_count": len((p.state or {}).get("clips", [])),
"size_bytes": p.size_bytes,
"created_at": p.created_at.isoformat() if p.created_at else None,
"updated_at": p.updated_at.isoformat() if p.updated_at else None,
} for p in projs]}
@router.put("/api/projects/{job_id}/state")
async def save_project_state(job_id: str, request: Request):
"""Persist the browser-only edit state of a project's clips.
Body: {"clips": [{"index", "active_layers", "server_file"?}]}. The Remotion
layers exist nowhere but the browser, so the frontend syncs them here
(debounced) to survive reload / reopen."""
user = await get_current_user_required(request)
if int(request.headers.get("content-length") or 0) > 262144:
raise HTTPException(status_code=413, detail="State too large")
body = await request.json()
clips_in = body.get("clips") or []
async with database.session() as s:
async with s.begin():
proj = (await s.execute(
select(Project).where(Project.job_id == job_id)
)).scalar_one_or_none()
if proj is None or str(proj.user_id) != str(user.id):
raise HTTPException(status_code=404, detail="Project not found")
state = dict(proj.state or {"v": 1, "clips": []})
clips_state = [dict(c) for c in state.get("clips", [])]
by_index = {c.get("index"): c for c in clips_state}
for c in clips_in:
idx = c.get("index")
if not isinstance(idx, int):
continue
entry = by_index.get(idx)
if entry is None:
entry = {"index": idx, "original_file": None,
"server_file": None, "active_layers": None}
clips_state.append(entry)
by_index[idx] = entry
entry["active_layers"] = c.get("active_layers")
if c.get("server_file"):
entry["server_file"] = os.path.basename(str(c["server_file"]))
state["clips"] = clips_state
proj.state = state
return {"success": True}
@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,
"clip_index": v.clip_index,
"title": v.title,
"created_at": v.created_at.isoformat() if v.created_at else None,
"size_bytes": v.size_bytes,
# The basename of the archived object. The preview player compares it
# against the clip's current server file: after an edit the local file
# is already the new one while the R2 re-archive is still in flight
# (_archive_clip_edit_bg is fire-and-forget), and playing the durable
# copy then would show the clip from BEFORE the edit.
"filename": (v.r2_key or "").rsplit("/", 1)[-1],
"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
# A canceled Google-authed user is now an entitled FREE user, not a
# lapsed one — their library follows the free 7-day per-clip expiry
# (purge_free_expired) instead of the full wipe.
async with database.session() as s:
if await metering.is_free_user(s, user_id):
continue
# Any videos or projects left?
async with database.session() as s:
has = (await s.execute(
select(UserVideo.id).where(UserVideo.user_id == user_id).limit(1)
)).first() or (await s.execute(
select(Project.id).where(Project.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))
await s.execute(delete(Project).where(Project.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}")
async def purge_free_expired():
"""Expire free users' clips/projects after FREE_CLIP_RETENTION_DAYS.
Paid libraries are durable; the free plan keeps R2 storage bounded (and the
limited retention is an upgrade lever). Only rows whose owner is currently
on the free plan are touched — a user who upgraded keeps everything.
"""
from datetime import datetime, timezone
cutoff = datetime.now(timezone.utc) - timedelta(days=FREE_CLIP_RETENTION_DAYS)
async with database.session() as s:
old_videos = list((await s.execute(
select(UserVideo).where(UserVideo.created_at < cutoff)
)).scalars())
old_projects = list((await s.execute(
select(Project).where(Project.updated_at < cutoff)
)).scalars())
by_user = {}
for v in old_videos:
by_user.setdefault(v.user_id, {"videos": [], "projects": []})["videos"].append(v)
for p in old_projects:
by_user.setdefault(p.user_id, {"videos": [], "projects": []})["projects"].append(p)
for user_id, items in by_user.items():
async with database.session() as s:
if not await metering.is_free_user(s, user_id):
continue
try:
for v in items["videos"]:
await asyncio.to_thread(storage.delete_key, v.r2_key)
for p in items["projects"]:
# Delete everything under the job prefix, not just the metadata
# key: the archive also stores clean canonical clips (which have
# no DB row of their own) and superseded derivatives would
# otherwise leak as orphans.
try:
prefix = storage.job_key(user_id, p.job_id, "")
for key in await asyncio.to_thread(storage.list_keys, prefix):
await asyncio.to_thread(storage.delete_key, key)
except Exception:
if p.metadata_r2_key:
await asyncio.to_thread(storage.delete_key, p.metadata_r2_key)
async with database.session() as s:
async with s.begin():
if items["videos"]:
await s.execute(delete(UserVideo).where(
UserVideo.id.in_([v.id for v in items["videos"]])))
if items["projects"]:
await s.execute(delete(Project).where(
Project.id.in_([p.id for p in items["projects"]])))
n = len(items["videos"]) + len(items["projects"])
print(f"🗑️ Free retention: purged {n} expired object(s) for user {user_id}.")
except Exception as e:
print(f"⚠️ Free retention purge failed for {user_id}: {e}")
async def warn_free_expiring():
"""Email free users whose clips enter their LAST day before deletion.
The 7-day free retention is the plan's strongest honest upgrade lever, but
silently deleting clips converts nobody — the user never learns they were
at risk. One email on day 6 turns the real deadline into a visible one.
"Already warned" is recorded in clip_expiry_warnings rather than in memory.
The warning window is a full day and this sweep runs every six hours, so a
process-local set meant any deploy inside that window re-mailed everyone who
had already been told.
"""
from datetime import datetime, timezone
from .emails import send_clips_expiring_email
now = datetime.now(timezone.utc)
doomed_after = now - timedelta(days=FREE_CLIP_RETENTION_DAYS) # already purgeable
warn_cutoff = now - timedelta(days=FREE_CLIP_RETENTION_DAYS - 1) # < 1 day left
async with database.session() as s:
expiring = list((await s.execute(
select(UserVideo).where(UserVideo.created_at < warn_cutoff,
UserVideo.created_at >= doomed_after)
)).scalars())
already = set((await s.execute(select(ClipExpiryWarning.video_id))).scalars())
by_user = {}
for v in expiring:
if v.id in already:
continue
by_user.setdefault(v.user_id, []).append(v)
for user_id, vids in by_user.items():
async with database.session() as s:
if not await metering.is_free_user(s, user_id):
continue
user = await s.get(User, user_id)
if not user or not user.email:
continue
# Record the warning BEFORE sending. A duplicate email is the failure we
# are fixing; a warning row for a mail that then failed to send only
# costs that user one notice, which is the cheaper way to be wrong.
try:
async with database.session() as s:
async with s.begin():
for v in vids:
s.add(ClipExpiryWarning(video_id=v.id, user_id=user_id))
except Exception as e:
print(f"⚠️ Could not record expiry warning for {user_id}: {e}")
continue
try:
await send_clips_expiring_email(user.email, len(vids))
print(f"⏳ Expiry warning sent: {len(vids)} clip(s), user {user_id}")
except Exception as e:
print(f"⚠️ Expiry warning 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 warn_free_expiring()
await purge_expired()
await purge_free_expired()
from .auth import purge_stale_magic_tokens
await purge_stale_magic_tokens()
from .account import purge_stale_deletion_records
await purge_stale_deletion_records()
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

@ -22,7 +22,7 @@
eyeballed): Google truncates past roughly that width, and a truncated
description is a worse answer than a shorter deliberate one. -->
<title>OpenShorts - Free Open Source AI Clip Generator (MIT)</title>
<meta name="description" content="Open source AI clip generator: turn long videos into 9:16 shorts for TikTok, Reels and Shorts. Self-host free under MIT, or cloud from $12/month." />
<meta name="description" content="Open source AI clip generator: turn long videos into 9:16 shorts for TikTok, Reels and Shorts. Self-host free under MIT, no watermark and no cap." />
<meta name="author" content="OpenShorts" />
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1" />
<!-- Canonical must match the host actually served. The apex redirects to www,
@ -35,7 +35,7 @@
<meta property="og:title"
content="OpenShorts - Open Source AI Clip Generator" />
<meta property="og:description"
content="Turn long videos into viral 9:16 shorts, or generate UGC videos with AI actors. Self-host free under MIT, or use the cloud from $12/month with 20 free minutes." />
content="Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Clip Generator, YouTube Studio and Postiz publishing, with no watermark and no cap." />
<meta property="og:image" content="https://www.openshorts.app/og-image.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
@ -48,15 +48,13 @@
<meta name="twitter:title"
content="OpenShorts - Open Source AI Clip Generator" />
<meta name="twitter:description"
content="Self-host free under MIT with no watermark and no cap, or use OpenShorts Cloud from $12/month." />
content="Self-host free under MIT with no watermark and no cap — Clip Generator, YouTube Studio and self-hosted Postiz publishing." />
<meta name="twitter:image" content="https://www.openshorts.app/og-image.png" />
<!-- JSON-LD Structured Data
Two products, described separately and on purpose. The previous graph
declared a single SoftwareApplication priced at 0, which is true of the
self-hosted edition and false of the hosted one, so engines summarised the
whole product as free. SoftwareApplication below is the MIT project;
Service is OpenShorts Cloud, with the real price range on it. -->
One product: an MIT-licensed, self-hosted SoftwareApplication priced at 0.
There is no hosted edition and no paid plan, so there is no Service node
and no price range to describe. -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
@ -73,7 +71,7 @@
"@type": "WebPage",
"@id": "https://www.openshorts.app/#webpage",
"name": "OpenShorts - Open Source AI Clip Generator",
"description": "Open source AI clip generator that turns long videos into viral 9:16 clips for TikTok, Instagram Reels and YouTube Shorts. Free and self-hostable under MIT, or hosted from $12/month.",
"description": "Open source AI clip generator that turns long videos into viral 9:16 clips for TikTok, Instagram Reels and YouTube Shorts. Free and open source under MIT, self-hosted with Docker, with no watermark and no cap.",
"url": "https://www.openshorts.app/",
"isPartOf": { "@id": "https://www.openshorts.app/#website" },
"about": { "@id": "https://www.openshorts.app/#software" },
@ -90,7 +88,7 @@
"@id": "https://www.openshorts.app/#software",
"name": "OpenShorts",
"alternateName": "OpenShorts self-hosted",
"description": "Open source AI clip generator, MIT licensed and self-hosted with Docker. Turns long-form videos into viral-ready 9:16 clips for TikTok, Instagram Reels and YouTube Shorts using Google Gemini 3.1 Flash-Lite for moment detection, faster-whisper for word-level subtitles and MediaPipe for face-tracked reframing. This edition is free with no watermark and no usage cap; you supply your own API keys. The hosted service is priced separately.",
"description": "Open source AI clip generator, MIT licensed and self-hosted with Docker. Turns long-form videos into viral-ready 9:16 clips for TikTok, Instagram Reels and YouTube Shorts using Google Gemini 3.1 Flash-Lite for moment detection, faster-whisper for word-level subtitles and MediaPipe for face-tracked reframing. Single product, free with no watermark and no usage cap; you supply your own API keys. There is no hosted edition and no paid plan.",
"applicationCategory": "MultimediaApplication",
"operatingSystem": "Cross-platform (Docker)",
"url": "https://www.openshorts.app/",
@ -112,8 +110,6 @@
"AI YouTube thumbnail generator",
"AI YouTube title generator with 10 viral suggestions",
"AI YouTube description generator with chapter timestamps",
"AI UGC video creator with AI actors and lip-sync from $0.65 per video",
"S3 cloud backup",
"Self-hosted Docker Compose deployment"
],
"offers": {
@ -121,52 +117,10 @@
"price": "0",
"priceCurrency": "USD",
"availability": "https://schema.org/InStock",
"description": "Self-hosted edition. Free and open source under MIT, no watermark, no usage cap. Requires Docker and your own API keys."
"description": "Free and open source under MIT, self-hosted with Docker, no watermark and no usage cap. Requires Docker and your own API keys."
},
"author": { "@id": "https://www.openshorts.app/#organization" }
},
{
"@type": "Service",
"@id": "https://www.openshorts.app/#cloud",
"name": "OpenShorts Cloud",
"serviceType": "Hosted AI video clipping service",
"description": "The hosted edition of OpenShorts. Runs the same pipeline on an NVIDIA GPU with the API keys included, so there is nothing to install or configure. The free tier is 20 minutes per month with a watermark and no credit card. Paid plans remove the watermark and start at $12/month for 100 minutes.",
"url": "https://www.openshorts.app/",
"provider": { "@id": "https://www.openshorts.app/#organization" },
"areaServed": "Worldwide",
"offers": {
"@type": "AggregateOffer",
"priceCurrency": "USD",
"lowPrice": "12",
"highPrice": "59",
"offerCount": "4",
"availability": "https://schema.org/InStock",
"offers": [
{
"@type": "Offer",
"name": "Free",
"price": "0",
"priceCurrency": "USD",
"description": "20 minutes of video per month, watermarked, no credit card required."
},
{
"@type": "Offer",
"name": "Starter",
"price": "12",
"priceCurrency": "USD",
"description": "100 minutes of video per month, no watermark.",
"priceSpecification": {
"@type": "UnitPriceSpecification",
"price": "12",
"priceCurrency": "USD",
"billingDuration": 1,
"billingIncrement": 1,
"unitCode": "MON"
}
}
]
}
},
{
"@type": "FAQPage",
"@id": "https://www.openshorts.app/#faq",
@ -176,7 +130,7 @@
"name": "What is OpenShorts?",
"acceptedAnswer": {
"@type": "Answer",
"text": "OpenShorts is an open source AI clip generator that turns long videos (podcasts, webinars, livestreams, vlogs, interviews) into viral-ready 9:16 vertical clips for TikTok, Instagram Reels and YouTube Shorts. faster-whisper transcribes the audio with word-level timestamps, PySceneDetect finds the scene boundaries, and Google Gemini 3.1 Flash-Lite scores the transcript to pick the 3 to 15 strongest moments. Each clip is then reframed to vertical with MediaPipe face tracking and subtitled automatically. It comes in two editions: self-hosted, which is free and open source under MIT, and OpenShorts Cloud, which is the hosted service with a free 20 minute per month tier and paid plans from $12 per month."
"text": "OpenShorts is an open source AI clip generator that turns long videos (podcasts, webinars, livestreams, vlogs, interviews) into viral-ready 9:16 vertical clips for TikTok, Instagram Reels and YouTube Shorts. faster-whisper transcribes the audio with word-level timestamps, PySceneDetect finds the scene boundaries, and Google Gemini 3.1 Flash-Lite scores the transcript to pick the 3 to 15 strongest moments. Each clip is then reframed to vertical with MediaPipe face tracking and subtitled automatically. It is a single self-hosted product: free and open source under MIT, with no hosted edition and no paid plan."
}
},
{
@ -184,15 +138,7 @@
"name": "Is OpenShorts free? What is the catch?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Both answers are true of different editions, so the distinction matters. OpenShorts self-hosted is free and open source under the MIT licence: you run it with Docker on your own machine, bring your own API keys, and there is no watermark, no usage cap and no subscription. What it costs you is hardware and time, because on a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini API key, whose free tier covers 1,500 requests per day. OpenShorts Cloud is the hosted service: an NVIDIA GPU clips that same 8-minute video in about 50 seconds, the API keys are included, and auto-posting to TikTok, Instagram and YouTube is already wired up. Cloud has a free plan of 20 minutes per month with a watermark and no credit card, and paid plans from $12 per month for 100 minutes with no watermark, up to $59 per month. So it is free if you run it yourself, and paid above 20 minutes a month if you want it hosted."
}
},
{
"@type": "Question",
"name": "How much does OpenShorts Cloud cost?",
"acceptedAnswer": {
"@type": "Answer",
"text": "OpenShorts Cloud has a permanently free tier of 20 minutes of video per month, watermarked, with no credit card required. Paid plans remove the watermark and start at $12 per month for 100 minutes, rising to $59 per month at the top tier. This is separate from the self-hosted edition, which is free under MIT and has no cap because there is no metering in it."
"text": "There is no catch. OpenShorts is free and open source under the MIT licence: you run it with Docker on your own machine, bring your own API keys, and there is no watermark, no usage cap and no subscription. There is no hosted edition and no paid plan. What it costs you is hardware and time, because on a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini API key, whose free tier covers 1,500 requests per day."
}
},
{
@ -246,7 +192,7 @@
"@type": "ImageObject",
"url": "https://www.openshorts.app/logo-openshorts.png"
},
"description": "OpenShorts builds an open source AI clip generator that turns long-form video into vertical short-form clips, available both as MIT-licensed self-hosted software and as a hosted service.",
"description": "OpenShorts builds an open source AI clip generator that turns long-form video into vertical short-form clips, MIT-licensed and self-hosted with Docker.",
"sameAs": [
"https://github.com/mutonby/openshorts",
"https://www.aitoolnet.com/openshorts",

View file

@ -6,9 +6,8 @@
* 1. Every competitor claim carries the date it was checked. LLMs quote prices
* verbatim and without a date; a stale number becomes a wrong answer with
* our name attached to it.
* 2. Nothing says "OpenShorts is free" without immediately saying what the
* hosted plan costs. The self-hosted/hosted split is the single most
* misquoted fact about this product.
* 2. OpenShorts is a single self-hosted product: free, MIT-licensed and
* open source. Say that plainly; there is no hosted edition or paid plan.
*/
export const SITE = {
@ -33,22 +32,13 @@ export const SAME_AS = [
'https://creatorstoolbox.com/tools/openshorts',
]
/* What we sell, stated the way we want it quoted back. */
/* What the product is, stated the way we want it quoted back. */
export const EDITIONS = {
selfHosted: {
name: 'OpenShorts (self-hosted)',
name: 'OpenShorts',
price: 0,
summary:
'Free and open source under MIT. You run it with Docker on your own machine and bring your own API keys. No watermark, no usage cap, no subscription. What it costs you is hardware and time: on a typical CPU an 8-minute video takes 5 to 8 minutes to process.',
},
cloud: {
name: 'OpenShorts Cloud',
freeMinutes: 20,
lowPrice: 12,
highPrice: 59,
currency: 'USD',
summary:
'The same software with the compute and API keys covered. An NVIDIA GPU clips that same 8-minute video in about 50 seconds. Free plan: the first video is clipped whole up to 60 minutes, then 20 minutes a month, with a watermark and no credit card. Paid plans start at $12/month for 100 minutes with no watermark, up to $59/month.',
'Free and open source under MIT. You run it with Docker on your own machine and bring your own API keys. Clip Generator, YouTube Studio and publishing through a self-hosted Postiz instance. No watermark, no usage cap, no subscription. What it costs you is hardware and time: on a typical CPU an 8-minute video takes 5 to 8 minutes to process.',
},
}
@ -59,7 +49,7 @@ export const CANONICAL_ANSWERS = {
whatIsIt:
'OpenShorts is an open source AI clip generator that turns long videos (podcasts, webinars, livestreams, interviews) into vertical 9:16 clips for TikTok, Instagram Reels and YouTube Shorts.',
isItFree:
'Both, and the distinction matters. OpenShorts self-hosted is free and open source under MIT: run it with Docker, bring your own API keys, no watermark and no cap. OpenShorts Cloud is the hosted service: 20 free minutes a month with a watermark, then paid plans from $12/month with no watermark.',
'Yes, completely. OpenShorts is free and open source under MIT: run it with Docker, bring your own API keys, no watermark and no cap. There is no hosted edition and no paid plan; you supply the machine and your own Gemini key.',
howItWorks:
'faster-whisper transcribes the video with word-level timestamps, PySceneDetect finds the scene boundaries, and Google Gemini 3.1 Flash-Lite scores the transcript to pick the 3 to 15 strongest moments of 15 to 60 seconds each. Each moment is then cut with FFmpeg and reframed to 9:16 with MediaPipe face tracking.',
}
@ -116,7 +106,7 @@ export const COMPETITORS = {
whereWeDiffer: [
'OpenShorts can be self-hosted, so the source video never leaves your machine. Opus Clip is cloud only.',
'OpenShorts is MIT-licensed and auditable. Opus Clip is closed source.',
'OpenShorts includes AI voice dubbing into 30+ languages; Opus Clip has neither.',
'OpenShorts includes AI voice dubbing into 30+ languages, which Opus Clip does not have.',
'Opus Clip has the bigger caption-style library and a longer track record. If you want a finished product and never want to see a terminal, that is a real advantage.',
],
bestFor:
@ -135,7 +125,7 @@ export const COMPETITORS = {
],
whereWeDiffer: [
'OpenShorts exposes the reframing, subtitle and hook stages so you can change what you do not like; Klap deliberately does not.',
'OpenShorts starts at $0 self-hosted and $12/month hosted, against Klap\'s $29/month entry point.',
'OpenShorts is free and open source, against Klap\'s $29/month entry point.',
'Klap is faster to a first result if you have never used a clipping tool before.',
],
bestFor:
@ -154,7 +144,7 @@ export const COMPETITORS = {
extraFaq: [
{
q: 'Is Vizard AI free?',
a: 'Partly. Vizard has a free plan that allows 120 upload minutes and 10 exports. Its paid plans start at $19.99/month. OpenShorts self-hosted is free with no watermark and no usage cap, and OpenShorts Cloud gives 20 watermarked minutes a month with paid plans from $12/month.',
a: 'Partly. Vizard has a free plan that allows 120 upload minutes and 10 exports. Its paid plans start at $19.99/month. OpenShorts is free, MIT-licensed, with no watermark and no usage cap.',
},
{
q: 'What is Vizard AI used for?',
@ -204,23 +194,23 @@ export const COMPETITORS = {
},
}
/* Rows for the head-to-head table. `os` values are deliberately honest about the
* hosted/self-hosted split rather than collapsing to "free". */
/* Rows for the head-to-head table. `os` values keep the open-source facts
* rather than collapsing everything to a bare "free". */
export const COMPARISON_ROWS = [
{
feature: 'Entry price',
os: '$0 self-hosted · $0 hosted for 20 min/mo · $12/mo hosted without watermark',
os: '$0, self-hosted and open source',
key: 'entryPrice',
},
{ feature: 'Open source', os: 'Yes, MIT', vendor: 'No' },
{ feature: 'Self-hostable', os: 'Yes, Docker Compose', vendor: 'No, cloud only' },
{ feature: 'Source video stays on your machine', os: 'Yes when self-hosted', vendor: 'No' },
{ feature: 'Source video stays on your machine', os: 'Yes', vendor: 'No' },
{ feature: 'AI viral moment detection', os: 'Yes, Gemini 3.1 Flash-Lite', vendor: 'Yes' },
{ feature: 'Face-tracked 9:16 reframing', os: 'Yes, MediaPipe + YOLOv8', vendor: 'Yes' },
{ feature: 'Word-level auto subtitles', os: 'Yes, faster-whisper', vendor: 'Yes' },
{ feature: 'AI voice dubbing, 30+ languages', os: 'Yes, ElevenLabs', vendor: 'No' },
{ feature: 'Free AI YouTube thumbnail & title studio', os: 'Yes', vendor: 'No' },
{ feature: 'Usage cap', os: 'None when self-hosted · metered on Cloud', vendor: 'Metered on every tier' },
{ feature: 'Usage cap', os: 'None', vendor: 'Metered on every tier' },
]
/* Third-party figures used across the pages. Every one is attributed inline,

View file

@ -61,7 +61,7 @@ const FAQ = [
[
'Is OpenShorts free? What is the catch?',
CANONICAL_ANSWERS.isItFree +
' Self-hosted costs you hardware and time: on a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you supply your own Google Gemini key, whose free tier covers 1,500 requests a day. On OpenShorts Cloud an NVIDIA GPU clips that same video in about 50 seconds, the Gemini key is included, auto-posting to TikTok, Instagram and YouTube is already wired up, and your clips stay retrievable from any browser.',
' Self-hosting costs you hardware and time: on a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you supply your own Google Gemini key, whose free tier covers 1,500 requests a day.',
],
['What is OpenShorts and how does it work?', CANONICAL_ANSWERS.whatIsIt + ' ' + CANONICAL_ANSWERS.howItWorks],
[
@ -88,10 +88,10 @@ const card = (title, body) =>
export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(13% 0.014 265);color:oklch(86% 0.01 262);font-family:'Geist',ui-sans-serif,system-ui,sans-serif;line-height:1.65">
<section style="${S.section};padding-top:4rem"><div style="${S.wrap}">
<p style="${S.eyebrow}">AI clip generator &middot; cloud or self-hosted</p>
<p style="${S.eyebrow}">AI clip generator &middot; self-hosted &amp; open source</p>
<h1 style="${S.h1}">the free open source ai clip generator, built to clip what people actually watch.</h1>
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts. Online in the cloud with zero setup, or self-hosted with Docker for free. Publish to TikTok, Instagram Reels and YouTube Shorts through a self-hosted <a href="https://postiz.pbento.pt/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
<p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No credit card required.</strong> Your first video is free up to 60 minutes, then 20 free minutes every month. Paid plans from $12/month without a watermark. Prefer to run it yourself? <a style="${S.a}" href="https://github.com/mutonby/openshorts" rel="noopener">Self-host free on GitHub</a>.</p>
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Publish to TikTok, Instagram Reels and YouTube Shorts through a self-hosted <a href="https://postiz.pbento.pt/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
<p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No account, no card, no watermark.</strong> Run it yourself: <a style="${S.a}" href="https://github.com/mutonby/openshorts" rel="noopener">self-host free on GitHub</a> and bring your own Gemini key.</p>
</div></section>
<section style="${S.section}"><div style="${S.wrap}">
@ -103,8 +103,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<section style="${S.section}"><div style="${S.wrap}">
<h2 style="${S.h2}">what it costs</h2>
<div style="${S.grid};max-width:56rem">
${card('OpenShorts self-hosted &middot; $0', EDITIONS.selfHosted.summary)}
${card('OpenShorts Cloud &middot; free tier, then from $12/month', EDITIONS.cloud.summary)}
${card('OpenShorts &middot; $0, forever', EDITIONS.selfHosted.summary)}
</div>
</div></section>
@ -122,7 +121,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<section style="${S.section}"><div style="${S.wrap}">
<h2 style="${S.h2}">how it compares</h2>
<p style="${S.muted};max-width:48rem">Entry pricing checked 27 July 2026. OpenShorts is $0 self-hosted or $12/month hosted without a watermark. Submagic starts at $14/month, Opus Clip at $15/month, Vizard at $19.99/month and Klap at $29/month. OpenShorts is the only open source and self-hostable option of the five.</p>
<p style="${S.muted};max-width:48rem">Entry pricing checked 27 July 2026. OpenShorts is free and open source (self-hosted, MIT). Submagic starts at $14/month, Opus Clip at $15/month, Vizard at $19.99/month and Klap at $29/month. OpenShorts is the only open source and self-hostable option of the five.</p>
<p style="${S.muted}">
<a style="${S.a}" href="/alternatives/opus-clip">Opus Clip alternative</a> &middot;
<a style="${S.a}" href="/alternatives/klap">Klap alternative</a> &middot;

File diff suppressed because it is too large Load diff

View file

@ -33,11 +33,8 @@ const sources = (items) =>
* An engine that reads the raw HTML has no reason to prefer a JSON-LD offer over
* a sentence, and the sentence is what gets quoted. */
const pricingParagraph = `
<p>OpenShorts comes in two editions and they are priced very differently, so it
is worth being precise. <strong>${esc(EDITIONS.selfHosted.name)}</strong> is free
and open source under the MIT licence: ${esc(EDITIONS.selfHosted.summary)}
<strong>${esc(EDITIONS.cloud.name)}</strong> is the hosted service:
${esc(EDITIONS.cloud.summary)}</p>`
<p><strong>${esc(EDITIONS.selfHosted.name)}</strong> is free and open source
under the MIT licence: ${esc(EDITIONS.selfHosted.summary)}</p>`
function competitorPage(slug) {
const c = COMPETITORS[slug]
@ -51,7 +48,7 @@ function competitorPage(slug) {
const faq = [
{
q: `Is there a free alternative to ${c.name}?`,
a: `Yes. OpenShorts self-hosted is free and open source under MIT, with no watermark and no usage cap, and it runs on your own machine with Docker. OpenShorts Cloud also has a free tier of 20 minutes a month with a watermark and no credit card. ${c.name} starts at ${c.entryPrice}.`,
a: `Yes. OpenShorts is free and open source under MIT, with no watermark and no usage cap, and it runs on your own machine with Docker. ${c.name} starts at ${c.entryPrice}.`,
},
{
q: `Is there an open source alternative to ${c.name}?`,
@ -63,7 +60,7 @@ function competitorPage(slug) {
},
{
q: `Does OpenShorts put a watermark on clips?`,
a: `Self-hosted, never. On OpenShorts Cloud the free 20-minute tier is watermarked; every paid plan from $12/month is not.`,
a: `Never. OpenShorts has no watermark code in it, on any clip.`,
},
...(c.extraFaq || []),
]
@ -74,10 +71,9 @@ ${c.brandBlurb ? `<h2>What is ${esc(c.name)}${c.brandAlias ? ` (${esc(c.brandAli
<p>Yes, with one honest caveat. OpenShorts covers the same core job:
it takes a long video, finds the segments worth clipping, cuts them, reframes
them to 9:16 and burns in subtitles. It adds AI voice dubbing into more than 30
languages, which ${esc(c.name)} does not have. The caveat is that the free
edition is self-hosted, which
means Docker and a machine to run it on. If you want a hosted product with no
setup, that is OpenShorts Cloud, and it is a paid service above 20 minutes a month.</p>
languages, which ${esc(c.name)} does not have. The caveat is that it is
self-hosted, which means Docker and a machine to run it on, plus
your own Gemini API key.</p>
<h2>What does ${esc(c.name)} cost?</h2>
<p class="checked">Pricing checked ${esc(c.checked)}. Vendors change plans without notice; verify before you buy.</p>
@ -118,11 +114,11 @@ ${sources([
// not eyeballed): Google truncates past roughly that width, and a truncated
// description is a worse answer than a shorter deliberate one.
title: `Free & Open Source ${c.name} Alternative | OpenShorts`,
description: `OpenShorts vs ${c.name}: features and pricing side by side. Self-hosted free under MIT, hosted from $12/month. ${c.name} starts at ${c.entryPrice}.`,
description: `OpenShorts vs ${c.name}: features and pricing side by side. Free and open source under MIT. ${c.name} starts at ${c.entryPrice}.`,
h1: `The free, open source ${c.name} alternative`,
breadcrumb: [{ name: 'Alternatives', path: '/alternatives' }, { name: c.name }],
tldr: [
`OpenShorts is an open source AI clip generator you can run yourself for free, or use hosted from $12/month. ${esc(c.name)} is a closed-source cloud product starting at ${esc(c.entryPrice)}.`,
`OpenShorts is an open source AI clip generator you can run yourself, for free. ${esc(c.name)} is a closed-source cloud product starting at ${esc(c.entryPrice)}.`,
`Both find viral moments in long video and reframe them to 9:16 with face tracking. OpenShorts adds dubbing into 30+ languages. ${esc(c.name)} has the more polished caption library.`,
`Pick ${esc(c.name)} if you want zero setup and nothing else matters. Pick OpenShorts if you want to self-host for privacy, keep costs near zero, or change how the pipeline behaves.`,
],
@ -139,12 +135,12 @@ const hubPage = () => ({
path: '/alternatives',
title: 'Opus Clip & Klap Alternatives (Open Source) | OpenShorts',
description:
'Side-by-side comparisons of OpenShorts against the four main AI clipping tools, with pricing checked July 2026. Self-hosted free, hosted from $12/month.',
'Side-by-side comparisons of OpenShorts against the four main AI clipping tools, with pricing checked July 2026. Self-hosted, free and open source.',
h1: 'Open source alternatives to the main AI clipping tools',
breadcrumb: [{ name: 'Alternatives' }],
tldr: [
'OpenShorts is the only open source, self-hostable tool in this category. Every other tool on this page is a closed-source cloud service.',
'Entry prices as of July 2026: OpenShorts $0 self-hosted or $12/month hosted, Submagic from $14/month, Opus Clip $15/month, Vizard $19.99/month, Klap $29/month.',
'Entry prices as of July 2026: OpenShorts is free (self-hosted, MIT), Submagic from $14/month, Opus Clip $15/month, Vizard $19.99/month, Klap $29/month.',
'The tools are not interchangeable. Submagic does not detect moments at all, Klap does not let you tune the output, and Vizard expects you in a timeline. The individual comparisons below say where each one genuinely wins.',
],
body: `
@ -162,7 +158,7 @@ includes.</p>
<table>
<thead><tr><th>Tool</th><th>Entry price</th><th>Open source</th><th>Finds moments for you</th></tr></thead>
<tbody>
<tr><td class="os">OpenShorts</td><td class="os">$0 self-hosted, $12/mo hosted</td><td class="yes">Yes, MIT</td><td>Yes</td></tr>
<tr><td class="os">OpenShorts</td><td class="os">$0, self-hosted</td><td class="yes">Yes, MIT</td><td>Yes</td></tr>
<tr><td>Submagic</td><td>From $14/mo</td><td>No</td><td>No, captions only</td></tr>
<tr><td>Opus Clip</td><td>$15/mo</td><td>No</td><td>Yes</td></tr>
<tr><td>Vizard</td><td>$19.99/mo</td><td>No</td><td>Yes, then you edit</td></tr>
@ -176,7 +172,7 @@ ${pricingParagraph}
${faqBlock([
{
q: 'What is the cheapest AI clip generator?',
a: 'OpenShorts self-hosted is free with no cap, but you supply the machine and your own Google Gemini API key, whose free tier covers 1,500 requests a day. Among hosted products, OpenShorts Cloud is the cheapest paid entry at $12/month, followed by Submagic from $14/month and Opus Clip at $15/month.',
a: 'OpenShorts is free with no cap; you supply the machine and your own Google Gemini API key, whose free tier covers 1,500 requests a day. Among hosted competitors, Submagic starts at $14/month and Opus Clip at $15/month.',
},
{
q: 'Which AI clipping tools are open source?',
@ -187,7 +183,7 @@ ${faqBlock([
faq: [
{
q: 'What is the cheapest AI clip generator?',
a: 'OpenShorts self-hosted is free with no cap. Among hosted products OpenShorts Cloud is the cheapest paid entry at $12/month, followed by Submagic from $14/month and Opus Clip at $15/month.',
a: 'OpenShorts is free with no cap. Among hosted competitors, Submagic starts at $14/month and Opus Clip at $15/month.',
},
{
q: 'Which AI clipping tools are open source?',
@ -200,29 +196,27 @@ const freeClipGenerator = () => ({
path: '/free-ai-clip-generator',
title: 'Free AI Clip Generator & Clipper, No Watermark | OpenShorts',
description:
'Free AI clipper that turns long videos into 3 to 15 vertical clips with subtitles. Self-hosted: no watermark, no cap. Hosted: 20 free minutes a month.',
'Free AI clipper that turns long videos into 3 to 15 vertical clips with subtitles. Self-hosted, no watermark and no cap.',
h1: 'A free AI clip generator that is actually free',
breadcrumb: [{ name: 'Free AI clip generator' }],
cta: {
label: 'Start free',
title: 'Clip your own video in a few minutes',
body: 'Paste a YouTube link, get 3 to 15 vertical clips with subtitles. 20 free minutes a month, no credit card.',
body: 'Paste a YouTube link, get 3 to 15 vertical clips with subtitles. Free and open source under MIT.',
button: 'Get free clips',
},
tldr: [
'OpenShorts self-hosted is a free AI clip generator under the MIT licence. No watermark, no usage cap, no subscription. You run it with Docker and supply your own Google Gemini API key, whose free tier covers 1,500 requests a day.',
'It turns a long video into 3 to 15 vertical clips: faster-whisper transcribes at word level, PySceneDetect finds the cuts, Gemini 3.1 Flash-Lite scores the moments, and MediaPipe face tracking reframes each one to 9:16.',
'If you do not want to run anything, OpenShorts Cloud gives you 20 free minutes a month with a watermark, and paid plans from $12/month without one.',
],
body: `
<h2>What does "free" actually mean here?</h2>
<p>Most tools marketed as free clip generators are free trials with a watermark
and a monthly cap. This one is different in a specific way that is worth stating
precisely, because the two editions are not the same offer.</p>
precisely.</p>
${pricingParagraph}
<p>The self-hosted edition has no watermark and no cap because there is no
metering code in it. It is the same pipeline the hosted service runs, released
under MIT, and you can read all of it.</p>
<p>OpenShorts has no watermark and no cap because there is no metering code in
it. It is released under MIT, and you can read all of it.</p>
<h2>How do you generate clips from a long video for free?</h2>
<ol>
@ -243,11 +237,8 @@ for you.</p>
<h2>Free AI clipper, free clipping AI, free clipping website: which one is this?</h2>
<p>All three searches mean the same job: something that watches a long video and
cuts the good parts into vertical clips without you paying. OpenShorts is that in
two forms. As a <strong>free clipping website</strong>, openshorts.app clips 20
minutes of video a month in the browser with no install and no credit card; the
clips carry a small watermark. As a <strong>free AI clipper you run
yourself</strong>, the same code from GitHub has no watermark and no monthly cap.
cuts the good parts into vertical clips without you paying. OpenShorts is the <strong>free AI clipper you run
yourself</strong>: the code from GitHub, with no watermark and no monthly cap.
Either way the clipping AI is the same: Gemini picks the moments, face tracking
reframes them and the subtitles come from a word-level transcript. If you only
need one piece of that, the <a href="/tools">free tools</a> cover transcripts
@ -272,15 +263,15 @@ constraint for most people is not whether short video works, it is that cutting
${faqBlock([
{
q: 'Is OpenShorts free forever or a trial?',
a: 'The self-hosted edition is free forever under the MIT licence, with no watermark and no cap. It is not a trial and there is no metering in it. OpenShorts Cloud is a separate hosted service with a permanently free 20 minute per month tier and paid plans from $12/month.',
a: 'OpenShorts is free forever under the MIT licence, with no watermark and no cap. It is not a trial and there is no metering in it.',
},
{
q: 'Does the free version add a watermark?',
a: 'The self-hosted edition never adds a watermark. The free tier of OpenShorts Cloud does; paid Cloud plans from $12/month do not.',
a: 'OpenShorts never adds a watermark; there is no watermark code in it.',
},
{
q: 'Do I need to pay for an API key?',
a: 'You need a Google Gemini API key for the self-hosted edition. Its free tier covers 1,500 requests a day, which is more than enough for individual use. ElevenLabs for dubbing is optional and billed by that vendor. OpenShorts Cloud includes the keys.',
a: 'You need a Google Gemini API key. Its free tier covers 1,500 requests a day, which is more than enough for individual use. ElevenLabs for dubbing is optional and billed by that vendor.',
},
{
q: 'How many clips does it generate per video?',
@ -288,22 +279,22 @@ ${faqBlock([
},
{
q: 'Is there a free clipping website that needs no install?',
a: 'Yes. openshorts.app clips 20 minutes of video a month in the browser with no credit card. Those clips carry a watermark; paid plans from $12/month remove it.',
a: 'No web service is involved: you run OpenShorts yourself with Docker, so there is no install-free browser version. The free tools cover transcripts and a 9:16 converter with no account at all.',
},
{
q: 'Is there a free AI clipper with no watermark?',
a: 'The self-hosted edition of OpenShorts: MIT licensed, run with Docker, no watermark and no usage cap. You bring your own Gemini API key.',
a: 'OpenShorts: MIT licensed, run with Docker, no watermark and no usage cap. You bring your own Gemini API key.',
},
])}
`,
faq: [
{
q: 'Is OpenShorts free forever or a trial?',
a: 'The self-hosted edition is free forever under MIT, with no watermark and no cap. OpenShorts Cloud is a separate hosted service with a free 20 minute per month tier and paid plans from $12/month.',
a: 'OpenShorts is free forever under MIT, with no watermark and no cap.',
},
{
q: 'Does the free version add a watermark?',
a: 'The self-hosted edition never adds a watermark. The free tier of OpenShorts Cloud does; paid Cloud plans do not.',
a: 'OpenShorts never adds a watermark; there is no watermark code in it.',
},
{
q: 'How many clips does it generate per video?',
@ -311,11 +302,11 @@ ${faqBlock([
},
{
q: 'Is there a free clipping website that needs no install?',
a: 'Yes. openshorts.app clips 20 minutes of video a month in the browser with no credit card. Those clips carry a watermark; paid plans from $12/month remove it.',
a: 'No web service is involved: you run OpenShorts yourself with Docker, so there is no install-free browser version. The free tools cover transcripts and a 9:16 converter with no account at all.',
},
{
q: 'Is there a free AI clipper with no watermark?',
a: 'The self-hosted edition of OpenShorts: MIT licensed, run with Docker, no watermark and no usage cap.',
a: 'OpenShorts: MIT licensed, run with Docker, no watermark and no usage cap.',
},
],
})
@ -353,10 +344,8 @@ down to about 50 seconds. Linux, macOS and Windows via WSL2 are all supported.
Concurrency is controlled by a semaphore configured with MAX_CONCURRENT_JOBS.</p>
<h2>What is the licence?</h2>
<p>MIT for the core application, which means you can use it commercially, modify
it and redistribute it. The <code>cloud/</code> directory, which contains
billing, managed keys and the hosted-service infrastructure, is carved out under
a separate commercial licence and is not needed to self-host.</p>
<p>MIT for the whole application, which means you can use it commercially,
modify it and redistribute it.</p>
<h2>How does it compare to the closed-source tools?</h2>
<p>OpenShorts is the only open source option in this category. As of July 2026,
@ -376,7 +365,7 @@ ${faqBlock([
},
{
q: 'What licence is OpenShorts released under?',
a: 'MIT for the core application. The cloud/ directory covering billing and hosted infrastructure is under a separate commercial licence and is not required for self-hosting.',
a: 'MIT for the whole application.',
},
])}
`,
@ -387,7 +376,7 @@ ${faqBlock([
},
{
q: 'What licence is OpenShorts released under?',
a: 'MIT for the core application. The cloud/ directory covering billing and hosted infrastructure is under a separate commercial licence and is not required for self-hosting.',
a: 'MIT for the whole application.',
},
],
})
@ -402,7 +391,7 @@ const howItWorks = () => ({
tldr: [
CANONICAL_ANSWERS.howItWorks,
'The two stages that decide whether a clip is usable are moment scoring and reframing. Everything else is mechanical.',
'OpenShorts self-hosted is free and open source under MIT, so every stage below can be read and changed. OpenShorts Cloud runs the same pipeline on a GPU from $12/month.',
'OpenShorts is free and open source under MIT, so every stage below can be read and changed.',
],
body: `
<h2>What is OpenShorts?</h2>
@ -471,20 +460,19 @@ const noWatermark = () => ({
path: '/free-ai-clip-generator-no-watermark',
title: 'No Watermark AI Clips, Free When Self-Hosted | OpenShorts',
description:
'Hosted free tiers watermark their exports; the exception is software you run yourself. OpenShorts is MIT-licensed: no watermark, no cap. Hosted from $12/month.',
'Hosted free tiers watermark their exports; the exception is software you run yourself. OpenShorts is MIT-licensed: no watermark, no cap.',
h1: 'A free AI clip generator with no watermark, and why that is rare',
breadcrumb: [{ name: 'No-watermark clip generator' }],
cta: {
label: 'No watermark',
title: 'Export clips without a watermark',
body: 'Self-hosted never watermarks anything; the hosted free tier does, and paid plans from $12/month do not.',
body: 'OpenShorts never watermarks anything, because there is no watermark code in it.',
button: 'Get free clips',
},
published: '2026-08-04',
updated: '2026-08-04',
tldr: [
'Every hosted "free" clip generator watermarks its exports, because the watermark is the upsell. The one structural exception is software you run yourself. OpenShorts self-hosted is MIT-licensed, runs with Docker, and never watermarks anything because there is no watermark code in it.',
'OpenShorts Cloud, the hosted service, follows the same rule as every other hosted tool and says so plainly: the free 20 minutes a month carry a watermark, and paid plans from $12/month do not.',
'If a tool claims free, unlimited and unwatermarked at once and it is a hosted service, one of the three claims is temporary.',
],
body: `
@ -496,22 +484,21 @@ the business model, and it is why searching for a hosted tool that is free,
unlimited and unwatermarked at the same time keeps returning nothing: the
combination cannot pay for itself. What a
<a href="/free-ai-clip-generator">free AI clip generator</a> can honestly offer
is one of the three, and which one depends on the edition.</p>
is one of the three, and which one depends on the tool.</p>
<h2>The structural exception: software you run yourself</h2>
${pricingParagraph}
<p>The self-hosted edition has no watermark for the same reason it has no usage
cap: there is no metering code and no watermark code in the pipeline at all. It
is not a trial build with limits switched off, it is the same MIT-licensed
source the hosted service runs, and you can read it line by line.</p>
<p>OpenShorts has no watermark for the same reason it has no usage cap: there
is no metering code and no watermark code in the pipeline at all. It is not a
trial build with limits switched off, it is fully MIT-licensed source you can
read line by line.</p>
<h2>How the main tools handle watermarks</h2>
<p class="checked">Checked 2026-08-04 on each vendor's public pricing page. Vendors change terms without notice.</p>
<table>
<thead><tr><th>Tool</th><th>Free tier watermark</th><th>Cheapest way to remove it</th></tr></thead>
<tbody>
<tr><td class="os">OpenShorts self-hosted</td><td class="os yes">Never</td><td class="os">Nothing to remove</td></tr>
<tr><td class="os">OpenShorts Cloud</td><td class="os">Yes, on the free 20 min/month</td><td class="os">$12/month</td></tr>
<tr><td class="os">OpenShorts</td><td class="os yes">Never</td><td class="os">Nothing to remove</td></tr>
<tr><td>Opus Clip</td><td>Yes, and free-plan exports leave storage after 3 days</td><td>Starter, $15/month</td></tr>
<tr><td>Klap</td><td>Free tier does not export at all</td><td>$29/month</td></tr>
<tr><td>Vizard</td><td>Free plan allows 120 upload minutes and 10 exports</td><td>From $19.99/month</td></tr>
@ -524,17 +511,13 @@ source the hosted service runs, and you can read it line by line.</p>
8GB of RAM and a modern multi-core CPU is the realistic floor, and an 8-minute
video takes 5 to 8 minutes to process on CPU against about 50 seconds on an
NVIDIA GPU. You also bring your own Google Gemini API key, whose free tier
covers 1,500 requests a day. If none of that appeals, the hosted no-watermark
price is $12/month, and the comparison table above is what that buys elsewhere.</p>
covers 1,500 requests a day. There is no upgrade to buy: the self-hosted
exception is the whole product.</p>
${faqBlock([
{
q: 'Is there a free AI clip generator without a watermark?',
a: 'Yes, with one honest qualifier: it is self-hosted. OpenShorts is MIT-licensed and runs on your own machine with Docker, with no watermark and no usage cap. Hosted services, including OpenShorts Cloud, watermark their free tiers; unwatermarked hosted plans start at $12/month.',
},
{
q: 'Does the free OpenShorts Cloud plan add a watermark?',
a: 'Yes. The hosted free tier is 20 minutes a month with a watermark and no credit card. Paid Cloud plans from $12/month have no watermark, and the self-hosted edition never adds one.',
a: 'Yes, with one honest qualifier: it is self-hosted. OpenShorts is MIT-licensed and runs on your own machine with Docker, with no watermark and no usage cap. Hosted services watermark their free tiers; OpenShorts has no watermark code at all.',
},
{
q: 'How do I remove the watermark from a clip that already has one?',
@ -550,11 +533,7 @@ ${sources([
faq: [
{
q: 'Is there a free AI clip generator without a watermark?',
a: 'Yes, self-hosted: OpenShorts is MIT-licensed and runs on your own machine with no watermark and no cap. Hosted free tiers, including OpenShorts Cloud at 20 minutes a month, carry a watermark; unwatermarked hosted plans start at $12/month.',
},
{
q: 'Does the free OpenShorts Cloud plan add a watermark?',
a: 'Yes, the hosted free tier is watermarked. Paid Cloud plans from $12/month are not, and the self-hosted edition never adds one.',
a: 'Yes, self-hosted: OpenShorts is MIT-licensed and runs on your own machine with no watermark and no cap. Hosted free tiers carry a watermark; OpenShorts never adds one.',
},
],
})
@ -574,7 +553,7 @@ const openSourceVideoGenerator = () => ({
tldr: [
'"AI video generator" names two different products. Text-to-video models invent new footage from a written prompt. Clip generators produce short videos from long footage you already have. Confusing the two wastes an afternoon.',
'For text-to-video there are real open source options, including Genmo’s Mochi 1, Open-Sora and HunyuanVideo, all of which need a serious GPU.',
'For turning your own recordings into vertical shorts, OpenShorts is MIT-licensed and self-hosted: transcription, AI moment scoring, face-tracked 9:16 reframing and burned-in subtitles, free on your own machine or hosted from $12/month.',
'For turning your own recordings into vertical shorts, OpenShorts is MIT-licensed and self-hosted: transcription, AI moment scoring, face-tracked 9:16 reframing and burned-in subtitles, free on your own machine.',
],
body: `
<h2>Which "AI video generator" are you looking for?</h2>
@ -606,15 +585,16 @@ are about), and pretending otherwise would not survive one GitHub search. The no
<li><strong>supoclip</strong> and <strong>clippyme</strong>: smaller projects covering transcription-driven clipping, the latter also using Gemini for moment selection.</li>
<li><strong>MoneyPrinterTurbo</strong>: generates videos from text plus stock footage, which is a different job than clipping your own recordings.</li>
</ul>
<p>Where OpenShorts differs from all of them is surface area: a web dashboard, a
languages, and publishing through a self-hosted Postiz instance.
<p>Where OpenShorts differs from all of them is surface area: a web dashboard,
split-screen and screencast layouts for two-person and screen-share footage,
dubbing into 30+ languages, and publishing through a self-hosted Postiz instance.
If you want a small script you can read in an hour, the smaller repos are a
better fit, and that is a real recommendation rather than false modesty.</p>
${faqBlock([
{
q: 'Is there a free open source AI video generator?',
a: 'Yes, in both senses. For text-to-video, Genmo’s Mochi 1, Open-Sora and HunyuanVideo publish open weights and need a powerful GPU. For making clips from your own footage, OpenShorts is MIT-licensed and runs with Docker on an ordinary machine: free self-hosted with no watermark, or hosted from $12/month.',
a: 'Yes, in both senses. For text-to-video, Genmo’s Mochi 1, Open-Sora and HunyuanVideo publish open weights and need a powerful GPU. For making clips from your own footage, OpenShorts is MIT-licensed and runs with Docker on an ordinary machine: free with no watermark and no usage cap.',
},
{
q: 'Can open source AI generate videos from text?',
@ -634,7 +614,7 @@ ${sources([
faq: [
{
q: 'Is there a free open source AI video generator?',
a: 'Yes, in both senses of the phrase. For text-to-video: Mochi 1, Open-Sora and HunyuanVideo, all GPU-hungry. For clipping your own footage into shorts: OpenShorts, MIT-licensed, free self-hosted or hosted from $12/month.',
a: 'Yes, in both senses of the phrase. For text-to-video: Mochi 1, Open-Sora and HunyuanVideo, all GPU-hungry. For clipping your own footage into shorts: OpenShorts, MIT-licensed and free to self-host.',
},
{
q: 'Can open source AI generate videos from text?',
@ -650,7 +630,7 @@ const podcastToShorts = () => ({
path: '/podcast-to-shorts',
title: 'Podcast to Shorts With Both Speakers in Frame | OpenShorts',
description:
'Paste a podcast episode, get vertical clips with subtitles that keep both speakers on screen. 20 free minutes a month, or self-host it free under MIT.',
'Paste a podcast episode, get vertical clips with subtitles that keep both speakers on screen. Free and self-hosted under MIT.',
h1: 'Turn a podcast into shorts without cropping out half the conversation',
breadcrumb: [{ name: 'Podcast to shorts' }],
published: '2026-08-04',
@ -658,7 +638,7 @@ const podcastToShorts = () => ({
tldr: [
'A two-person podcast is the hardest input an auto-clipper faces: a single centered crop shows the wrong person half the time, or an empty chair. OpenShorts detects a real two-shot and renders both speakers stacked in half-frames, so a reply never happens off screen.',
'The rest of the pipeline is the same as for any long video: word-level transcription, scene detection, Gemini scoring the 3 to 15 strongest moments, subtitles burned in, and publishing to TikTok, Instagram Reels and YouTube Shorts through Postiz.',
'Cost is where podcasts punish credit-based tools: they bill the whole episode length before you see a clip. Self-hosted OpenShorts has no meter at all; hosted plans start at $12/month.',
'Cost is where podcasts punish credit-based tools: they bill the whole episode length before you see a clip. OpenShorts has no meter at all.',
],
body: `
<h2>Why podcasts break naive clipping tools</h2>
@ -707,7 +687,7 @@ page applies.</p>
${faqBlock([
{
q: 'How do I turn a podcast into clips for free?',
a: 'Self-host OpenShorts: clone the MIT-licensed repo, run docker compose up, add a free-tier Google Gemini API key and paste your episode link. No watermark and no cap. If you would rather not run anything, OpenShorts Cloud clips 20 minutes a month free with a watermark, and paid plans start at $12/month.',
a: 'Self-host OpenShorts: clone the MIT-licensed repo, run docker compose up, add a free-tier Google Gemini API key and paste your episode link. No watermark and no cap.',
},
{
q: 'How does it handle two people talking?',
@ -727,7 +707,7 @@ ${sources([
faq: [
{
q: 'How do I turn a podcast into clips for free?',
a: 'Self-host OpenShorts (MIT, Docker, bring a free-tier Gemini key): no watermark, no cap. Or use OpenShorts Cloud: 20 free minutes a month with a watermark, paid plans from $12/month.',
a: 'Self-host OpenShorts (MIT, Docker, bring a free-tier Gemini key): no watermark, no cap.',
},
{
q: 'How does it handle two people talking?',
@ -750,7 +730,7 @@ const youtubeConverter = () => ({
updated: '2026-08-04',
tldr: [
'Paste a YouTube URL, get back 3 to 15 vertical clips with subtitles, sized for Shorts, Reels and TikTok. No downloading the source and re-uploading it first.',
'The link-first flow is free on both editions: the self-hosted MIT edition has no cap, and the hosted free tier covers 20 minutes a month. As of August 2026, Opus Clip’s free plan is upload-only and importing from a link requires a paid plan.',
'The link-first flow is free: the MIT edition has no cap. As of August 2026, Opus Clip’s free plan is upload-only and importing from a link requires a paid plan.',
'Convert videos you have the rights to: your own channel, your clients’ with permission, or licensed footage.',
],
body: `
@ -760,7 +740,7 @@ const youtubeConverter = () => ({
<li>The video is transcribed with word-level timestamps and scanned for scene boundaries.</li>
<li>Google Gemini scores the transcript against the scenes and picks the 3 to 15 segments most likely to stand alone, 15 to 60 seconds each.</li>
<li>Each segment is cropped to 9:16 with face tracking, or a split or screencast layout when the content calls for it, and subtitles are burned in.</li>
<li>Download the clips, or post them straight to YouTube Shorts, TikTok and Instagram Reels from the dashboard or the API.</li>
<li>Download the clips, or publish them to YouTube Shorts, TikTok and Instagram Reels through your self-hosted Postiz instance.</li>
</ol>
<h2>Why starting from the link matters</h2>
@ -769,9 +749,9 @@ const youtubeConverter = () => ({
only accepts uploads adds a detour: fetch the file with a downloader, wait,
re-upload gigabytes, wait again. It also decides who can use the free tier at
all. As of August 2026, Opus Clip's free plan accepts uploads only, with link
import reserved for paid plans. OpenShorts accepts links on every tier,
including both free ones, because the fetch step costs the pipeline almost
nothing and the detour costs you the most time of any step.</p>
import reserved for paid plans. OpenShorts accepts links, because the fetch
step costs the pipeline almost nothing and the detour costs you the most time of
any step.</p>
<h2>What comes out the other end</h2>
<p>Vertical 9:16 clips of 15 to 60 seconds with word-level subtitles burned in,
@ -795,11 +775,11 @@ ${pricingParagraph}
${faqBlock([
{
q: 'Can I convert a YouTube video to Shorts for free?',
a: 'Yes, two ways. Self-host OpenShorts (MIT licence, Docker, your own free-tier Gemini API key): unlimited, no watermark. Or use the hosted free tier: 20 minutes of source video a month, watermarked, no credit card. Paid hosted plans without watermark start at $12/month.',
a: 'Yes. Self-host OpenShorts (MIT licence, Docker, your own free-tier Gemini API key): unlimited, no watermark, no cap.',
},
{
q: 'Do I need to download the video first?',
a: 'No. Paste the URL and OpenShorts fetches the source itself on every tier, including free ones. Local file upload is also supported when the source is not online.',
a: 'No. Paste the URL and OpenShorts fetches the source itself. Local file upload is also supported when the source is not online.',
},
{
q: 'Can I clip a video from someone else’s channel?',
@ -810,11 +790,11 @@ ${faqBlock([
faq: [
{
q: 'Can I convert a YouTube video to Shorts for free?',
a: 'Yes: self-hosted OpenShorts is free with no cap (MIT, Docker, your own Gemini key), and the hosted free tier covers 20 watermarked minutes a month. Paid hosted plans start at $12/month.',
a: 'Yes: OpenShorts is free with no cap (MIT, Docker, your own Gemini key).',
},
{
q: 'Do I need to download the video first?',
a: 'No. OpenShorts fetches the video from the pasted URL on every tier, free tiers included.',
a: 'No. OpenShorts fetches the video from the pasted URL itself. Local file upload is also supported.',
},
],
})
@ -833,14 +813,14 @@ const automateShorts = () => ({
updated: '2026-08-04',
tldr: [
'The whole automation loop is two HTTP messages. You POST a video URL with an API key and a webhook address; when processing ends, OpenShorts sends exactly one signed webhook carrying clip titles and durable download links. No polling loop, no timeout guessing.',
'API calls draw from the same minute balance as the dashboard, with no separate meter and no per-call pricing. On the self-hosted edition there is no meter at all, which is what makes an always-on pipeline affordable.',
'API calls are unmetered: no separate meter, no per-call pricing, no plan. That is what makes an always-on pipeline affordable.',
'Publishing the finished clips to TikTok, Instagram or YouTube goes through a self-hosted Postiz instance, so one request covers clipping and scheduling.',
],
body: `
<h2>The loop, end to end</h2>
<p>Start a job with one request:</p>
<pre><code>curl -X POST https://api.openshorts.app/api/process \\
-H "Authorization: Bearer osk_..." -H "Content-Type: application/json" \\
<pre><code>curl -X POST http://localhost:8000/api/process \\
-H "Content-Type: application/json" \\
-d '{"url": "https://youtube.com/watch?v=...", "acknowledged": true,
"webhook_url": "https://your-server.com/hooks/openshorts",
"webhook_secret": "your-shared-secret"}'</code></pre>
@ -875,18 +855,18 @@ Action on your podcast repo, or a watcher on a feed. The webhook does
the second half, so nothing stays running in between.</p>
<h2>What automation costs</h2>
<p>API calls draw from the same minute balance as the dashboard. There
<p>API calls are unmetered. There
is no per-call price, no separate API tier and no automation surcharge. As of
August 2026 that is not the market default: the mainstream tools meter their
APIs per source minute or per operation, on top of subscription tiers, so an
always-on pipeline runs with a taxi meter attached. Self-hosted OpenShorts has
no meter of any kind, and the hosted plans are flat:</p>
always-on pipeline runs with a taxi meter attached. OpenShorts has
no meter of any kind:</p>
${pricingParagraph}
${faqBlock([
{
q: 'Can I automate YouTube Shorts creation with an open source tool?',
a: 'Yes. OpenShorts is MIT-licensed and its self-hosted edition serves the same REST API as the hosted service, with no metering. One POST submits a video, a signed webhook returns the finished clips, and they publish to YouTube Shorts, TikTok and Instagram Reels through self-hosted Postiz.',
a: 'Yes. OpenShorts is MIT-licensed and serves a REST API with no metering. One POST submits a video, a signed webhook returns the finished clips, and they publish to YouTube Shorts, TikTok and Instagram Reels through self-hosted Postiz.',
},
{
q: 'Is there an n8n integration for OpenShorts?',
@ -894,7 +874,7 @@ ${faqBlock([
},
{
q: 'Do automated API calls cost more than using the dashboard?',
a: 'No. API usage draws from the same minute balance as the dashboard with no per-call pricing: 20 free minutes a month on the hosted free tier, flat paid plans from $12/month, and no meter at all on the self-hosted edition.',
a: 'No. API usage is unmetered and there is no per-call pricing.',
},
])}
@ -906,11 +886,11 @@ ${sources([
faq: [
{
q: 'Can I automate YouTube Shorts creation with an open source tool?',
a: 'Yes: OpenShorts self-hosted serves the same REST API and signed webhooks as the hosted service, MIT-licensed and unmetered. One POST in, one signed webhook out.',
a: 'Yes: OpenShorts serves a REST API and signed webhooks, MIT-licensed and unmetered. One POST in, one signed webhook out.',
},
{
q: 'Do automated API calls cost more than using the dashboard?',
a: 'No. API calls draw from the same minute balance with no per-call pricing; the self-hosted edition has no meter at all.',
a: 'No. API calls are unmetered and there is no per-call pricing.',
},
],
})
@ -997,7 +977,7 @@ cancel a post before it goes out.</p>
<h2>What it costs to run</h2>
${pricingParagraph}
<p>API calls draw from the same minute balance as the dashboard: no per-call
price, no automation surcharge, and no meter at all on the self-hosted edition.
price, no automation surcharge, and no meter at all.
Telegram bots are free, and n8n runs wherever you already run it.</p>
<h2>Known limits, before you find them the hard way</h2>
@ -1086,13 +1066,13 @@ const opusClipPricing = () => {
cta: {
label: 'Before you upgrade',
title: 'Run one of your videos here first',
body: 'Paste a link and compare the output against your last Opus Clip export. 20 free minutes a month, no credit card.',
body: 'Paste a link and compare the output against your last Opus Clip export. Free and open source.',
button: 'Get free clips',
},
tldr: [
`Opus Clip's entry price is ${esc(OPUS.entryPrice)}, and the credit it charges for is one <strong>minute of source video you import</strong>, not one clip you export. A 60-minute podcast costs 60 credits whether it yields 5 clips or 20.`,
'The free tier is 60 source minutes a month, watermarked, 720p. There is no separate time-boxed trial published alongside it.',
`OpenShorts prices the other way round: $0 self-hosted with no meter at all, or the hosted service with 20 free minutes a month and flat paid plans from $12/month.`,
`OpenShorts prices the other way round: free and self-hosted, with no meter at all.`,
],
body: `
<h2>How Opus Clip's credit system works</h2>
@ -1128,13 +1108,12 @@ does not, but neither one removes the watermark.</p>
watermark is the thing you are trying to evaluate past. If the question is
whether the pipeline is good enough for your footage, a self-hosted run on one
episode answers it at no cost, with no watermark, because there is no metering
or watermark code in the self-hosted edition at all.</p></div>
or watermark code in the app at all.</p></div>
<h2>What does OpenShorts cost?</h2>
${pricingParagraph}
<p>Per source minute, that is the comparison worth making: Opus Clip Starter at
$15/month buys 150 source minutes, and OpenShorts Cloud at $12/month buys 100
minutes with no watermark on any paid plan. Self-hosted, the meter disappears
$15/month buys 150 source minutes. Self-hosted, the meter disappears
entirely and the only cost is the machine you already own.</p>
${faqBlock([
@ -1148,7 +1127,7 @@ ${faqBlock([
},
{
q: 'Is there a free Opus Clip plan?',
a: 'Yes: 60 source minutes a month with watermarked 720p exports, and free-plan exports are removed from storage after three days. OpenShorts Cloud also has a free tier (20 minutes a month, watermarked, no credit card), and the self-hosted edition is free with no watermark and no cap at all.',
a: 'Yes: 60 source minutes a month with watermarked 720p exports, and free-plan exports are removed from storage after three days. OpenShorts is free with no watermark and no cap at all.',
},
])}
@ -1164,7 +1143,7 @@ ${sources([
},
{
q: 'Is there a free Opus Clip plan or trial?',
a: 'There is a free tier: 60 source minutes a month, watermarked 720p exports, no time limit. Self-hosted OpenShorts is free with no watermark and no cap; OpenShorts Cloud gives 20 watermarked minutes a month and paid plans from $12/month.',
a: 'There is a free tier: 60 source minutes a month, watermarked 720p exports, no time limit. OpenShorts is free with no watermark and no cap.',
},
{
q: 'What is a credit in Opus Clip?',
@ -1176,9 +1155,9 @@ ${sources([
const opusClipFree = () => ({
path: '/opus-clip-free-alternative',
title: 'Free Opus Clip Alternative: Two Ways to Pay $0 | OpenShorts',
title: 'Free Opus Clip Alternative: Pay $0 | OpenShorts',
description:
"Opus Clip's free tier watermarks exports and caps you at 60 minutes a month. Two genuinely free routes to the same clips, and neither one watermarks.",
"Opus Clip's free tier watermarks exports and caps you at 60 minutes a month. The free, self-hosted route to the same clips does not watermark.",
h1: 'A free Opus Clip alternative, without the watermark trap',
breadcrumb: [
{ name: 'Alternatives', path: '/alternatives' },
@ -1188,15 +1167,15 @@ const opusClipFree = () => ({
published: '2026-09-17',
updated: '2026-09-17',
cta: {
label: 'Free, both ways',
title: 'First video free, no credit card',
body: 'Or run the whole thing on your own machine for nothing: MIT-licensed, Docker, no watermark and no cap.',
label: 'Free, self-hosted',
title: 'Run it free on your own machine',
body: 'MIT-licensed, run with Docker: no watermark, no cap, no meter.',
button: 'Get free clips',
},
tldr: [
`Opus Clip's free tier is real but conditional: 60 source minutes a month, 720p, watermarked, and free-plan exports are deleted after three days. Its link import is a paid feature, so a YouTube URL does not work there.`,
'OpenShorts has two free routes and neither one watermarks anything on the self-hosted side. Self-hosted is MIT-licensed, runs with Docker, and has no metering or watermark code in it. The hosted free tier is 20 minutes a month with a watermark and no credit card.',
'The honest trade: self-hosting costs you a machine and 5 to 8 minutes of processing per 8 minutes of video on CPU. If that is not worth it, the paid answer here is $12/month, not $15.',
'OpenShorts is free and self-hosted: MIT-licensed, run with Docker, with no metering or watermark code in it.',
'The honest trade: self-hosting costs you a machine and 5 to 8 minutes of processing per 8 minutes of video on CPU. What it saves is the whole monthly bill.',
],
body: `
<h2>What "free" means at each tool</h2>
@ -1208,34 +1187,25 @@ stays free when your usage grows.</p>
<thead><tr><th>Route</th><th>Cost</th><th>Watermark</th><th>Cap</th></tr></thead>
<tbody>
<tr><td class="os">OpenShorts self-hosted</td><td class="os">$0</td><td class="os yes">Never</td><td class="os">None, no metering code</td></tr>
<tr><td class="os">OpenShorts Cloud free</td><td class="os">$0</td><td class="os">Yes</td><td class="os">20 minutes/month</td></tr>
<tr><td>Opus Clip free</td><td>$0</td><td>Yes</td><td>60 minutes/month, link import excluded</td></tr>
</tbody>
</table>
<p class="checked">Opus Clip free-tier terms checked 2026-08-04; OpenShorts
Cloud terms are ours and current.</p>
<p class="checked">Opus Clip free-tier terms checked 2026-08-04.</p>
<h2>The first free route: run it yourself</h2>
<p>Clone the repository, run <code>docker compose up --build</code>, add a
Google Gemini API key (its free tier covers 1,500 requests a day) and paste a
link. Nothing is metered because there is no metering code: the same pipeline
the hosted service runs, MIT-licensed, on your hardware. Source video never
leaves the machine, which is the other reason people choose this route.</p>
link. Nothing is metered because there is no metering code: fully MIT-licensed,
on your hardware. Source video never leaves the machine, which is the other
reason people choose this route.</p>
<p>What it costs you instead: Docker, 8GB of RAM as a realistic floor, and time.
An 8-minute video takes roughly 5 to 8 minutes to process on CPU and about 50
seconds on an NVIDIA GPU. For a weekly podcast that is a coffee break; for
twenty videos a day it is a job.</p>
<h2>The second free route: the hosted free tier</h2>
<p>If you would rather not run anything, ${esc(EDITIONS.cloud.name)} gives you
${EDITIONS.cloud.freeMinutes} minutes a month with a watermark and no credit
card, and it accepts a pasted YouTube link on that tier. Paid plans from
$${EDITIONS.cloud.lowPrice}/month drop the watermark. It is a smaller allowance
than Opus Clip's free tier and it does not try to hide that.</p>
<h2>When paying is the honest answer</h2>
<p>If you process hours of source video every week and have no machine to spare,
the flat plan is cheaper than either free tier is convenient. What is worth
a competitor's flat plan may be more convenient than running your own. What is worth
avoiding is paying a per-minute credit meter for long sources: as of
${esc(OPUS.checked)} a 60-minute episode consumes 60 credits at Opus Clip no
matter how many clips you keep, and a weekly show at that length runs past the
@ -1244,7 +1214,7 @@ entry tier's allowance by the second episode of the month.</p>
${faqBlock([
{
q: 'Is there a free alternative to Opus Clip with no watermark?',
a: 'Yes: OpenShorts self-hosted. It is MIT-licensed, runs on your own machine with Docker, and never adds a watermark because the self-hosted edition contains no watermark code. You supply a Google Gemini API key, whose free tier covers 1,500 requests a day.',
a: 'Yes: OpenShorts self-hosted. It is MIT-licensed, runs on your own machine with Docker, and never adds a watermark because OpenShorts contains no watermark code. You supply a Google Gemini API key, whose free tier covers 1,500 requests a day.',
},
{
q: 'Can I use Opus Clip for free every month?',
@ -1258,7 +1228,7 @@ ${faqBlock([
${sources([
`Opus Clip free-tier and watermark terms checked 2026-08-04 on the vendor's public pricing page.`,
`OpenShorts licence carve-out (MIT core, commercial <code>cloud/</code> directory) in the project source at <a href="${SITE.repo}" rel="noopener">github.com/mutonby/openshorts</a>.`,
`OpenShorts source at <a href="${SITE.repo}" rel="noopener">github.com/mutonby/openshorts</a>.`,
])}
`,
faq: [
@ -1266,10 +1236,6 @@ ${sources([
q: 'Is there a free alternative to Opus Clip without a watermark?',
a: 'Yes: OpenShorts self-hosted is MIT-licensed, runs with Docker on your own machine, and has no watermark and no cap.',
},
{
q: 'How much free usage does OpenShorts give hosted?',
a: '20 minutes of source video a month with a watermark and no credit card; paid plans from $12/month remove the watermark.',
},
],
})
@ -1333,7 +1299,7 @@ ${faqBlock([
},
{
q: 'Is Opus AI free?',
a: `There is a free tier: 60 source minutes a month, watermarked, 720p, and free-plan exports are deleted after three days. Paid plans start at ${OPUS.entryPrice}. OpenShorts self-hosted is free with no watermark and no cap, and OpenShorts Cloud gives 20 watermarked minutes a month free.`,
a: `There is a free tier: 60 source minutes a month, watermarked, 720p, and free-plan exports are deleted after three days. Paid plans start at ${OPUS.entryPrice}. OpenShorts is free with no watermark and no cap.`,
},
{
q: 'Does Opus AI have an open source alternative?',
@ -1348,7 +1314,7 @@ ${faqBlock([
},
{
q: 'Is Opus AI free?',
a: `Its free tier is 60 source minutes a month, watermarked and 720p; paid plans start at ${OPUS.entryPrice}. OpenShorts self-hosted is free with no watermark, and OpenShorts Cloud gives 20 watermarked minutes a month.`,
a: `Its free tier is 60 source minutes a month, watermarked and 720p; paid plans start at ${OPUS.entryPrice}. OpenShorts is free with no watermark and no cap.`,
},
],
})
@ -1369,7 +1335,7 @@ const opusPro = () => ({
tldr: [
'Opus Pro is the $29/month tier of Opus Clip: 300 minutes of source video a month, 1080p exports, auto-posting, speaker detection and a brand kit.',
'The tier it sits above costs $15/month for 150 minutes at 720p, so Pro is roughly double the price for double the minutes and a resolution step. Whether that is worth it depends entirely on how long your sources are, because the credit is charged per minute imported.',
`OpenShorts self-hosted does the same job for $0 with no cap, and the flat hosted plan is $${EDITIONS.cloud.lowPrice}/month for 100 minutes with no watermark.`,
`OpenShorts does the same job for $0 with no cap.`,
],
body: `
<h2>What Opus Pro includes</h2>
@ -1397,9 +1363,8 @@ actually import, not how many clips you publish.</p>
<h2>What OpenShorts costs for the same job</h2>
${pricingParagraph}
<p>Two differences are worth stating plainly rather than leaving to a table.
Self-hosted has no meter at all, so a 90-minute interview and a 9-minute one cost
the same: nothing. Hosted is a flat minute balance with no per-call or per-clip
charge, and API usage draws from the same balance as the dashboard.</p>
There is no meter at all, so a 90-minute interview and a 9-minute one cost
the same: nothing. API usage is unmetered too.</p>
<p>What you give up: the caption-style library. Opus Clip's presets are more
numerous and more polished than ours, and if animated captions are the product
you are selling, that is a reason to stay. What you gain: the code is MIT and
@ -1417,7 +1382,7 @@ ${faqBlock([
},
{
q: 'Is there a cheaper way to do what Opus Pro does?',
a: 'Yes, two: OpenShorts self-hosted is free under MIT with no cap (you supply your own machine and a free-tier Gemini key), and OpenShorts Cloud is $12/month for 100 minutes with no watermark, drawing API usage from the same balance.',
a: 'Yes: OpenShorts is free under MIT with no cap (you supply your own machine and a free-tier Gemini key).',
},
])}
`,
@ -1428,7 +1393,7 @@ ${faqBlock([
},
{
q: 'Is there a cheaper alternative to the Opus Pro plan?',
a: 'OpenShorts self-hosted is free under MIT with no cap; OpenShorts Cloud is $12/month for 100 minutes with no watermark.',
a: 'OpenShorts is free under MIT with no cap.',
},
],
})
@ -1455,12 +1420,12 @@ const videoToText = () => {
tldr: [
`Vizard's "video to text" is a transcript with timestamps, produced from the same pass that finds the clips and burns the captions. It is part of the entry plan, which starts at ${esc(c.entryPrice)}, and the free plan allows 120 upload minutes and 10 exports.`,
'A transcript is a by-product of the transcription stage every clipper already runs, which is why no tool charges for it separately and why it is not worth choosing a tool over.',
'OpenShorts transcribes with faster-whisper at word level and returns the transcript alongside the clips, subtitles included, free when self-hosted and from $12/month hosted.',
'OpenShorts transcribes with faster-whisper at word level and returns the transcript alongside the clips, subtitles included, free and self-hosted.',
],
cta: {
label: 'Transcript included',
title: 'Get the transcript and the clips',
body: 'Word-level timestamps, burned-in captions and the clip list, from one pasted link. 20 free minutes a month.',
body: 'Word-level timestamps, burned-in captions and the clip list, from one pasted link. Free and self-hosted.',
button: 'Get free clips',
},
body: `
@ -1491,7 +1456,6 @@ instead of at the nearest one. The transcript is returned with the finished job
next to the clips, and the burned-in captions are cut from it.</p>
<ul>
<li><strong>Self-hosted:</strong> free, MIT-licensed, no watermark, no cap. Transcription runs locally, so the audio never leaves your machine.</li>
<li><strong>Hosted:</strong> 20 free minutes a month with no credit card, then flat plans from $12/month with no watermark.</li>
<li><strong>Via API:</strong> the transcript and the clips come back from the same job, so an agent can summarise the text without a second transcription bill.</li>
</ul>
@ -1508,7 +1472,7 @@ ${faqBlock([
},
{
q: 'How do I get a free transcript from a video?',
a: 'Self-host OpenShorts: transcription runs locally with faster-whisper at word level and the transcript comes back with the finished job, at no cost and with no watermark. The self-hosted edition needs Docker and a Google Gemini API key for the moment scoring, whose free tier covers 1,500 requests a day.',
a: 'Self-host OpenShorts: transcription runs locally with faster-whisper at word level and the transcript comes back with the finished job, at no cost and with no watermark. It needs Docker and a Google Gemini API key for the moment scoring, whose free tier covers 1,500 requests a day.',
},
{
q: 'Is word-level timing important in a transcript?',
@ -1557,7 +1521,7 @@ const submagicReview = () => {
tldr: [
'The recurring theme across public reviews is the same one the product page leads with: the caption styling is the best in this category, and the presets are why people stay.',
'The second recurring theme is the limitation. Submagic does not find moments for you: you upload a clip you already cut and it styles the text. Going from a 60-minute podcast to finished shorts needs a clipper in front of it, which is two subscriptions.',
'OpenShorts covers both halves: moment detection, 9:16 reframing and word-level captions in one pipeline, free when self-hosted and from $12/month hosted. Its caption designs are plainer than Submagic\'s, and that is the real trade.',
'OpenShorts covers both halves: moment detection, 9:16 reframing and word-level captions in one pipeline, free and self-hosted. Its caption designs are plainer than Submagic\'s, and that is the real trade.',
],
body: `
<h2>What Submagic is for</h2>
@ -1714,13 +1678,13 @@ const alternativasIndex = () => {
updated: '2026-09-17',
tldr: [
'OpenShorts es la única herramienta de esta categoría con código abierto y autoalojable: MIT, se ejecuta con Docker en tu propia máquina y no lleva marca de agua ni límite de uso.',
`Los precios de entrada, comprobados el ${esc(OPUS.checked)}: OpenShorts $0 autoalojado o $12/mes alojado, Submagic ${esc(COMPETITORS.submagic.entryPrice)}, Opus Clip ${esc(OPUS.entryPrice)}, Vizard ${esc(COMPETITORS.vizard.entryPrice)} y Klap ${esc(COMPETITORS.klap.entryPrice)}.`,
`Los precios de entrada, comprobados el ${esc(OPUS.checked)}: OpenShorts es gratis (autoalojado, MIT), Submagic ${esc(COMPETITORS.submagic.entryPrice)}, Opus Clip ${esc(OPUS.entryPrice)}, Vizard ${esc(COMPETITORS.vizard.entryPrice)} y Klap ${esc(COMPETITORS.klap.entryPrice)}.`,
'Las herramientas no son equivalentes: Submagic no detecta momentos, Klap no deja ajustar la salida y Vizard espera que edites en su línea de tiempo. Cada comparativa de abajo dice dónde gana de verdad.',
],
cta: {
label: 'Pruébalo',
title: 'Pega un enlace y mira los clips',
body: '20 minutos gratis al mes, sin tarjeta. O autoalojado, gratis para siempre y sin marca de agua.',
body: 'Autoalojado, gratis para siempre y sin marca de agua.',
button: 'Probar gratis',
},
body: `
@ -1736,7 +1700,7 @@ página, no por popularidad de la herramienta.</p>
<table>
<thead><tr><th>Herramienta</th><th>Precio de entrada</th><th>Código abierto</th><th>Autoalojable</th></tr></thead>
<tbody>
<tr><td class="os">OpenShorts</td><td class="os">$0 autoalojado · $12/mes alojado</td><td class="yes">Sí, MIT</td><td class="yes">Sí, Docker</td></tr>
<tr><td class="os">OpenShorts</td><td class="os">$0 autoalojado</td><td class="yes">Sí, MIT</td><td class="yes">Sí, Docker</td></tr>
<tr><td>Submagic</td><td>${esc(COMPETITORS.submagic.entryPrice)}</td><td>No</td><td>No</td></tr>
<tr><td>Opus Clip</td><td>${esc(OPUS.entryPrice)}</td><td>No</td><td>No</td></tr>
<tr><td>Vizard</td><td>${esc(COMPETITORS.vizard.entryPrice)}</td><td>No</td><td>No</td></tr>
@ -1753,7 +1717,7 @@ medidor de ningún tipo, así que un vídeo de 90 minutos cuesta lo mismo que un
${faqBlock([
{
q: '¿Cuál es la alternativa gratuita a Opus Clip?',
a: 'OpenShorts autoalojado: licencia MIT, se ejecuta con Docker en tu máquina, sin marca de agua y sin límite de uso. Solo necesitas una clave de Google Gemini, cuyo plan gratuito cubre 1.500 peticiones al día. Si prefieres no instalar nada, OpenShorts Cloud da 20 minutos al mes con marca de agua y planes de pago desde $12/mes.',
a: 'OpenShorts autoalojado: licencia MIT, se ejecuta con Docker en tu máquina, sin marca de agua y sin límite de uso. Solo necesitas una clave de Google Gemini, cuyo plan gratuito cubre 1.500 peticiones al día.',
},
{
q: '¿Qué herramienta de clipping tiene código abierto?',
@ -1768,7 +1732,7 @@ ${faqBlock([
faq: [
{
q: '¿Cuál es la alternativa gratuita a Opus Clip?',
a: 'OpenShorts autoalojado: MIT, Docker, sin marca de agua y sin límite. Hosted: 20 minutos gratis al mes y planes desde $12/mes.',
a: 'OpenShorts autoalojado: MIT, Docker, sin marca de agua y sin límite.',
},
{
q: '¿Qué herramienta de clipping es de código abierto?',
@ -1798,7 +1762,7 @@ const gtaClips = () => ({
updated: '2026-09-15',
tldr: [
'A GTA 5 stream is four to eight hours of 16:9 gameplay with a webcam box in one corner. OpenShorts reads the whole VOD, picks the moments worth posting out of what was said, and reframes each one so the gameplay keeps its full width and the facecam is enlarged underneath it instead of cropped away.',
'Length is what makes this expensive everywhere else. Tools in this category bill one credit per minute of source you import, so a single eight-hour stream is 480 minutes: more than the 300 minutes a $29/month Opus Clip Pro plan includes (checked 2026-07-27). Self-hosted OpenShorts has no meter at all; the hosted edition starts at $12/month.',
'Length is what makes this expensive everywhere else. Tools in this category bill one credit per minute of source you import, so a single eight-hour stream is 480 minutes: more than the 300 minutes a $29/month Opus Clip Pro plan includes (checked 2026-07-27). OpenShorts has no meter at all.',
'Gameplay with no commentary is handled too, and it is where most clippers stop: when a stream has no usable speech OpenShorts switches by itself to a vision pass where Gemini watches the footage and picks the moments, instead of failing on an empty transcript. The switch is automatic, with one practical ceiling noted below.',
],
body: `
@ -1908,11 +1872,11 @@ fine, and the platforms strike it.</p>
${faqBlock([
{
q: 'How do I make GTA 5 clips for TikTok?',
a: 'Paste the stream VOD link into OpenShorts with the vertical layout set to auto. It transcribes the whole recording, has Gemini pick the 3 to 15 strongest 15 to 60 second moments out of what was said, reframes each one to 9:16 keeping the gameplay full width with your facecam enlarged below it, and burns in word-level subtitles. Clips download or post straight to TikTok, Reels and Shorts.',
a: 'Paste the stream VOD link into OpenShorts with the vertical layout set to auto. It transcribes the whole recording, has Gemini pick the 3 to 15 strongest 15 to 60 second moments out of what was said, reframes each one to 9:16 keeping the gameplay full width with your facecam enlarged below it, and burns in word-level subtitles. Clips download or publish to TikTok, Reels and Shorts through Postiz.',
},
{
q: 'Can it handle a whole eight-hour GTA RP stream?',
a: 'Yes, long sources are the design case. Moment scoring reads the transcript rather than the raw video, so an eight-hour VOD does not degrade selection the way it degrades a frame-by-frame approach. Processing time scales with length: the GPU-backed hosted edition clips about 8 minutes of source in 50 seconds, and self-hosted on CPU it is roughly 5 to 8 minutes of processing per 8 minutes of source.',
a: 'Yes, long sources are the design case. Moment scoring reads the transcript rather than the raw video, so an eight-hour VOD does not degrade selection the way it degrades a frame-by-frame approach. Processing time scales with length: on an NVIDIA GPU it clips about 8 minutes of source in 50 seconds, and on CPU it is roughly 5 to 8 minutes of processing per 8 minutes of source.',
},
{
q: 'Does it keep my facecam in the clip?',
@ -1924,7 +1888,7 @@ ${faqBlock([
},
{
q: 'Is it free for streamers?',
a: 'Self-hosted OpenShorts is free and open source under MIT with no per-minute meter, which is the edition that makes sense when your sources are measured in hours: run it with Docker and bring your own Gemini API key. OpenShorts Cloud covers 20 minutes a month free with a watermark, and paid hosted plans start at $12/month.',
a: 'OpenShorts is free and open source under MIT with no per-minute meter, which is what makes sense when your sources are measured in hours: run it with Docker and bring your own Gemini API key.',
},
])}
@ -1965,7 +1929,7 @@ ${sources([
'Turn a multi-hour GTA 5 or GTA RP stream VOD into vertical 9:16 clips for TikTok, YouTube Shorts and Instagram Reels, keeping the gameplay full width and the facecam visible.',
totalTime: 'PT15M',
supply: [{ '@type': 'HowToSupply', name: 'A GTA 5 stream VOD (link or local file) you have the rights to' }],
tool: [{ '@type': 'HowToTool', name: 'OpenShorts (self-hosted with Docker, or OpenShorts Cloud)' }],
tool: [{ '@type': 'HowToTool', name: 'OpenShorts (self-hosted with Docker)' }],
step: [
{
'@type': 'HowToStep',
@ -2030,7 +1994,7 @@ export function relatedFor(page, all) {
const blurb = {
'/alternatives': 'All four tools compared, with entry pricing.',
'/opus-clip-pricing': 'What a credit is, what the free tier includes, and every plan.',
'/opus-clip-free-alternative': 'The two genuinely free routes, against a watermarked free tier.',
'/opus-clip-free-alternative': 'The free self-hosted route, against a watermarked free tier.',
'/opus-ai': 'What the name refers to, what it does and what it costs.',
'/opus-pro': 'What the $29 tier buys, and when it is the wrong plan.',
'/vizard-ai-video-to-text': 'Transcript, subtitles or clips: which one you are asking for.',

View file

@ -311,9 +311,8 @@ const footer = (_related) => `
<a href="/vizard-ai-video-to-text">Vizard AI video to text</a>
<a href="/submagic-reviews">Submagic review</a>
</div>
<p>OpenShorts self-hosted is free and open source under MIT. OpenShorts Cloud
is the hosted service: 20 free minutes a month, paid plans from $12/month.
Last updated ${esc(SITE.updated)}.</p>
<p>OpenShorts is free and open source under MIT. Run it yourself with Docker
and bring your own Gemini key. Last updated ${esc(SITE.updated)}.</p>
</div></footer>`
/* Product analytics for the static pages.
@ -410,8 +409,8 @@ const ATTRIBUTION = `
const DEFAULT_CTA = {
label: 'Try it',
title: 'Paste a link, get vertical clips',
body: 'Your first video free up to 60 minutes, then 20 free minutes a month, no credit card. Or self-host it free under MIT.',
button: 'Get free clips',
body: 'Free and open source under MIT. Run it with Docker and bring your own Gemini key.',
button: 'Get clips',
}
const ctaBlock = (page) => {

View file

@ -93,9 +93,8 @@ bars. It does not follow faces: that is what the clip generator is for.</p>
<h2>Where the paid product starts</h2>
<p>If what you want is not one transcript or one converted file but a long video
cut into several vertical clips with subtitles and the speaker kept in frame,
that is <a href="/free-ai-clip-generator">the free AI clip generator</a>: 20 free
minutes a month on OpenShorts Cloud, or unlimited if you self-host the MIT
licensed code.</p>
that is <a href="/free-ai-clip-generator">the free AI clip generator</a>: free
and open source under MIT, run it on your own machine with Docker.</p>
`,
faq: [],
})
@ -125,7 +124,7 @@ const transcriptTool = `
</div>
<div id="yt-text" class="transcript" tabindex="0" aria-label="Transcript"></div>
<div class="cta-inline">
<p>Want the best moments of this video as vertical clips with subtitles? OpenShorts cuts it into 3 to 15 shorts. 20 free minutes a month.</p>
<p>Want the best moments of this video as vertical clips with subtitles? OpenShorts cuts it into 3 to 15 shorts, free and self-hosted.</p>
<button type="button" id="yt-clip" class="btn-primary">Turn this video into clips</button>
</div>
</div>

View file

@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Sparkles, Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, History, X, Terminal, Shield, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, ExternalLink, Mail, Loader2, Download, Menu, Lock } from 'lucide-react';
import { Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, X, Terminal, Shield, Image, Globe, RotateCcw, AlertTriangle, KeyRound, ExternalLink, Mail, Loader2, Download, Menu, Lock } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import ResultCard from './components/ResultCard';
@ -7,22 +7,11 @@ import ProcessingAnimation from './components/ProcessingAnimation';
import ThumbnailStudio from './components/ThumbnailStudio';
import ClipEditor from './components/ClipEditor';
import ReframeEditor from './components/ReframeEditor';
import UsageMeter from './components/UsageMeter';
import TopUpModal from './components/TopUpModal';
import WatermarkModal, { watermarkNoticeDismissed } from './components/WatermarkModal';
import { getApiUrl } from './config';
import StarBanner from './components/StarBanner';
import PlanChoiceModal from './components/PlanChoiceModal';
import ClipTutorial from './components/ClipTutorial';
import OnboardingSurvey from './components/OnboardingSurvey';
import TrialUpgradeModal from './components/TrialUpgradeModal';
import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate';
import HistoryTab from './components/HistoryTab';
import ProfileMenu from './components/ProfileMenu';
import Modal from './components/ui/Modal';
import { useAuth } from './contexts/AuthContext';
import { apiFetch, apiJson, QuotaError } from './lib/api';
import { apiFetch } from './lib/api';
import { track } from './lib/analytics';
// Enhanced "Encryption" using XOR + Base64 with a Salt
@ -150,65 +139,13 @@ const UserProfileSelector = ({ channels, postizUrl }) => {
</div>
);
};
/* The job a signed-out visitor started, parked until they come back signed in.
*
* Pressing "get free clips" without a session used to open the login modal and
* drop the work on the floor: the magic link lands on a fresh document, so the
* pasted URL was gone and the highest-intent step in the funnel ended in an
* empty form. The same is true of the Google round trip.
*
* So the request is written down before the redirect and replayed after it.
* localStorage rather than sessionStorage because the magic link usually opens
* in a new tab, and a TTL because a request parked last week is not what the
* user is doing now. File uploads cannot be serialised (a File is not JSON), so
* those are only resumed within the same document, via the in-memory fallback. */
const PENDING_JOB_KEY = 'os_pending_job';
const PENDING_JOB_TTL_MS = 60 * 60 * 1000;
let pendingJobInMemory = null;
function stashPendingJob(data) {
const stamp = Date.now();
const entry = { stamp, data: { ...data, payload: typeof data?.payload === 'string' ? data.payload : null } };
pendingJobInMemory = { stamp, data };
try {
localStorage.setItem(PENDING_JOB_KEY, JSON.stringify(entry));
} catch (_) { /* private mode: the in-memory copy still covers same-document flows */ }
return stamp;
}
function peekPendingJob() {
try {
const raw = localStorage.getItem(PENDING_JOB_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (parsed?.data?.payload && Date.now() - (parsed.stamp || 0) < PENDING_JOB_TTL_MS) {
return parsed;
}
localStorage.removeItem(PENDING_JOB_KEY);
}
} catch (_) { /* ignore */ }
// A File cannot survive a reload; this covers a sign-in that did not reload.
if (pendingJobInMemory && Date.now() - pendingJobInMemory.stamp < PENDING_JOB_TTL_MS) {
return pendingJobInMemory;
}
return null;
}
function clearPendingJob() {
pendingJobInMemory = null;
try {
localStorage.removeItem(PENDING_JOB_KEY);
} catch (_) { /* ignore */ }
}
const formatRetention = (seconds) => {
if (seconds >= 86400) return `${Math.round(seconds / 86400)} day${seconds >= 172800 ? 's' : ''}`;
if (seconds >= 3600) return `${Math.round(seconds / 3600)} hour${seconds >= 7200 ? 's' : ''}`;
return `${Math.max(1, Math.round(seconds / 60))} min`;
};
// Headers the backend uses to resolve a self-host Postiz instance. Managed
// (cloud) installs leave these off and the server falls back to its own env.
// Headers the backend uses to resolve the self-host Postiz instance.
const postizHeaders = (key, url) => {
const headers = {};
if (key) headers['X-Postiz-Key'] = key;
@ -244,29 +181,12 @@ const pollJob = async (jobId) => {
};
function App() {
// Cloud auth/billing session (inert when billing is disabled).
const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe, jobRetentionSeconds, localLlm } = useAuth();
const [showLogin, setShowLogin] = useState(false);
const [showTopUp, setShowTopUp] = useState(false);
// Free plan: "want the watermark off?" once per job, when the clips land.
const [showWmNotice, setShowWmNotice] = useState(false);
const wmNoticedJobRef = useRef(null);
const [showPlanChoice, setShowPlanChoice] = useState(false);
// Self-host config: job retention (retention notice) and whether a local LLM
// backend removes the Gemini-key requirement. Auth/billing is gone.
const { jobRetentionSeconds, localLlm } = useAuth();
const [tutorialPhase, setTutorialPhase] = useState(null); // null | intro | coach | celebrate
const [showTrialUpgrade, setShowTrialUpgrade] = useState(false);
const [topUpInfo, setTopUpInfo] = useState({});
// {processed_minutes, total_minutes} when the running/finished job clips
// only the first part of the source (the quota wall's free offer).
const [partialJob, setPartialJob] = useState(null);
// The free plan's first video, clipped whole past the 20-minute balance.
const [firstVideoJob, setFirstVideoJob] = useState(false);
// {position, ahead, eta_seconds} while the job waits in line, else null.
const [queueInfo, setQueueInfo] = useState(null);
// Why the last job could not start or failed, in plain words (or '').
const [jobError, setJobError] = useState('');
// Durable R2 URLs (per clip index) for the current job — used as a fallback when
// the ephemeral local /videos/ files have been cleaned up (e.g. after a reload).
const [durableClips, setDurableClips] = useState({});
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
// Postiz (self-hosted social publishing) config. The API key is encrypted at
@ -339,12 +259,6 @@ function App() {
const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings
// Mobile only: the full nav lives in a drawer behind the header's menu button.
const [navOpen, setNavOpen] = useState(false);
// Reopened-project state (paid mode): per-clip {index, server_file, active_layers}
// restored from the backend so ResultCards resume editing where they left off.
const [projectState, setProjectState] = useState(null);
// True when the current job was reopened from the library: its source video
// was never persisted, so the session must not fall back to /api/source.
const [noSource, setNoSource] = useState(false);
const [sessionRecovered, setSessionRecovered] = useState(false);
// Clip editor overlay: index of the clip being edited, or null.
@ -369,127 +283,9 @@ function App() {
setIsSyncedPlaying(false);
};
// --- Project persistence (paid mode) ---
// Debounced sync of each clip's browser-only edit state (Remotion layers +
// current server file) to the backend, so a reopened project resumes intact.
const clipStateSync = useRef({ jobId: null, pending: {}, files: {}, timer: null });
// Read by in-flight async chases to notice that the user moved on to another job.
const jobIdRef = useRef(jobId);
useEffect(() => { jobIdRef.current = jobId; }, [jobId]);
const flushClipState = () => {
const s = clipStateSync.current;
if (s.timer) { clearTimeout(s.timer); s.timer = null; }
const entries = Object.entries(s.pending);
if (!s.jobId || entries.length === 0) return;
const clips = entries.map(([i, v]) => ({
index: Number(i),
active_layers: v.activeLayers,
server_file: v.serverVideoFile,
}));
s.pending = {};
apiFetch(`/api/projects/${s.jobId}/state`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clips }),
}).catch(() => {});
};
// One /api/history read, reduced to this job's clips.
const fetchDurableMap = async () => {
const d = await apiJson('/api/history');
const map = {};
for (const v of (d.videos || [])) {
if (v.job_id === jobId && v.clip_index != null) map[v.clip_index] = { url: v.view_url, filename: v.filename };
}
return map;
};
// A server-side edit rewrites the clip's file while the R2 re-archive behind it
// is still in flight (_archive_clip_edit_bg is fire-and-forget), so the durable
// map goes stale and the card falls back to streaming from the API. Re-read the
// map on a backoff until the archived name matches the clip's new file, then it
// can play from R2 again. Gives up quietly: staying on /videos is correct, just
// slower, and is exactly what happens for self-hosted users all the time.
const openUpsell = () => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); };
// The clips just landed on a free account: ask once, per job, whether they
// want the mark off. A beat after the grid renders, so the first thing they
// see is their clips and not a modal over them.
useEffect(() => {
if (status !== 'complete' || plan !== 'free' || !isManaged || !jobId) return;
if (!(results?.clips?.length > 0)) return;
if (wmNoticedJobRef.current === jobId || watermarkNoticeDismissed(jobId)) return;
wmNoticedJobRef.current = jobId;
const t = setTimeout(() => { if (jobIdRef.current === jobId) setShowWmNotice(true); }, 2500);
return () => clearTimeout(t);
}, [status, plan, isManaged, jobId, results?.clips?.length]);
// Paying re-points the clips already on screen at their clean twins (the API
// does it from the Stripe webhook, a few seconds after the plan flips). Chase
// the job result until no served file carries the wm_ prefix, then refresh
// the durable map so the players switch to the clean R2 copies too.
useEffect(() => {
if (!isManaged || !jobId || !plan || plan === 'free') return;
const isMarked = (c) => /\/wm_[^/]*$/.test(c?.video_url || '');
if (!(results?.clips || []).some(isMarked)) return;
let cancelled = false;
(async () => {
for (const delay of [1500, 3000, 6000, 12000, 20000]) {
await new Promise((r) => setTimeout(r, delay));
if (cancelled || jobIdRef.current !== jobId) return;
let data;
try { data = await pollJob(jobId); } catch { continue; }
if (cancelled || jobIdRef.current !== jobId) return;
if (data?.result) setResults(data.result);
if (!(data?.result?.clips || []).some(isMarked)) {
fetchDurableMap().then((m) => { if (!cancelled) setDurableClips(m); }).catch(() => {});
return;
}
}
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [plan, isManaged, jobId]);
const chaseDurableFile = async (index, expectedFile) => {
const forJob = jobId;
for (const delay of [2500, 6000, 15000, 30000]) {
await new Promise((r) => setTimeout(r, delay));
if (jobIdRef.current !== forJob) return;
let map;
try { map = await fetchDurableMap(); } catch { return; }
// A new job started mid-chase: this map describes the old one, so dropping
// it here keeps it from overwriting the new job's URLs.
if (jobIdRef.current !== forJob) return;
setDurableClips(map);
if (map[index]?.filename === expectedFile) return;
}
};
const handleClipStateChange = (index, state) => {
if (!isManaged || !jobId) return;
const s = clipStateSync.current;
if (s.jobId !== jobId) { s.pending = {}; s.files = {}; s.jobId = jobId; }
s.pending[index] = state;
// Cards report on mount too, so only an actual change of server file means an
// edit just landed. The first report per clip is the mount, never a chase.
const files = s.files || (s.files = {});
const file = state?.serverVideoFile;
if (file && files[index] !== file) {
const isMount = files[index] === undefined;
files[index] = file;
if (!isMount) chaseDurableFile(index, file);
}
if (s.timer) clearTimeout(s.timer);
s.timer = setTimeout(flushClipState, 2000);
};
// A recut replaced the clip's server file with a fresh render (burned layers
// reset), so update the results, the reopened-project state and the synced
// per-clip edit state, and let the ResultCard remount from the new file.
// reset), so update the results and let the ResultCard remount from the new file.
const handleClipRerendered = (index, data) => {
const newFile = (data.new_video_url || '').split('/').pop();
setResults((prev) => {
if (!prev?.clips?.[index]) return prev;
const clips = prev.clips.slice();
@ -502,41 +298,6 @@ function App() {
};
return { ...prev, clips };
});
setProjectState((prev) => {
if (!prev?.clips) return prev;
return {
...prev,
clips: prev.clips.map((c) => (c.index === index
? { ...c, server_file: newFile, active_layers: null }
: c)),
};
});
// The old durable R2 object is deleted when the recut is archived, so the
// stale URL would 404 as a fallback; drop it until the next refresh.
setDurableClips((prev) => {
if (!(index in prev)) return prev;
const next = { ...prev };
delete next[index];
return next;
});
handleClipStateChange(index, { activeLayers: null, serverVideoFile: newFile });
};
// Reopen an archived project from the History tab: the backend re-downloads
// its files from R2 into the server's working dir and returns the full state.
const restoreProject = async (projectJobId) => {
const data = await apiJson(`/api/projects/${projectJobId}/restore`, { method: 'POST' });
flushClipState();
setProjectState(data.project_state || null);
setNoSource(true);
setJobId(data.job_id);
setResults(data.result || null);
setLogs(['♻️ Project restored from your library.']);
setLogTimes([Date.now() / 1000]);
setProcessingMedia(null);
setQualityGate(null);
setStatus('complete');
setActiveTab('dashboard');
};
// Apply one subtitle style to every clip of the job, sequentially.
@ -582,7 +343,6 @@ function App() {
}
}
setBulkSub({ running: false, current: total, total, errors });
refreshMe();
// Refresh results so each ResultCard picks up its new subtitled video_url.
try {
const data = await pollJob(jobId);
@ -626,12 +386,9 @@ function App() {
setJobId(session.jobId);
setResults(session.results || null);
// Restore the source preview. Older sessions (or uploads) saved no
// media, so fall back to the backend-served source for this job —
// except for reopened projects, whose source was never persisted.
// media, so fall back to the backend-served source for this job.
if (session.processingMedia) setProcessingMedia(session.processingMedia);
else if (!session.noSource) setProcessingMedia({ type: 'server', payload: `/api/source/${session.jobId}` });
if (session.noSource) setNoSource(true);
if (session.projectState) setProjectState(session.projectState);
else setProcessingMedia({ type: 'server', payload: `/api/source/${session.jobId}` });
if (session.activeTab) setActiveTab(session.activeTab);
// If was processing, resume polling; if complete/error, just show results
setStatus(session.status === 'processing' ? 'processing' : session.status);
@ -662,8 +419,6 @@ function App() {
results,
processingMedia: persistMedia,
activeTab,
noSource,
projectState,
timestamp: Date.now()
};
localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData));
@ -671,7 +426,7 @@ function App() {
// localStorage full or serialization error - ignore
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jobId, status, results, activeTab, noSource, projectState]);
}, [jobId, status, results, activeTab]);
useEffect(() => {
// Gemini key stays plain for backward compatibility with older sessions.
@ -697,53 +452,11 @@ function App() {
}, [elevenLabsKey]);
useEffect(() => {
if ((postizKey || isManaged) && postizChannels.length === 0) {
if (postizKey && postizChannels.length === 0) {
fetchPostizChannels({ silent: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [postizKey, postizUrl, isManaged]);
// For managed users, fetch the durable R2 URLs of the current job's clips. The
// preview player prefers them (free egress, edge-served, and not competing with
// the renders for the API process), and falls back to /videos when the local
// file is newer than the archived one or the signed link fails.
// Kept fresh by chaseDurableFile after each edit and by the completion chase
// below; until either lands, the card just streams from /videos.
useEffect(() => {
if (!isManaged || !jobId || !(results?.clips?.length)) { setDurableClips({}); return; }
let cancelled = false;
fetchDurableMap()
.then((map) => { if (!cancelled) setDurableClips(map); })
.catch(() => {});
return () => { cancelled = true; };
// Keyed on the clip COUNT, not on results: the status poll hands back a new
// results object every couple of seconds while the job runs, and this used to
// re-read the history on every one of them.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManaged, jobId, results?.clips?.length]);
// A job is marked complete BEFORE _archive_managed_job has finished uploading
// (app.py:878), so the read above can land while R2 still has nothing for it and
// every card would stream from the API for the rest of the session. Chase until
// all clips have a durable copy.
useEffect(() => {
const count = results?.clips?.length || 0;
if (!isManaged || !jobId || status !== 'complete' || !count) return;
let cancelled = false;
(async () => {
for (const delay of [0, 3000, 8000, 20000, 40000]) {
if (delay) await new Promise((r) => setTimeout(r, delay));
if (cancelled) return;
let map;
try { map = await fetchDurableMap(); } catch { return; }
if (cancelled) return;
setDurableClips(map);
if (Object.keys(map).length >= count) return;
}
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isManaged, jobId, status, results?.clips?.length]);
}, [postizKey, postizUrl]);
useEffect(() => {
let interval;
@ -758,21 +471,15 @@ function App() {
setResults(data.result);
}
if (data.partial) setPartialJob(data.partial);
setQueueInfo(data.status === 'queued' && data.queue ? data.queue : null);
if (data.status === 'completed') {
setQueueInfo(null);
setStatus('complete');
clearInterval(interval);
refreshMe();
} else if (data.status === 'failed') {
setStatus('error');
const errorMsg = data.error || (data.logs && data.logs.length > 0 ? data.logs[data.logs.length - 1] : "Process failed");
setJobError(readableError(errorMsg));
setLogs(prev => [...prev, "Error: " + errorMsg]);
clearInterval(interval);
refreshMe();
} else {
// Update logs if available
if (data.logs) {
@ -786,13 +493,12 @@ function App() {
}, 2000);
}
return () => clearInterval(interval);
}, [status, jobId, refreshMe]);
}, [status, jobId]);
// silent: background auto-fetch — never alert(), just log. Managed users need
// no local key (the server resolves its own); self-host sends the headers.
// silent: background auto-fetch — never alert(), just log.
const fetchPostizChannels = async ({ silent = false } = {}) => {
if (!postizKey && !isManaged) return;
if (!postizKey) return;
try {
const res = await apiFetch('/api/postiz/integrations', {
headers: postizHeaders(postizKey, postizUrl),
@ -812,19 +518,17 @@ function App() {
}
};
// Hosted is paid-only (no BYOK core). Self-host uses BYOK keys.
// `keysMissing` only covers what clipping itself needs — the Gemini key.
// Publishing is a separate, optional Postiz concern (gated in the publish
// flows instead), so a missing Postiz key never blocks the clip generator.
// A self-hosted server running the moment picker on a local LLM
// (LLM_BASE_URL) does not need a Gemini key for the core pipeline.
// A server running the moment picker on a local LLM (LLM_BASE_URL) does not
// need a Gemini key for the core pipeline.
const geminiOk = !!apiKey || !!localLlm;
const keysMissing = !billingEnabled && !geminiOk;
const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial
const keysMissing = !geminiOk;
// Fresh sign-up: Clip Generator tutorial (AuthContext set os_show_clip_tutorial
// after the auth redirect). QA: #app?tutorial=1. Resume coach if they refreshed
// mid-job. Runs once on mount so a later isSignedIn flip cannot reset intro→coach.
// mid-job. Runs once on mount.
useEffect(() => {
let showTutorial = false;
let resumeCoach = false;
@ -836,13 +540,6 @@ function App() {
if (qa === 'celebrate') { setTutorialPhase('celebrate'); return; }
if (localStorage.getItem('os_show_clip_tutorial') === '1') showTutorial = true;
if (localStorage.getItem('os_clip_tutorial') === 'coach') resumeCoach = true;
// A request parked before the sign-in redirect is about to resume on its
// own: opening the intro ("paste a link and generate") on top of a job
// that is already starting contradicts itself. Skip it for this signup.
if (showTutorial && peekPendingJob()) {
showTutorial = false;
localStorage.removeItem('os_show_clip_tutorial');
}
} catch (_) { /* ignore */ }
if (showTutorial) {
setTutorialPhase('intro');
@ -853,37 +550,17 @@ function App() {
}
}, []);
// Legacy: an older build may still have set os_show_plan_choice. Don't open it
// on top of the tutorial.
useEffect(() => {
if (tutorialPhase) return;
if (!(billingEnabled && isSignedIn)) return;
let showPlans = false;
try { showPlans = localStorage.getItem('os_show_plan_choice') === '1'; } catch (_) { /* ignore */ }
if (showPlans) {
setShowPlanChoice(true);
try { localStorage.removeItem('os_show_plan_choice'); } catch (_) { /* ignore */ }
}
}, [billingEnabled, isSignedIn, tutorialPhase]);
const tutorialLock = tutorialPhase === 'intro' || tutorialPhase === 'coach' || tutorialPhase === 'celebrate';
// Sign-up survey (cloud/onboarding.py): before the tutorial intro, never on
// top of a job that is already running (a parked request resuming, or the
// coach phase) or of the celebration.
const [surveyDone, setSurveyDone] = useState(false);
const showSurvey = billingEnabled && !!me?.onboarding_survey_pending && !surveyDone
&& (tutorialPhase === null || tutorialPhase === 'intro') && status === 'idle';
useEffect(() => {
if (tutorialLock && activeTab !== 'dashboard') setActiveTab('dashboard');
}, [tutorialLock, activeTab]);
// Deep links into a tab (#app?tab=history|settings|thumbnails|dashboard).
// Deep links into a tab (#app?tab=settings|thumbnails|dashboard).
// Read once per hash change, then the query is dropped so a reload does not
// keep forcing the tab.
useEffect(() => {
const DEEP_LINK_TABS = ['history', 'settings', 'thumbnails', 'dashboard'];
const DEEP_LINK_TABS = ['settings', 'thumbnails', 'dashboard'];
const apply = () => {
const hash = window.location.hash || '';
if (!hash.startsWith('#app?')) return;
@ -921,10 +598,6 @@ function App() {
track('ClipTutorialSkipped', { props: { phase: tutorialPhase } });
finishTutorial();
};
// Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio.
const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails'];
const TOOL_NAMES = { dashboard: 'the Clip Generator', thumbnails: 'the YouTube Studio' };
const gateThisTab = needsPlan && INCLUDED_TOOL_TABS.includes(activeTab); // included tool, no plan yet
// Distinct platform identifiers (tiktok/instagram/youtube/…) among the
// connected Postiz channels. Empty means "nothing connected yet".
@ -932,7 +605,9 @@ function App() {
() => [...new Set(postizChannels.map((c) => c.identifier).filter(Boolean))],
[postizChannels],
);
const showSocialNudge = isManaged && !socialNudgeDismissed && connectedSocials.length === 0 && !tutorialLock;
// Prompt to set up publishing once clips land, unless Postiz is already
// configured or the user dismissed the nudge.
const showSocialNudge = !postizKey && !socialNudgeDismissed && connectedSocials.length === 0 && !tutorialLock;
// One Seen event per job, only when the banner actually rendered.
const socialNudgeSeenRef = useRef(null);
@ -944,32 +619,17 @@ function App() {
}, [status, results, showSocialNudge, jobId]);
// Channels are connected inside the Postiz instance itself, so "connect"
// simply opens Postiz; self-host users configure it in Settings.
// simply opens Postiz.
const handleConnectSocials = () => {
window.open(postizUrl || 'https://postiz.pbento.pt', '_blank', 'noopener');
};
// Scheduled posts are inspected in Postiz's own calendar.
const handleOpenCalendar = () => {
window.open((postizUrl || 'https://postiz.pbento.pt').replace(/\/$/, ''), '_blank', 'noopener');
};
const handleProcess = async (data, forceLowQuality = false) => {
// Hosted: must be signed in AND on an active plan/trial. Self-host: BYOK keys.
if (billingEnabled) {
// The billing gate below is unchanged: signed in, then entitled, then the
// processing path. The only new thing is the first branch remembering what
// the visitor asked for before sending them to sign in, so the resume
// effect can hand the exact same request back to this function and let it
// fall through the same gates.
if (!isSignedIn) { stashPendingJob(data); setShowLogin(true); return; }
if (!isManaged) { window.location.hash = '#/pricing'; return; }
} else if (keysMissing) {
// The only gate is the BYOK Gemini key (unless a local LLM handles it).
if (keysMissing) {
setShowKeyModal(true);
return;
}
// Past every gate, so this request is really running: nothing left to resume.
clearPendingJob();
setStatus('processing');
setJobError('');
setLogs(["Starting process..."]);
@ -979,15 +639,10 @@ function App() {
// backend-served source once the job id is known.
setProcessingMedia(data.type === 'thumbnail_session' ? null : data);
setQualityGate(null);
setProjectState(null);
setNoSource(false);
setPartialJob(null);
setFirstVideoJob(false);
try {
let body;
// BYOK sends the Gemini header; managed users rely on the bearer token
// that apiFetch attaches automatically.
// BYOK: send the Gemini header.
const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {};
// Advanced generation controls: only sent when the user set them, so the
@ -1002,9 +657,6 @@ function App() {
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
// 'auto' is the server default, so only a deliberate choice travels.
layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
// Set when the user took the quota wall's "clip the first N minutes"
// offer: the server reserves N minutes and cuts the source to them.
max_minutes: data.maxMinutes || null,
};
if (data.type === 'url') {
@ -1051,48 +703,11 @@ function App() {
}
setJobId(resData.job_id);
setPartialJob(resData.partial || null);
setFirstVideoJob(!!resData.first_video);
// The server clipped past the balance on its own (no wall): the first
// video whole, or the first N minutes of a later one.
if (resData.first_video) track('FirstVideoGrant');
else if (resData.partial && data.maxMinutes == null) {
track('AutoPartial', { props: { processed: resData.partial.processed_minutes, total: resData.partial.total_minutes } });
}
if (data.type === 'thumbnail_session') {
setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` });
}
// Minutes are reserved at job start, not at complete.
refreshMe();
} catch (e) {
if (e instanceof QuotaError) {
setStatus('idle');
refreshMe();
// 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 {
// The wall can offer the first N minutes of this same submission on
// the minutes they have: same data, plus max_minutes.
const partial = e.partialMinutes || 0;
setTopUpInfo({
required: e.minutesRequired,
remaining: e.minutesRemaining,
partialMinutes: partial,
onPartial: partial
? () => {
track('PartialClipChosen', { props: { required: e.minutesRequired, partial } });
setShowTopUp(false);
handleProcess({ ...data, maxMinutes: partial }, forceLowQuality);
}
: null,
});
setShowTopUp(true);
}
return;
}
const reason = readableError(e.message);
setJobError(reason);
setStatus('error');
@ -1100,42 +715,13 @@ function App() {
}
};
// Resume the job the visitor started before signing in. Runs on the render
// that first sees isSignedIn true — after a magic link or a Google round trip,
// i.e. a fresh document — and replays the request through handleProcess, so
// the entitlement gate still decides whether it actually runs: an unentitled
// account lands on #/pricing with the request still parked, and pays for it
// later. `resumedStamp` keeps one parked request from being replayed twice in
// the same document (the pricing redirect would otherwise loop on it).
const handleProcessRef = useRef(null);
const resumedStampRef = useRef(0);
useEffect(() => {
handleProcessRef.current = handleProcess;
});
useEffect(() => {
if (!billingEnabled || !isSignedIn) return;
const pending = peekPendingJob();
if (!pending || pending.stamp === resumedStampRef.current) return;
resumedStampRef.current = pending.stamp;
track('JobResumedAfterSignin', { props: { type: pending.data?.type || 'unknown' } });
handleProcessRef.current(pending.data);
}, [billingEnabled, isSignedIn]);
const handleReset = () => {
// Flush any pending edit-state sync before dropping the project: the clips
// themselves are already archived to R2 as they were edited.
flushClipState();
setStatus('idle');
setJobId(null);
setResults(null);
setLogs([]);
setLogTimes([]);
setProcessingMedia(null);
setProjectState(null);
setNoSource(false);
setPartialJob(null);
setFirstVideoJob(false);
setQueueInfo(null);
setJobError('');
localStorage.removeItem(SESSION_KEY);
};
@ -1148,8 +734,7 @@ function App() {
const navItems = [
{ id: 'dashboard', ord: '01', icon: LayoutDashboard, label: 'Clip Generator', short: 'clips', primary: true },
{ id: 'thumbnails', ord: '02', icon: Image, label: 'YouTube Studio', short: 'studio', primary: true },
...(billingEnabled && isSignedIn ? [{ id: 'history', ord: '03', icon: History, label: 'History', short: 'history' }] : []),
{ id: 'settings', ord: '04', icon: Settings, label: 'Settings', short: 'settings' },
{ id: 'settings', ord: '03', icon: Settings, label: 'Settings', short: 'settings' },
];
const activeNav = navItems.find((n) => n.id === activeTab);
@ -1189,15 +774,6 @@ function App() {
<svg height="14" viewBox="0 0 16 16" version="1.1" width="14" aria-hidden="true" fill="currentColor" className="shrink-0"><path fillRule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
<span className={collapsed ? 'hidden lg:block truncate' : 'truncate'}>open source</span>
</a>
{billingEnabled && (
<a
href="#/pricing"
className="flex items-center gap-2 px-3 py-2 text-xs lowercase text-muted hover:text-ink2 transition-colors"
>
<Sparkles size={14} className="shrink-0" />
<span className={collapsed ? 'hidden lg:block truncate' : 'truncate'}>plans &amp; pricing</span>
</a>
)}
<a
href="mailto:info@openshorts.app"
className="flex items-center gap-2 px-3 py-2 text-xs lowercase text-muted hover:text-ink2 transition-colors"
@ -1399,36 +975,13 @@ function App() {
<UserProfileSelector channels={postizChannels} postizUrl={postizUrl} />
)}
{/* Cloud: minutes meter + account/sign-in. For free users the meter
opens the upgrade modal — otherwise the only path to a plan is
failing against the quota wall. */}
{billingEnabled && isManaged && (
<UsageMeter onClick={() => {
if (plan === 'free') { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }
else { window.location.hash = '#/account'; }
}} />
)}
{billingEnabled && isSignedIn && !isManaged && (
<button onClick={() => setShowPlanChoice(true)}
className="btn-primary px-4 py-2 text-xs">
Choose a plan
</button>
)}
{billingEnabled && !isSignedIn && (
<button onClick={() => setShowLogin(true)}
className="btn-ghost px-4 py-2 text-xs">
Sign in
</button>
)}
{billingEnabled && isSignedIn && <ProfileMenu />}
{/* Hidden below sm: the standing banner underneath already says the
same thing, and two warnings in a 360px header is just noise. */}
{keysMissing && (
<button
onClick={() => (billingEnabled && !isSignedIn ? setShowLogin(true) : goToTab('settings'))}
onClick={() => goToTab('settings')}
className="badge-warn hover:brightness-125 transition-all hidden sm:inline-flex"
title="Configure API keys or choose a plan"
title="Configure your Gemini API key"
>
<AlertTriangle size={12} />
<span className="hidden md:inline">Gemini API Key Missing</span>
@ -1477,9 +1030,6 @@ function App() {
</div>
)}
{/* Included tools (Clip Generator, YouTube Studio): non-blocking trial prompt. */}
{gateThisTab && <TrialGate toolName={TOOL_NAMES[activeTab] || 'this'} />}
{/* Main Workspace */}
<div className="flex-1 overflow-hidden relative">
@ -1488,58 +1038,13 @@ function App() {
<div className="h-full overflow-y-auto p-4 sm:p-8 max-w-2xl mx-auto animate-fade">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-8">
<div>
<p className="eyebrow mb-1.5">04 · SETTINGS</p>
<p className="eyebrow mb-1.5">03 · SETTINGS</p>
<h1 className="font-display lowercase text-2xl text-ink">Settings</h1>
</div>
<div className="flex items-center gap-2 text-xs text-muted mt-1">
<Shield size={12} className="text-ok shrink-0" /> Privacy: keys only live in your browser (sent to backend just to process)
</div>
</div>
{isManaged ? (
<div className="card p-6 mb-2">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-input bg-paper3 flex items-center justify-center shrink-0">
<Shield size={16} className="text-brass" />
</div>
<h2 className="text-base font-medium text-ink lowercase">Included in your plan</h2>
</div>
<span className="badge-ok">Managed</span>
</div>
<p className="text-xs text-muted mb-5 leading-relaxed">
Your plan includes the <strong>Clip Generator</strong> and <strong>YouTube Studio</strong>,
fully managed. Publishing goes through your <strong>Postiz</strong> instance; dubbing uses
your own ElevenLabs key (below).
</p>
<div className="flex flex-wrap gap-2">
<button onClick={handleConnectSocials} className="btn-primary py-2 px-4 text-sm">
<Share2 size={16} /> Connect social accounts
</button>
<button onClick={handleOpenCalendar} className="btn-quiet py-2 px-4 text-sm">
<Calendar size={16} /> Content calendar
</button>
</div>
</div>
) : billingEnabled ? (
<div className="card p-6 mb-2">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-input bg-paper3 flex items-center justify-center shrink-0">
<Sparkles size={16} className="text-brass" />
</div>
<h2 className="text-base font-medium text-ink lowercase">Choose your plan</h2>
</div>
<span className="badge-ok">Free plan available</span>
</div>
<p className="text-xs text-muted mb-5 leading-relaxed">
Generate shorts with zero setup — no API keys needed. Start free with 20 min/month, or go paid from $12/mo. Cancel anytime.
</p>
<button onClick={() => setShowPlanChoice(true)} className="btn-primary py-2 px-4 text-sm">
<Sparkles size={16} /> Choose a plan
</button>
</div>
) : (
<>
<KeyInput onKeySet={setApiKey} savedKey={apiKey} />
<div className="card p-4 sm:p-6 mt-8">
@ -1608,9 +1113,6 @@ function App() {
</div>
</div>
</>
)}
<div className="card p-4 sm:p-6 mt-8">
<div className="flex flex-wrap items-center justify-between gap-2 mb-4">
<div className="flex items-center gap-3">
@ -1670,21 +1172,11 @@ function App() {
</div>
)}
{/* View: History */}
{activeTab === 'history' && (
<div className="h-full overflow-y-auto custom-scrollbar animate-fade">
<div className="max-w-6xl mx-auto p-4 sm:p-6 md:p-8">
<HistoryTab onReopenProject={restoreProject} />
</div>
</div>
)}
{activeTab === 'thumbnails' && (
<ThumbnailStudio
geminiApiKey={apiKey}
postizKey={postizKey}
postizUrl={postizUrl}
managed={isManaged}
onCreateClips={(sessionId) => {
setActiveTab('dashboard');
// The Studio source is the user's own upload, published to their
@ -1743,26 +1235,6 @@ function App() {
</span>
</div>
{/* Waiting in line: say where and for how long, and that paid
plans go first (they do: plan priority in the job queue). */}
{status === 'processing' && queueInfo && (
<div className="mb-4 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm">
<p className="text-ink">
{queueInfo.ahead === 0
? 'You are next in line. Starting in a moment…'
: <>You are <b>#{queueInfo.position}</b> in line · about <b>{Math.max(1, Math.round(queueInfo.eta_seconds / 60))} min</b></>}
</p>
{billingEnabled && !['starter', 'creator', 'pro'].includes(plan) && queueInfo.ahead > 0 && (
<button
onClick={() => { track('QueueUpsellClick', { props: { position: String(queueInfo.position) } }); setShowPlanChoice(true); }}
className="mt-2 text-xs lowercase text-brass hover:underline"
>
paid plans skip the line →
</button>
)}
</div>
)}
{/* Video Preview */}
{processingMedia && (
<ProcessingAnimation
@ -1844,7 +1316,7 @@ function App() {
{results.clips.length} Clips
</span>
)}
{results?.cost_analysis && !isManaged && (
{results?.cost_analysis && (
<span className="readout bg-paper3 px-2.5 py-1 rounded-full" title={`Input: ${results.cost_analysis.input_tokens} | Output: ${results.cost_analysis.output_tokens}`}>
GEMINI · ${results.cost_analysis.total_cost.toFixed(5)}
</span>
@ -1868,42 +1340,9 @@ function App() {
{status === 'complete' && results?.clips?.length > 0 && (
<div className="mb-2 space-y-2">
{/* Partial job: the clips on screen come from the first N
minutes only. Say so, and sell the rest of the video. */}
{partialJob && (
<button
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
>
<span className="text-ink">These clips come from the first {partialJob.processed_minutes} of {partialJob.total_minutes} minutes.</span>{' '}
<span className="text-brass font-medium">Clip the whole video →</span>
</button>
)}
{/* Peak-moment upsell: they just SAW their clips — sell while
they're proud of the result, before asking for stars. */}
{firstVideoJob && !partialJob && (
<button
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
>
<span className="text-ink">Your first video is on us: we clipped all of it.</span>{' '}
<span className="text-muted">That used this month's free minutes.</span>{' '}
<span className="text-brass font-medium">Keep clipping →</span>
</button>
)}
{plan === 'free' && !partialJob && !firstVideoJob && (
<button
onClick={() => { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); }}
className="w-full text-left px-3 py-2.5 rounded-input bg-paper3 border border-brass/40 hover:border-brass text-sm transition-colors"
>
<span className="text-ink">Like these clips?</span>{' '}
<span className="text-muted">Upgrade and these exact clips lose the watermark on the spot, and stay for good.</span>{' '}
<span className="text-brass font-medium">Remove the watermark →</span>
</button>
)}
{/* Distribution nudge at the same peak: clips on screen,
publishing them is one connect away. Hidden once any
network is linked or the user dismisses it. */}
publishing them is one connect away. Hidden once Postiz
is configured or the user dismisses it. */}
{showSocialNudge && (
<div className="w-full flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 px-3 py-2.5 rounded-input bg-paper3 border border-rule text-sm">
<div className="flex items-start gap-3 flex-1 min-w-0">
@ -1944,9 +1383,8 @@ function App() {
</button>
</div>
)}
{/* Self-host only: cloud archives clips to the video library,
here they really are gone once the retention sweep runs. */}
{!billingEnabled && jobRetentionSeconds > 0 && (
{/* Clips really are gone once the retention sweep runs. */}
{jobRetentionSeconds > 0 && (
<div className="px-3 py-2.5 rounded-input bg-paper3 border border-paper3 text-sm">
<span className="text-ink">Clips are kept for {formatRetention(jobRetentionSeconds)}, then deleted.</span>{' '}
<span className="text-muted">Download what you want to keep, or raise JOB_RETENTION_SECONDS in your env.</span>
@ -1966,17 +1404,12 @@ function App() {
jobId={jobId}
onEditClip={(index) => setEditingClip(index)}
onReframeClip={(index) => setReframingClip(index)}
onUpgrade={isManaged ? openUpsell : null}
initialState={projectState?.clips?.find((c) => c.index === i) || null}
onStateChange={handleClipStateChange}
durable={durableClips[i]}
postizKey={postizKey}
postizUrl={postizUrl}
geminiApiKey={apiKey}
elevenLabsKey={elevenLabsKey}
isManaged={isManaged}
connectedPlatforms={postizLoaded ? connectedSocials : null}
onConnectSocials={isManaged ? handleConnectSocials : null}
onConnectSocials={handleConnectSocials}
onPlay={(time) => handleClipPlay(time)}
onPause={handleClipPause}
onBulkSubtitle={handleBulkSubtitles}
@ -2117,9 +1550,7 @@ function App() {
onReframed={handleClipRerendered}
/>
)}
{showLogin && <LoginModal onClose={() => setShowLogin(false)} queued={typeof peekPendingJob()?.data?.payload === 'string'} />}
{showSurvey && <OnboardingSurvey onDone={() => setSurveyDone(true)} />}
{tutorialPhase && !showSurvey && (
{tutorialPhase && (
<ClipTutorial
phase={tutorialPhase}
jobStatus={status}
@ -2129,33 +1560,6 @@ function App() {
onDismissCelebrate={finishTutorial}
/>
)}
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
{showWmNotice && (
<WatermarkModal
source="results"
jobId={jobId}
previewSrc={results?.clips?.[0]?.video_url ? getApiUrl(results.clips[0].video_url) : null}
onUpgrade={openUpsell}
onClose={() => setShowWmNotice(false)}
/>
)}
{showTopUp && (
<TopUpModal
onClose={() => setShowTopUp(false)}
required={topUpInfo.required}
remaining={topUpInfo.remaining}
partialMinutes={topUpInfo.partialMinutes}
onPartial={topUpInfo.onPartial}
context={topUpInfo.context || 'wall'}
/>
)}
{showTrialUpgrade && (
<TrialUpgradeModal
plan={plan}
onActivated={refreshMe}
onClose={() => setShowTrialUpgrade(false)}
/>
)}
</div>
);
}

View file

@ -1,7 +1,5 @@
import React from 'react';
import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors, Link2 } from 'lucide-react';
import PricingSection from './components/PricingSection';
import { useAuth } from './contexts/AuthContext';
import './landing.css';
// 64 deterministic tick heights: gaussian envelope × sine wave (no randomness)
@ -74,12 +72,11 @@ const FAQItem = ({ question, answer, isOpen, onClick }) => (
);
export default function Landing({ onLaunchApp }) {
const { billingEnabled } = useAuth();
const [openFaq, setOpenFaq] = React.useState(null);
const [heroUrl, setHeroUrl] = React.useState('');
// Hand the pasted link to the app: MediaInput picks it up on mount, so the
// user lands with their own video ready instead of on a pricing page.
// user lands with their own video ready instead of an empty state.
const handleHeroSubmit = (e) => {
e.preventDefault();
const url = heroUrl.trim();
@ -153,7 +150,7 @@ export default function Landing({ onLaunchApp }) {
const faqs = [
{
question: "Is OpenShorts really free? What's the catch?",
answer: "There is no catch, but there are two different things on offer. (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. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing if you want it. (2) Hosted at openshorts.app is the same software with the running costs covered: our NVIDIA GPU clips that same 8-minute video in about 50 seconds, the Gemini key is included so there is nothing to create or paste, and your clips are stored and re-openable from any browser. It has a free plan (20 minutes a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you are happy to run it yourself, paid if you would rather it just ran fast. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
answer: "There is no catch. OpenShorts is 100% free and open source under MIT: 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. There is no hosted edition and no paid plan. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing if you want it. So: free if you are happy to run it yourself, and always will be. That is far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
},
{
question: "What is OpenShorts and how does it work?",
@ -189,7 +186,7 @@ export default function Landing({ onLaunchApp }) {
},
{
question: "Can I automate OpenShorts?",
answer: "Yes. OpenShorts exposes a REST API with per-user keys and completion webhooks, so a script or workflow can submit a video URL, wait for processing, and list the clips. Those clips publish to TikTok, Instagram or YouTube through a self-hosted Postiz instance. There is also an importable n8n workflow. Full guide at openshorts.app/automate-shorts-api."
answer: "Yes. OpenShorts exposes a REST API with per-user keys and completion webhooks, so a script or workflow can submit a video URL, wait for processing, and list the clips. Those clips publish to TikTok, Instagram or YouTube through a self-hosted Postiz instance. There is also an importable n8n workflow. Full guide at /automate-shorts-api."
},
{
question: "What are the system requirements to run OpenShorts?",
@ -213,7 +210,6 @@ export default function Landing({ onLaunchApp }) {
<div className="hidden md:flex items-center gap-7 text-sm lowercase text-muted">
<a href="#features" className="hover:text-ink transition-colors">Features</a>
<a href="#how-it-works" className="hover:text-ink transition-colors">How It Works</a>
{billingEnabled && <a href="#pricing" className="hover:text-ink transition-colors">Pricing</a>}
<a href="#comparison" className="hover:text-ink transition-colors">Comparison</a>
<a href="#faq" className="hover:text-ink transition-colors">FAQ</a>
<a href="/tools" className="hover:text-ink transition-colors">Free tools</a>
@ -239,14 +235,14 @@ export default function Landing({ onLaunchApp }) {
<section className="hero-blueprint relative overflow-clip border-b border-rule pt-32 pb-20 px-6">
<div className="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_auto] gap-14 items-center">
<div className="min-w-0">
<p className="eyebrow mb-6">00 · AI Clip Generator · Cloud or Self-Hosted</p>
<p className="eyebrow mb-6">00 · AI Clip Generator · Self-Hosted</p>
<h1 className="hero-h1 mb-6">
the free open source ai <em>clip generator</em>, built to clip what people actually watch.
</h1>
<p className="hero-description text-muted max-w-2xl mb-8 leading-relaxed lowercase">
turn long videos into viral 9:16 shorts. online, in the cloud, zero setup, or self-hosted with docker for free.
turn long videos into viral 9:16 shorts — self-hosted with docker, free under mit.
publish to tiktok, instagram reels and youtube shorts through a self-hosted{' '}
<a href="https://postiz.pbento.pt/" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">postiz</a>{' '}
instance, or wire the rest api into your own pipeline with the{' '}
@ -256,8 +252,7 @@ export default function Landing({ onLaunchApp }) {
</p>
{/* The hero CTA is the product itself: paste a link and land in the
app with it loaded. Sign-in is asked for at generate time, not
before the user has seen anything. */}
app with it loaded. There is no account to create first. */}
<form onSubmit={handleHeroSubmit} className="mb-5">
<div className="hero-input-row flex flex-col sm:flex-row items-stretch gap-3">
<div className="relative flex-1 min-w-0">
@ -278,13 +273,13 @@ export default function Landing({ onLaunchApp }) {
</div>
</form>
{/* Trust line right under the CTA: the objection this removes
(a card) is the whole point of the free plan. */}
{/* Trust line right under the CTA: the software is free, so the
only real trade is hardware and setup time. */}
<div className="flex flex-wrap items-center gap-x-5 gap-y-2 mb-5 text-sm">
<span className="badge-ok whitespace-nowrap">
<Check size={12} /> no credit card required
<Check size={12} /> mit licensed · free forever
</span>
<span className="text-muted lowercase">first video free (up to 60 min) · then 20 min every month</span>
<span className="text-muted lowercase">no watermark · no usage cap · no account</span>
<button
onClick={onLaunchApp}
className="text-ink2 lowercase underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors"
@ -294,7 +289,7 @@ export default function Landing({ onLaunchApp }) {
</div>
<p className="text-sm text-muted lowercase">
paid plans from $12/mo without watermark. prefer to run it yourself?{' '}
self-host it with docker and bring your own keys.{' '}
<a
href="https://github.com/mutonby/openshorts"
target="_blank"
@ -398,39 +393,33 @@ export default function Landing({ onLaunchApp }) {
</div>
</section>
{/* Two ways to use it: free self-host vs paid hosted */}
{/* One product, two self-host paths: Docker image or from source. */}
<section className="py-20 px-6 border-t border-rule">
<div className="max-w-4xl mx-auto">
<SectionHeader eyebrow="02 · Deploy" title="Two ways to use OpenShorts">
The same open source software, running either on our GPU or on your machine.
<SectionHeader eyebrow="02 · Deploy" title="Run it on your own machine">
One self-hosted product, free and open source under MIT — there is no hosted edition and no paid plan.
</SectionHeader>
<div className="grid md:grid-cols-2 gap-6">
<div className="card p-8 flex flex-col border-brass">
<div className="flex flex-wrap items-center gap-3 mb-3">
<Sparkles size={18} className="text-brass" />
<h3 className="font-display text-2xl lowercase text-ink">cloud — openshorts.app</h3>
<span className="badge-brass">Recommended · Free Plan</span>
<h3 className="font-display text-2xl lowercase text-ink">docker — one command</h3>
<span className="badge-brass">Recommended · Free · MIT</span>
</div>
<ul className="space-y-1.5 mb-6 flex-1">
{['Our NVIDIA GPU: an 8-min video in about 50s', 'Gemini key included, nothing to set up', 'Social publishing built in', 'First video free up to 60 min, then 20 min/month, no card'].map((f, i) => (
{['docker compose up starts the whole stack', 'Runs on your machine or your own server', 'Bring your own Gemini key, free tier covers 1,500 requests a day', 'No watermark, no usage cap, no subscription'].map((f, i) => (
<li key={i} className="flex items-center gap-2 text-sm text-muted"><Check size={14} className="text-ok shrink-0" />{f}</li>
))}
</ul>
{billingEnabled ? (
<a href="#pricing" className="btn-primary whitespace-nowrap">
start free <ArrowRight size={16} />
</a>
) : (
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
launch openshorts <ArrowRight size={16} />
</button>
)}
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
launch openshorts <ArrowRight size={16} />
</button>
</div>
<div className="card p-8 flex flex-col">
<div className="flex flex-wrap items-center gap-3 mb-3">
<Github size={18} className="text-muted" />
<h3 className="font-display text-2xl lowercase text-ink">self-hosted — for developers</h3>
<span className="readout border border-rule rounded-full px-2.5 py-1">Free · Docker</span>
<h3 className="font-display text-2xl lowercase text-ink">source — for developers</h3>
<span className="readout border border-rule rounded-full px-2.5 py-1">Free · MIT</span>
</div>
<ul className="space-y-1.5 mb-6 flex-1">
{['Your machine: 5 to 8 min on a typical CPU', 'Bring your own Gemini and ElevenLabs keys', 'You install it, you maintain it, you back it up', 'Free forever, and always will be'].map((f, i) => (
@ -446,23 +435,11 @@ export default function Landing({ onLaunchApp }) {
</div>
</section>
{/* Pricing Section — hosted plans (self-host stays free) */}
{billingEnabled && (
<section id="pricing" className="py-20 px-6 border-t border-rule">
<div className="max-w-6xl mx-auto">
<SectionHeader eyebrow="03 · Pricing" title="Simple, transparent pricing">
Your first video is free, up to 60 minutes. Then 20 free minutes a month — no credit card. Cancel anytime.
</SectionHeader>
<PricingSection onRequireLogin={() => { window.location.hash = '#/pricing'; }} />
</div>
</section>
)}
{/* 3 Tools in 1 Section */}
<section className="py-20 px-6 border-t border-rule">
<div className="max-w-6xl mx-auto">
<SectionHeader eyebrow="04 · Tools" title="3 Free Tools in 1 Platform">
Everything below is included in cloud plans — no keys, no setup.
<SectionHeader eyebrow="03 · Tools" title="3 Free Tools in 1 Platform">
Everything below runs in the self-hosted app — bring your own keys for the AI features.
</SectionHeader>
<div className="grid md:grid-cols-3 gap-5">
<div className="card p-8">
@ -505,7 +482,7 @@ export default function Landing({ onLaunchApp }) {
{/* Features Section */}
<section id="features" className="py-20 px-6 border-t border-rule">
<div className="max-w-6xl mx-auto">
<SectionHeader eyebrow="05 · Features" title="Free AI Clip Generator">
<SectionHeader eyebrow="04 · Features" title="Free AI Clip Generator">
The free open source clip generator. A smart AI video clipper for TikTok, Reels & Shorts.
</SectionHeader>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5">
@ -519,8 +496,8 @@ export default function Landing({ onLaunchApp }) {
{/* API Keys Section */}
<section className="py-20 px-6 border-t border-rule">
<div className="max-w-5xl mx-auto">
<SectionHeader eyebrow="06 · API Keys" title="Self-hosting? Every API has a free tier">
Cloud plans include managed Gemini and Postiz publishing — self-hosters bring their own keys (all with generous free tiers):
<SectionHeader eyebrow="05 · API Keys" title="Self-hosting? Every API has a free tier">
You bring your own keys — Gemini is required, ElevenLabs and Postiz are optional, and each has a generous free tier:
</SectionHeader>
<div className="grid md:grid-cols-3 gap-5">
<div className="card p-6 relative">
@ -557,7 +534,7 @@ export default function Landing({ onLaunchApp }) {
{/* How It Works Section */}
<section id="how-it-works" className="py-20 px-6 border-t border-rule">
<div className="max-w-4xl mx-auto">
<SectionHeader eyebrow="07 · Pipeline" title="How It Works">
<SectionHeader eyebrow="06 · Pipeline" title="How It Works">
From long-form video to viral-ready clips in 5 automated steps.
</SectionHeader>
<div className="space-y-8">
@ -571,7 +548,7 @@ export default function Landing({ onLaunchApp }) {
{/* Tech Stack */}
<section className="py-20 px-6 border-t border-rule">
<div className="max-w-5xl mx-auto">
<SectionHeader eyebrow="08 · Stack" title="Built with Proven Technology">
<SectionHeader eyebrow="07 · Stack" title="Built with Proven Technology">
Industry-leading AI models and open source tools in one pipeline.
</SectionHeader>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
@ -597,8 +574,8 @@ export default function Landing({ onLaunchApp }) {
{/* Comparison Table */}
<section id="comparison" className="py-20 px-6 border-t border-rule">
<div className="max-w-4xl mx-auto">
<SectionHeader eyebrow="09 · Comparison" title="Free Clip Generator vs Paid Alternatives">
Hosted OpenShorts starts at $12/mo — or self-host free. Opus Clip runs $15-228/month, Kapwing $24-79/month.
<SectionHeader eyebrow="08 · Comparison" title="Free Clip Generator vs Paid Alternatives">
OpenShorts is free and open source — you self-host it. Opus Clip runs $15-228/month, Kapwing $24-79/month.
</SectionHeader>
<div className="overflow-x-auto">
<table className="w-full">
@ -636,7 +613,7 @@ export default function Landing({ onLaunchApp }) {
{/* Use Cases */}
<section className="py-20 px-6 border-t border-rule">
<div className="max-w-5xl mx-auto">
<SectionHeader eyebrow="10 · Use Cases" title="Who Uses OpenShorts?">
<SectionHeader eyebrow="09 · Use Cases" title="Who Uses OpenShorts?">
Creators, marketers, and agencies scaling short-form video production.
</SectionHeader>
<div className="grid md:grid-cols-3 gap-5">
@ -675,7 +652,7 @@ export default function Landing({ onLaunchApp }) {
{/* FAQ Section */}
<section id="faq" className="py-20 px-6 border-t border-rule">
<div className="max-w-3xl mx-auto">
<SectionHeader eyebrow="11 · FAQ" title="Frequently Asked Questions">
<SectionHeader eyebrow="10 · FAQ" title="Frequently Asked Questions">
Everything you need to know about OpenShorts, from setup to features.
</SectionHeader>
<div className="divide-y divide-rule border-y border-rule">
@ -696,19 +673,12 @@ export default function Landing({ onLaunchApp }) {
<section className="py-24 px-6 border-t border-rule">
<div className="max-w-3xl mx-auto text-center">
<h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-5">start creating viral videos today.</h2>
<p className="text-muted mb-10 max-w-xl mx-auto leading-relaxed lowercase">first video free (up to 60 min) · then 20 min/month · no credit card — or self-host free with docker.</p>
<p className="text-muted mb-10 max-w-xl mx-auto leading-relaxed lowercase">free and open source under mit · no watermark · no usage cap · self-host with docker.</p>
<div className="flex flex-wrap items-center justify-center gap-4">
{billingEnabled ? (
<a href="#pricing" className="btn-primary whitespace-nowrap">
start free
<ArrowRight size={16} />
</a>
) : (
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
launch openshorts
<ArrowRight size={16} />
</button>
)}
<button onClick={onLaunchApp} className="btn-primary whitespace-nowrap">
launch openshorts
<ArrowRight size={16} />
</button>
<a
href="https://github.com/mutonby/openshorts"
target="_blank"

View file

@ -1,247 +0,0 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Loader2, CreditCard, LogOut, Plus } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import ApiKeysCard from './ApiKeysCard';
import DeleteAccountCard from './DeleteAccountCard';
import InvoicesCard from './InvoicesCard';
import CancelPlanModal from './CancelPlanModal';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
// Mirrors cloud/config.BILLING_ATTENTION_STATES: states where the customer has
// to do something (fix a card, finish a payment) before minutes come back.
const PAYMENT_ISSUE_STATES = ['past_due', 'unpaid', 'incomplete', 'paused'];
// Mirrors cloud/cancellation.CANCELLABLE_STATES.
const CANCELLABLE_STATES = ['active', 'trialing', 'past_due'];
// 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);
const [cancelOpen, setCancelOpen] = 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();
// 'free' is the default plan for any signed-in account, so it does NOT
// mean the checkout landed — keep polling until the webhook writes the
// paid subscription.
const paidPlan = data?.plan && data.plan !== 'free';
if (paidPlan || tries > 15) {
clearInterval(t);
setActivating(false);
// Fire the Subscribed conversion goal. A pending-checkout stash (set in
// PricingSection) carries the plan price, so we can attach real revenue;
// top-ups don't set it, so they never count as a subscription.
if (paidPlan) {
let pending = null;
try { pending = JSON.parse(localStorage.getItem('os_pending_checkout') || 'null'); } catch (_) { /* ignore */ }
if (pending) {
// This Plausible is Community Edition, which has no revenue goals —
// so the price rides along as plain props (value_usd / plan) that CE
// can break the goal down by. The exact MRR still lives in Stripe.
track('Subscribed', {
props: {
plan: pending.plan,
interval: pending.interval,
value_usd: Math.round((pending.amount || 0) / 100),
},
});
try { localStorage.removeItem('os_pending_checkout'); } catch (_) { /* ignore */ }
}
}
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.'); }
}, []);
// The portal no longer cancels, and its "renew" went with that, so undoing
// a scheduled cancel happens here (cloud/cancellation.py).
const resume = useCallback(async () => {
setBusy(true);
try {
await apiJson('/api/billing/resume', { method: 'POST' });
track('SubscriptionResumed', { props: { plan } });
await refreshMe();
} catch (e) { alert(e?.detail || 'Could not resume your subscription.'); }
setBusy(false);
}, [plan, refreshMe]);
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(e?.detail || 'Could not start checkout.'); }
}, []);
if (!me) return <div className="flex justify-center py-16"><Loader2 className="animate-spin text-brass" /></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;
const low = total > 0 && (m.remaining || 0) <= total * 0.2;
return (
<div className="max-w-2xl mx-auto space-y-6">
<div className="flex items-end justify-between gap-4">
<div>
<p className="eyebrow mb-1.5">ACCOUNT</p>
<h2 className="font-display lowercase text-2xl text-ink leading-tight">Your account</h2>
<p className="text-muted text-sm mt-1">{me.user?.email}</p>
</div>
<button onClick={logout} className="btn-quiet shrink-0">
<LogOut size={16} /> Sign out
</button>
</div>
{activating && (
<div className="card px-4 py-3 text-sm text-ink2 flex items-center gap-2 lowercase">
<Loader2 size={16} className="animate-spin text-brass" /> Activating your plan…
</div>
)}
<div className="card p-6">
<div className="flex items-center justify-between gap-4 mb-4">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-ink font-medium capitalize">{plan ? `${plan} plan` : 'No active plan'}</span>
{/* Payment-issue states get the explanatory banner below instead —
showing raw Stripe jargon ("past_due") twice explains nothing. */}
{me.status && me.status !== 'active'
&& !PAYMENT_ISSUE_STATES.includes(me.status) && (
<span className="badge-warn">{me.status}</span>
)}
{me.cancel_at_period_end && (
<span className="badge-warn">cancels at period end</span>
)}
</div>
{/* Any Stripe relationship — live OR broken (past_due, unpaid) — must
keep the portal reachable. A declined card demotes `plan` to free,
so keying this off the plan alone hid the one button that fixes it. */}
{me.has_billing_account ? (
<button onClick={openPortal} disabled={busy} className="btn-ghost px-4 py-2 shrink-0">
<CreditCard size={16} /> Manage billing
</button>
) : (
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary px-4 py-2 shrink-0 text-xs">
Upgrade
</button>
)}
</div>
{/* A bare "past_due" chip explains nothing. Say what happened and what
fixes it — this is the whole reason the account reads as free. */}
{PAYMENT_ISSUE_STATES.includes(me.status) && (
<div className="mb-4 rounded-card border border-warn/40 bg-warn/5 p-3 text-sm text-ink2">
<b className="text-ink">We couldn't charge your card.</b>{' '}
{me.status === 'incomplete'
? 'Your payment was never completed, so the plan never started.'
: 'Your plan is paused and you\'re on free minutes until it goes through.'}{' '}
<button onClick={openPortal} disabled={busy}
className="underline underline-offset-2 hover:text-ink">
Update your card
</button>{' '}
and it resumes right away.
</div>
)}
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted lowercase">Plan minutes</span>
<span className="text-ink2">{fmt1(m.plan_used)} / {fmt1(m.plan_allowance)} used</span>
</div>
<div className="h-1.5 bg-paper3 rounded-full overflow-hidden">
<div className={`h-full transition-all ${low ? 'bg-warn' : 'bg-brass'}`} style={{ width: `${usedPct}%` }} />
</div>
<div className="flex justify-between text-sm pt-1">
<span className="text-muted lowercase">Top-up minutes</span>
<span className="text-ink2">{fmt1(m.topup_remaining)} remaining</span>
</div>
<div className="flex justify-between text-sm pt-2 border-t border-rule">
<span className="text-ink font-medium lowercase">Total remaining</span>
<span className="text-brass font-medium">{fmt1(m.remaining)} min</span>
</div>
</div>
{/* Our own cancel flow (reason + review + retention offer). The portal
cannot cancel (turned off in Stripe), so this is the only way out. */}
{me.has_billing_account && CANCELLABLE_STATES.includes(me.status) && !me.cancel_at_period_end && (
<div className="pt-4 mt-4 border-t border-rule text-right">
<button onClick={() => { track('CancelFlowOpened', { props: { plan } }); setCancelOpen(true); }}
className="text-xs text-muted underline underline-offset-2 hover:text-ink">
Cancel subscription
</button>
</div>
)}
{me.has_billing_account && CANCELLABLE_STATES.includes(me.status) && me.cancel_at_period_end && (
<div className="pt-4 mt-4 border-t border-rule flex items-center justify-between gap-3 text-sm text-ink2">
<span>Your plan ends on {me.period_end ? new Date(me.period_end).toLocaleDateString('en-US', { month: 'long', day: 'numeric' }) : 'the end of the period'}.</span>
<button onClick={resume} disabled={busy} className="btn-ghost px-4 py-2 text-xs shrink-0">
Keep my subscription
</button>
</div>
)}
</div>
{cancelOpen && (
<CancelPlanModal
plan={plan}
periodEnd={me.period_end}
onClose={() => setCancelOpen(false)}
onCanceled={() => { setCancelOpen(false); refreshMe(); }}
/>
)}
{/* Only accounts that ever had a Stripe relationship can have invoices. */}
{me.has_billing_account && <InvoicesCard />}
{topups.length > 0 && (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2"><Plus size={16} className="text-brass" /> Buy more minutes</h3>
<p className="text-muted text-sm mb-4 lowercase">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-rule hover:border-brass rounded-card p-4 text-left transition-colors disabled:opacity-50">
<div className="text-ink font-medium">+{t.minutes} min</div>
<div className="readout mt-1">
{new Intl.NumberFormat('en-US', { style: 'currency', currency: (t.currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((t.amount || 0) / 100)}
</div>
</button>
))}
</div>
</div>
)}
<ApiKeysCard />
<DeleteAccountCard />
</div>
);
}

View file

@ -1,116 +0,0 @@
import React, { useState, useEffect, useCallback } from 'react';
import { KeyRound, Plus, Trash2, Copy, Check, Loader2 } from 'lucide-react';
import { apiJson } from '../lib/api';
// API keys for programmatic access (MCP clients, scripts, n8n). The raw key is
// returned exactly once by POST /api/keys, so it is surfaced in a one-time
// banner the user must copy before it disappears.
export default function ApiKeysCard() {
const [keys, setKeys] = useState(null);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const [freshKey, setFreshKey] = useState(null); // { key, name } shown once
const [copied, setCopied] = useState(false);
const load = useCallback(() => {
apiJson('/api/keys').then((d) => setKeys(d.keys || [])).catch(() => setKeys([]));
}, []);
useEffect(() => { load(); }, [load]);
const createKey = useCallback(async () => {
setBusy(true);
try {
const d = await apiJson('/api/keys', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: name.trim() || undefined }),
});
setFreshKey(d);
setCopied(false);
setName('');
load();
} catch (e) { alert(e?.detail || 'Could not create the key.'); }
setBusy(false);
}, [name, load]);
const revoke = useCallback(async (k) => {
if (!window.confirm(`Revoke "${k.name}"? Anything using it stops working immediately.`)) return;
try {
await apiJson(`/api/keys/${k.id}`, { method: 'DELETE' });
load();
} catch (e) { alert(e?.detail || 'Could not revoke the key.'); }
}, [load]);
const copyKey = useCallback(() => {
navigator.clipboard?.writeText(freshKey.key).then(() => setCopied(true)).catch(() => {});
}, [freshKey]);
const active = (keys || []).filter((k) => !k.revoked);
return (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<KeyRound size={16} className="text-brass" /> API keys
</h3>
<p className="text-muted text-sm mb-4">
Keys for CLI clients, scripts and the REST API (see &ldquo;Connect an agent&rdquo; above).
Apps connected through claude.ai or ChatGPT show up here too: revoking a key disconnects
that app. Keys use your plan&apos;s minutes.
</p>
{freshKey && (
<div className="mb-4 rounded-card border border-brass/40 bg-brass/5 p-3 text-sm">
<p className="text-ink mb-2">
<b>Copy your new key now.</b> For security it will never be shown again.
</p>
<div className="flex items-center gap-2">
<code className="readout flex-1 break-all select-all">{freshKey.key}</code>
<button onClick={copyKey} className="btn-ghost px-3 py-1.5 shrink-0">
{copied ? <Check size={14} /> : <Copy size={14} />} {copied ? 'Copied' : 'Copy'}
</button>
</div>
</div>
)}
{keys === null ? (
<div className="flex justify-center py-4"><Loader2 className="animate-spin text-brass" size={18} /></div>
) : (
<>
{active.length > 0 && (
<div className="space-y-2 mb-4">
{active.map((k) => (
<div key={k.id} className="flex items-center justify-between gap-3 border border-rule rounded-card px-3 py-2 text-sm">
<div className="min-w-0">
<span className="text-ink">{k.name}</span>{' '}
<code className="readout">{k.prefix}…</code>
</div>
<div className="flex items-center gap-3 shrink-0">
<span className="text-muted text-xs lowercase">
{k.last_used_at ? `used ${new Date(k.last_used_at).toLocaleDateString()}` : 'never used'}
</span>
<button onClick={() => revoke(k)} title="Revoke key"
className="text-muted hover:text-warn transition-colors">
<Trash2 size={15} />
</button>
</div>
</div>
))}
</div>
)}
<div className="flex gap-2">
<input
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') createKey(); }}
placeholder="Key name (e.g. n8n, claude)"
className="input-field flex-1 text-sm"
maxLength={60}
/>
<button onClick={createKey} disabled={busy} className="btn-ghost px-4 py-2 shrink-0">
{busy ? <Loader2 size={16} className="animate-spin" /> : <Plus size={16} />} Create key
</button>
</div>
</>
)}
</div>
);
}

View file

@ -1,238 +0,0 @@
import React, { useState, useRef, useEffect } from 'react';
import { Loader2, Star } from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import Modal from './ui/Modal';
// Mirrors cloud/cancellation.CANCEL_REASONS. A closed list so churn can be
// counted; the text box under it is where the specifics go.
const REASONS = [
['too_expensive', 'Too expensive'],
['not_using_it', "I'm not using it enough"],
['one_off_project', 'I only needed it for one project'],
['clip_quality', "The clips weren't good enough"],
['missing_feature', 'Missing a feature I need'],
['too_complex', 'Too hard to use'],
['found_alternative', 'I found something better'],
['support', 'Bad experience with support'],
['other', 'Something else'],
];
const DETAIL_PROMPT = {
too_expensive: 'What price would have worked for you?',
clip_quality: 'What was wrong with the clips?',
missing_feature: 'Which feature were you missing?',
found_alternative: 'Which tool are you moving to, and what does it do better?',
too_complex: 'Where did you get stuck?',
support: 'What happened?',
};
const fmtDate = (iso) => {
if (!iso) return 'the end of your billing period';
try {
return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
} catch (_) { return 'the end of your billing period'; }
};
// Cancel flow: reason -> review -> confirm. The cancel only happens on the
// last step, and at period end (backend: cloud/cancellation.py), so every
// "keep my plan" exit leaves the subscription untouched. The last step leads
// with the retention offer when the server says this subscription gets one.
export default function CancelPlanModal({ plan, periodEnd, onClose, onCanceled }) {
const [step, setStep] = useState(0);
const [reason, setReason] = useState('');
const [details, setDetails] = useState('');
const [rating, setRating] = useState(0);
const [hover, setHover] = useState(0);
const [review, setReview] = useState('');
const [publicOk, setPublicOk] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [offer, setOffer] = useState(null);
const [saved, setSaved] = useState(null);
const sending = useRef(false);
// Asked up front so the last step never waits on it; no answer means no offer.
useEffect(() => {
apiJson('/api/billing/retention-offer')
.then((o) => { if (o?.eligible) setOffer(o); })
.catch(() => {});
}, []);
useEffect(() => {
if (step === 2 && offer) track('RetentionOfferShown', { props: { plan, reason } });
}, [step, offer]); // eslint-disable-line react-hooks/exhaustive-deps
const feedback = () => JSON.stringify({
reason,
details: details.trim() || undefined,
rating: rating || undefined,
review: review.trim() || undefined,
review_public_ok: publicOk,
});
const acceptOffer = async () => {
if (sending.current) return;
sending.current = true;
setBusy(true);
setError('');
try {
const out = await apiJson('/api/billing/retention-offer/accept', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: feedback(),
});
track('RetentionOfferAccepted', { props: { plan, reason } });
setSaved(out);
} catch (e) {
setError(e?.detail || 'Could not apply the discount. Please try again or email info@openshorts.app.');
}
sending.current = false;
setBusy(false);
};
const keep = () => {
track('CancelFlowAbandoned', { props: { step, reason: reason || undefined } });
onClose();
};
const submit = async () => {
if (sending.current) return;
sending.current = true;
setBusy(true);
setError('');
try {
await apiJson('/api/billing/cancel', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: feedback(),
});
track('SubscriptionCanceled', { props: { plan, reason, rating: rating || undefined, offered: !!offer } });
onCanceled();
} catch (e) {
setError(e?.detail || 'Could not cancel. Please try again or email info@openshorts.app.');
sending.current = false;
setBusy(false);
}
};
const shown = hover || rating;
const months = offer?.months ? ` for the next ${offer.months} months` : '';
if (saved) {
return (
<Modal isOpen onClose={onCanceled} eyebrow="YOU'RE STAYING" title="Discount applied">
<div className="space-y-4 text-sm text-ink2">
<p>
Thanks for giving us another go. Your plan stays as it is, and your next
{saved.months ? ` ${saved.months}` : ''} invoice{saved.months > 1 ? 's are' : ' is'}{' '}
<b className="text-ink">{saved.percent_off}% off</b>.
</p>
<p>We read every answer you gave us and will work on it.</p>
<div className="flex justify-end pt-1">
<button onClick={onCanceled} className="btn-primary px-4 py-2 text-xs">Done</button>
</div>
</div>
</Modal>
);
}
return (
<Modal isOpen onClose={busy ? undefined : keep} eyebrow={`CANCEL PLAN · ${step + 1}/3`}
title={['Why are you cancelling?', 'How was OpenShorts?',
offer ? 'Before you go' : 'Confirm cancellation'][step]}>
{step === 0 && (
<div className="space-y-4">
<p className="text-sm text-muted">Your answer goes straight to the people building OpenShorts.</p>
<div className="space-y-1.5">
{REASONS.map(([value, label]) => (
<label key={value}
className={`flex items-center gap-2.5 rounded-card border px-3 py-2 text-sm cursor-pointer transition-colors
${reason === value ? 'border-brass text-ink' : 'border-rule text-ink2 hover:border-brass/60'}`}>
<input type="radio" name="cancel-reason" value={value} checked={reason === value}
onChange={() => setReason(value)} />
{label}
</label>
))}
</div>
{reason && (
<label className="block">
<span className="text-sm text-muted">{DETAIL_PROMPT[reason] || 'Anything else we should know?'} (optional)</span>
<textarea value={details} onChange={(e) => setDetails(e.target.value)} maxLength={2000} rows={3}
className="input-field w-full text-sm mt-1" />
</label>
)}
<div className="flex items-center justify-between gap-2 pt-1">
<button onClick={keep} className="btn-quiet">Keep my plan</button>
<button onClick={() => setStep(1)} disabled={!reason} className="btn-ghost px-4 py-2">Continue</button>
</div>
</div>
)}
{step === 1 && (
<div className="space-y-4">
<p className="text-sm text-muted">Rate your experience and leave a short review. It takes ten seconds and helps us more than anything else.</p>
<div className="flex items-center gap-1" onMouseLeave={() => setHover(0)}>
{[1, 2, 3, 4, 5].map((n) => (
<button key={n} type="button" aria-label={`${n} star${n > 1 ? 's' : ''}`}
onClick={() => setRating(n)} onMouseEnter={() => setHover(n)} className="p-1">
<Star size={26} className={n <= shown ? 'text-brass fill-current' : 'text-muted'} />
</button>
))}
</div>
<label className="block">
<span className="text-sm text-muted">Your review</span>
<textarea value={review} onChange={(e) => setReview(e.target.value)} maxLength={2000} rows={4}
placeholder="What worked, what didn't, who you'd recommend it to…"
className="input-field w-full text-sm mt-1" />
</label>
{review.trim() && (
<label className="flex items-start gap-2 text-sm text-ink2 cursor-pointer">
<input type="checkbox" checked={publicOk} onChange={(e) => setPublicOk(e.target.checked)} className="mt-0.5" />
OpenShorts may quote this review publicly (first name only).
</label>
)}
<div className="flex items-center justify-between gap-2 pt-1">
<button onClick={() => setStep(0)} className="btn-quiet">Back</button>
<button onClick={() => setStep(2)} disabled={!rating} className="btn-ghost px-4 py-2">Continue</button>
</div>
</div>
)}
{step === 2 && (
<div className="space-y-4 text-sm text-ink2">
{offer && (
<div className="rounded-card border border-brass bg-brass/5 p-4 space-y-3">
<p className="text-ink">
Stay and get <b>{offer.percent_off}% off{months}</b>. Same plan, same
minutes, half the price.
</p>
<button onClick={acceptOffer} disabled={busy} className="btn-primary px-4 py-2 text-xs">
{busy && <Loader2 size={16} className="animate-spin" />}
Keep my plan with {offer.percent_off}% off
</button>
</div>
)}
<p>
{offer ? 'If you still want to leave, your' : 'Your'}
{' '}{plan ? <b className="text-ink capitalize">{plan}</b> : null} plan stays active until{' '}
<b className="text-ink">{fmtDate(periodEnd)}</b>, with every minute you have left.
You won't be charged again.
</p>
<p>You can undo this from your account page any time before then.</p>
{error && <p className="text-danger">{error}</p>}
<div className="flex items-center justify-between gap-2 pt-1">
<button onClick={keep} disabled={busy}
className={offer ? 'btn-quiet' : 'btn-primary px-4 py-2 text-xs'}>
{offer ? 'Keep my plan at full price' : 'Keep my plan'}
</button>
<button onClick={submit} disabled={busy} className="btn-danger px-4 py-2">
{busy && <Loader2 size={16} className="animate-spin" />}
{busy ? 'Cancelling…' : 'Cancel subscription'}
</button>
</div>
</div>
)}
</Modal>
);
}

View file

@ -5,8 +5,7 @@ import {
PanelLeft, PanelLeftClose, Film,
} from 'lucide-react';
import { getApiUrl } from '../config';
import { apiFetch, apiJson, QuotaError } from '../lib/api';
import { useAuth } from '../contexts/AuthContext';
import { apiFetch, apiJson } from '../lib/api';
// Full-screen clip editor: shows WHICH source segments a clip was cut from,
// lets the user trim/extend/split/reorder them (word-snapped), and re-renders
@ -96,7 +95,6 @@ function editorReducer(state, action) {
}
export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRerendered }) {
const { refreshMe } = useAuth();
const [edl, setEdl] = useState(null);
const [loadError, setLoadError] = useState(null);
const [state, dispatch] = useReducer(editorReducer, { segments: [], selected: 0, past: [], future: [], pendingBase: null });
@ -868,14 +866,8 @@ export default function ClipEditor({ jobId, clipIndex, clipTitle, onClose, onRer
dispatch({ type: 'init', segments: data.recipe.segments.map((s) => ({ ...s })) });
setPreviewUrl(`${getApiUrl(data.new_video_url)}?t=${Date.now()}`);
onRerendered?.(clipIndex, data);
refreshMe();
} catch (e) {
if (e instanceof QuotaError) {
refreshMe();
setRenderError(`not enough minutes left (needs ${e.minutesRequired ?? '?'}, ${e.minutesRemaining ?? 0} remaining)`);
} else {
setRenderError(e.message || 're-render failed');
}
setRenderError(e.message || 're-render failed');
} finally {
setRendering(false);
}

View file

@ -1,150 +0,0 @@
import React, { useState, useRef, useCallback } from 'react';
import { Trash2, AlertTriangle, Loader2 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
// Mirrors cloud/account.DELETION_REASONS. A closed list rather than a text
// box, because the answer is stored in a record that outlives the account and
// free text is how personal data gets into one by accident.
const REASONS = [
['too_expensive', 'Too expensive'],
['not_using_it', "I'm not using it"],
['clip_quality', "The clips weren't good enough"],
['missing_feature', 'Missing a feature I need'],
['found_alternative', 'I found something better'],
['privacy', 'Privacy concerns'],
['other', 'Something else'],
];
// GDPR Art. 17 erasure, self-service (backend: cloud/account.py). The privacy
// policy tells users they can delete their account from the dashboard, so this
// has to be findable — but it is also irreversible, hence: collapsed by
// default, an itemised list of what actually goes, and typing the account email
// as the confirmation step (there is no password to re-enter; sign-in is a
// magic link).
export default function DeleteAccountCard() {
const { me, logout } = useAuth();
const [open, setOpen] = useState(false);
const [confirm, setConfirm] = useState('');
const [reason, setReason] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
// setBusy only disables the button on the next render, which a fast double
// click beats. The server survives a duplicate call, but each one re-runs a
// Stripe cancel and an R2 prefix delete for nothing.
const sending = useRef(false);
const email = me?.user?.email || '';
// `!!email` matters: without it an account page rendered before /api/me
// resolves would treat an empty box as a match and arm the delete button.
const matches = !!email && confirm.trim().toLowerCase() === email.toLowerCase();
const remove = useCallback(async () => {
if (sending.current) return;
sending.current = true;
setBusy(true);
setError('');
try {
await apiJson('/api/account', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ confirm_email: confirm.trim(), reason: reason || undefined }),
});
// The session token now points at nothing. Drop it before navigating, or
// the landing page spends a request discovering that for itself. The
// funnel flags go too: they are the only reason a re-signup with the same
// address would behave like a returning user rather than a fresh one.
logout();
try {
localStorage.removeItem('os_socials_prompted');
localStorage.removeItem('os_pending_checkout');
} catch (_) { /* ignore */ }
window.location.hash = '#/deleted';
window.location.reload();
} catch (e) {
setError(e?.detail || 'Could not delete your account. Please try again or email info@openshorts.app.');
sending.current = false;
setBusy(false);
}
}, [confirm, reason, logout]);
return (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<Trash2 size={16} className="text-danger" /> Delete account
</h3>
<p className="text-muted text-sm">
Close your OpenShorts account and erase everything we hold about you. This
cannot be undone.
</p>
{!open ? (
<button onClick={() => setOpen(true)} className="btn-danger px-4 py-2 mt-4">
<Trash2 size={16} /> Delete my account
</button>
) : (
<div className="mt-4 space-y-4">
<div className="rounded-card border border-danger/40 bg-danger/5 p-3 text-sm text-ink2">
<p className="flex items-start gap-2 text-ink">
<AlertTriangle size={16} className="text-danger shrink-0 mt-0.5" />
<b>This is permanent. There is no recovery.</b>
</p>
<p className="mt-2">Deleted immediately:</p>
<ul className="list-disc pl-5 mt-1 space-y-0.5">
<li>your account and sign-in</li>
<li>every project, clip and transcript, here and in our storage</li>
<li>your API keys, so anything using them stops working</li>
<li>the link to any social accounts you connected</li>
</ul>
<p className="mt-2">
Any active subscription is cancelled as part of this. We keep your
invoices for six years because Spanish law requires it, plus a
one-way hash of your email address, instead of the address, as
proof the deletion happened.
</p>
</div>
<label className="block">
<span className="text-sm text-muted lowercase">Why are you leaving? (optional)</span>
<select
value={reason}
onChange={(e) => setReason(e.target.value)}
className="input-field w-full text-sm mt-1"
>
<option value="">Prefer not to say</option>
{REASONS.map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
</label>
<label className="block">
<span className="text-sm text-muted">
Type <b className="text-ink">{email}</b> to confirm
</span>
<input
value={confirm}
onChange={(e) => { setConfirm(e.target.value); setError(''); }}
autoComplete="off"
spellCheck={false}
className="input-field w-full text-sm mt-1"
/>
</label>
{error && <p className="text-sm text-danger">{error}</p>}
<div className="flex items-center gap-2">
<button onClick={remove} disabled={!matches || busy} className="btn-danger px-4 py-2">
{busy ? <Loader2 size={16} className="animate-spin" /> : <Trash2 size={16} />}
{busy ? 'Deleting…' : 'Permanently delete my account'}
</button>
<button onClick={() => { setOpen(false); setConfirm(''); setError(''); }}
disabled={busy} className="btn-quiet">
Cancel
</button>
</div>
</div>
)}
</div>
);
}

View file

@ -1,126 +0,0 @@
import React, { useState, useEffect, useMemo } from 'react';
import { Loader2, Download, Film, FolderOpen } from 'lucide-react';
import { apiJson } from '../lib/api';
// The signed-in user's saved video library (stored in R2). Private, signed links.
// Videos are grouped by project (job); re-openable projects get a "reopen"
// action that restores the whole job for further editing in the Clip Generator.
export default function HistoryTab({ onReopenProject }) {
const [videos, setVideos] = useState(null);
const [projects, setProjects] = useState({});
const [reopening, setReopening] = useState(null);
const [reopenError, setReopenError] = useState('');
const [error, setError] = useState('');
useEffect(() => {
apiJson('/api/history')
.then((d) => setVideos(d.videos || []))
.catch(() => setError('Could not load your library.'));
apiJson('/api/projects')
.then((d) => {
const map = {};
for (const p of d.projects || []) map[p.job_id] = p;
setProjects(map);
})
.catch(() => {});
}, []);
// Group videos by job, preserving the newest-first order of /api/history.
const groups = useMemo(() => {
const byJob = new Map();
for (const v of videos || []) {
const key = v.job_id || v.id;
if (!byJob.has(key)) byJob.set(key, []);
byJob.get(key).push(v);
}
return [...byJob.entries()];
}, [videos]);
const handleReopen = async (jobId) => {
if (!onReopenProject || reopening) return;
setReopening(jobId);
setReopenError('');
try {
await onReopenProject(jobId);
} catch (e) {
setReopenError('Could not reopen this project. Please try again.');
setReopening(null);
}
};
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-brass" /></div>;
}
return (
<div className="h-full overflow-y-auto p-8 max-w-5xl mx-auto animate-fade">
<p className="eyebrow mb-1.5">03 · HISTORY</p>
<h1 className="font-display lowercase text-2xl text-ink mb-2">Your library</h1>
<p className="text-muted text-sm mb-8 lowercase">
All the shorts you've generated, saved while your plan is active. Kept for 7 days after your plan ends. Reopen a project to keep editing its clips.
</p>
{error && <p className="text-danger text-sm">{error}</p>}
{reopenError && <p className="text-danger text-sm mb-4">{reopenError}</p>}
{videos && videos.length === 0 && (
<div className="text-center py-20 text-muted">
<Film size={40} className="mx-auto mb-4 text-muted" />
<p className="lowercase">No videos yet. Generate your first short from the Clip Generator.</p>
</div>
)}
<div className="space-y-10">
{groups.map(([jobId, vids]) => {
const project = projects[jobId];
return (
<section key={jobId}>
<div className="flex flex-wrap items-center justify-between gap-3 mb-4 pb-2 border-b border-rule">
<div className="min-w-0">
<p className="text-sm text-ink font-medium truncate" title={project?.title || vids[0]?.title}>
{project?.title || vids[0]?.title || 'Project'}
</p>
<p className="readout mt-0.5">
{fmtDate(vids[0]?.created_at)} · {vids.length} clip{vids.length === 1 ? '' : 's'}
</p>
</div>
{project && onReopenProject && (
<button
onClick={() => handleReopen(jobId)}
disabled={!!reopening}
className="btn-ghost px-3 py-2 text-xs shrink-0"
title="Restore this project in the Clip Generator to keep editing subtitles, hooks, effects and dubbing"
>
{reopening === jobId
? <><Loader2 size={14} className="animate-spin" /> reopening…</>
: <><FolderOpen size={14} /> reopen project</>}
</button>
)}
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-5">
{vids.map((v) => (
<div key={v.id} className="card card-hover 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 text-ink font-medium line-clamp-2 mb-1" title={v.title}>{v.title || 'Short'}</p>
<div className="flex items-center justify-between">
<span className="readout">{fmtDate(v.created_at)}</span>
<a href={v.download_url} className="text-micro font-mono uppercase text-brass hover:text-ink flex items-center gap-1 transition-colors" title="Download">
<Download size={14} /> Download
</a>
</div>
</div>
</div>
))}
</div>
</section>
);
})}
</div>
</div>
);
}

View file

@ -1,92 +0,0 @@
import React, { useState, useEffect } from 'react';
import { FileText, ExternalLink, Download, Loader2 } from 'lucide-react';
import { apiJson } from '../lib/api';
// Legally valid invoices for the account's Stripe charges, issued by
// AgentLedger. The backend hands us pre-signed public links, so "View" and
// "Download" open directly without any extra auth from the browser.
const STATUS_CLASS = {
paid: 'badge-ok',
partially_paid: 'badge-warn',
overdue: 'badge-warn',
};
function formatDate(iso) {
if (!iso) return '';
const [y, m, d] = iso.split('-');
return y && m && d ? `${d}/${m}/${y}` : iso;
}
function formatMoney(amount, currency) {
const n = Number(amount);
if (!Number.isFinite(n)) return `${amount} ${currency}`;
try {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: (currency || 'EUR').toUpperCase() }).format(n);
} catch (_) {
return `${n.toFixed(2)} ${currency}`;
}
}
export default function InvoicesCard() {
const [invoices, setInvoices] = useState(null);
const [error, setError] = useState('');
useEffect(() => {
let cancelled = false;
apiJson('/api/billing/invoices')
.then((d) => { if (!cancelled) setInvoices(Array.isArray(d.invoices) ? d.invoices : []); })
.catch((e) => { if (!cancelled) { setError(e?.detail || 'Could not load invoices.'); setInvoices([]); } });
return () => { cancelled = true; };
}, []);
return (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<FileText size={16} className="text-brass" /> Invoices
</h3>
<p className="text-muted text-sm mb-4 lowercase">
Legally valid invoices for every charge on this account.
</p>
{invoices === null ? (
<div className="flex items-center gap-2 text-muted text-sm py-4">
<Loader2 size={16} className="animate-spin text-brass" /> Loading invoices…
</div>
) : error ? (
<p className="text-sm text-warn">{error}</p>
) : invoices.length === 0 ? (
<p className="text-sm text-muted">
No invoices yet. They appear here after your first payment — give it a few minutes if you just subscribed.
</p>
) : (
<ul className="divide-y divide-rule">
{invoices.map((inv) => (
<li key={inv.doc_number || inv.public_url} className="py-3 flex items-center justify-between gap-3 flex-wrap">
<div className="min-w-0">
<div className="text-ink font-medium font-mono text-xs">{inv.doc_number}</div>
<div className="text-muted text-xs mt-0.5">
{formatDate(inv.doc_date)} · <span className="text-ink2">{formatMoney(inv.total, inv.currency)}</span>
{inv.status && (
<span className={`ml-2 ${STATUS_CLASS[inv.status] || 'badge-warn'}`}>{inv.status.replace(/_/g, ' ')}</span>
)}
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{inv.public_url && (
<a href={inv.public_url} target="_blank" rel="noopener noreferrer" className="btn-ghost px-3 py-1.5 text-xs">
<ExternalLink size={14} /> View
</a>
)}
{inv.pdf_url && (
<a href={inv.pdf_url} target="_blank" rel="noopener noreferrer" className="btn-ghost px-3 py-1.5 text-xs">
<Download size={14} /> PDF
</a>
)}
</div>
</li>
))}
</ul>
)}
</div>
);
}

View file

@ -1,104 +0,0 @@
import React, { useState } from 'react';
import { Mail, Check, Loader2 } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import Modal from './ui/Modal';
// Sign-in modal: magic link (email) + Google OAuth.
// `queued` says the visitor pressed "get free clips" before signing in and the
// request is parked: the work resumes by itself once they are back, and saying
// so is the difference between a sign-in wall and a saved job.
export default function LoginModal({ onClose, queued = false }) {
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 (
<Modal isOpen onClose={onClose} eyebrow="ACCOUNT" title="Sign in to OpenShorts" size="md">
<p className="text-muted text-sm mb-6 lowercase">Access your plan and generate shorts with no API keys.</p>
{queued && (
<div className="flex items-start gap-2 border border-rule2 rounded-input bg-paper2 px-3 py-2 mb-5">
<Check size={14} className="mt-0.5 shrink-0 text-ok" />
<p className="text-xs text-ink2 leading-relaxed m-0">
Your video is saved. Sign in and the clips start on their own — you will not have to paste it again.
</p>
</div>
)}
{sent ? (
<div className="text-center py-6">
<span className="badge-ok px-3 py-1"><Check size={14} /> sent</span>
<p className="text-ink font-medium lowercase mt-4">Check your inbox</p>
<p className="text-muted text-sm mt-1">We sent a sign-in link to <b className="text-ink font-medium">{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-muted" />
<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-danger text-sm">{error}</p>}
<button
type="submit"
disabled={busy || !email.trim()}
className="btn-primary w-full"
>
{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 border-t border-rule" />
<span className="readout">or</span>
<div className="flex-1 border-t border-rule" />
</div>
<button
onClick={loginWithGoogle}
className="btn-ghost w-full"
>
<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>
</>
)}
{/* The account is created by this button, so the terms have to be
reachable from it: a magic-link signup never passes the footer. */}
<p className="text-muted text-xs mt-5 text-center leading-relaxed">
By signing in you agree to our{' '}
<a href="/terms" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-2 hover:text-brass transition-colors">Terms of Service</a>
{' '}and{' '}
<a href="/privacy" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-2 hover:text-brass transition-colors">Privacy Policy</a>.
</p>
</>
)}
</Modal>
);
}

View file

@ -1,111 +0,0 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Plug, Loader2, ShieldCheck } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { getApiUrl } from '../config';
import LoginModal from './LoginModal';
// The OAuth consent screen for MCP clients (claude.ai, ChatGPT, ...). The API
// bounced the client's /oauth/authorize request here because only the
// dashboard holds the session. Approving mints a code server-side and sends
// the browser back to the client; the access token it then receives is an
// ordinary API key, listed (and revocable) in the account page.
function readParams() {
const hash = window.location.hash || '';
const q = hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : '';
return Object.fromEntries(new URLSearchParams(q).entries());
}
export default function OAuthConsent() {
const { isSignedIn, loading, me } = useAuth();
const params = useMemo(readParams, []);
const [client, setClient] = useState(null);
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const [showLogin, setShowLogin] = useState(false);
useEffect(() => {
if (!params.client_id) { setError('This link is missing the client id.'); return; }
fetch(getApiUrl(`/api/oauth/client/${encodeURIComponent(params.client_id)}`))
.then((r) => (r.ok ? r.json() : Promise.reject(new Error('Unknown client'))))
.then(setClient)
.catch(() => setError('This connection request comes from an unknown app. Start again from the app you are connecting.'));
}, [params.client_id]);
useEffect(() => {
if (!loading && !isSignedIn) setShowLogin(true);
}, [loading, isSignedIn]);
const decide = async (allow) => {
setBusy(true);
try {
if (!allow) {
const u = new URL(params.redirect_uri);
u.searchParams.set('error', 'access_denied');
if (params.state) u.searchParams.set('state', params.state);
window.location.replace(u.toString());
return;
}
const d = await apiJson('/api/oauth/authorize', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_id: params.client_id,
redirect_uri: params.redirect_uri,
state: params.state || null,
code_challenge: params.code_challenge,
code_challenge_method: params.code_challenge_method || 'S256',
scope: params.scope || null,
response_type: params.response_type || 'code',
}),
});
window.location.replace(d.redirect);
} catch (e) {
setError(e?.detail || 'Could not complete the connection. Try again from the app.');
setBusy(false);
}
};
const name = client?.client_name || 'an app';
return (
<div className="min-h-screen flex items-center justify-center bg-background px-4">
<div className="card p-8 max-w-md w-full text-center">
<div className="w-12 h-12 rounded-full bg-brass/10 flex items-center justify-center mx-auto mb-4">
<Plug size={20} className="text-brass" />
</div>
<h1 className="font-display lowercase text-2xl text-ink mb-2">Connect {name} to OpenShorts</h1>
{error ? (
<p className="text-warn text-sm">{error}</p>
) : (
<>
<p className="text-muted text-sm mb-6">
<b className="text-ink">{name}</b> wants to clip and publish videos with your account
{me?.email ? <> (<span className="text-ink">{me.email}</span>)</> : null}.
It will use your plan&apos;s minutes and you can disconnect it any time from
Account → API keys.
</p>
<ul className="text-left text-xs text-ink2 space-y-1.5 mb-6">
<li className="flex gap-2"><ShieldCheck size={14} className="text-ok shrink-0 mt-0.5" /> Process videos and read the resulting clips</li>
<li className="flex gap-2"><ShieldCheck size={14} className="text-ok shrink-0 mt-0.5" /> Add subtitles, recut and publish clips you own</li>
<li className="flex gap-2"><ShieldCheck size={14} className="text-ok shrink-0 mt-0.5" /> Nothing else: no billing, no account settings, no key management</li>
</ul>
{loading || !client ? (
<div className="flex justify-center py-2"><Loader2 className="animate-spin text-brass" size={18} /></div>
) : isSignedIn ? (
<div className="flex gap-3">
<button onClick={() => decide(false)} disabled={busy} className="btn-ghost flex-1 py-2.5">Cancel</button>
<button onClick={() => decide(true)} disabled={busy} className="btn-primary flex-1 py-2.5">
{busy ? <Loader2 size={16} className="animate-spin" /> : 'Allow'}
</button>
</div>
) : (
<button onClick={() => setShowLogin(true)} className="btn-primary w-full py-2.5">Sign in to continue</button>
)}
</>
)}
</div>
{showLogin && !isSignedIn && <LoginModal onClose={() => setShowLogin(false)} />}
</div>
);
}

View file

@ -1,131 +0,0 @@
import React, { useState, useRef } from 'react';
import { Loader2 } from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import Modal from './ui/Modal';
// Mirror cloud/onboarding.SOURCES / GOALS / ROLES.
const SOURCES = [
['google', 'Google search'],
['ai_assistant', 'ChatGPT, Claude or another AI'],
['youtube', 'YouTube'],
['tiktok_instagram', 'TikTok or Instagram'],
['x_twitter', 'X (Twitter)'],
['reddit', 'Reddit'],
['github', 'GitHub'],
['friend', 'A friend or colleague'],
['directory', 'Product Hunt or a tools directory'],
['newsletter_blog', 'A newsletter or blog'],
['other', 'Somewhere else'],
];
const GOALS = [
['clips_from_long_videos', 'Clips from my long videos'],
['ai_avatar_videos', 'Clip long videos into shorts'],
['autopilot_posting', 'Publish to my socials'],
['thumbnails', 'YouTube titles & thumbnails'],
['subtitles', 'Subtitles'],
['dubbing', 'Dubbing into other languages'],
['api_agents', 'API / AI agent integration'],
['self_host', 'Self-hosting OpenShorts'],
];
const ROLES = [
['creator', 'Creator / YouTuber'],
['podcaster', 'Podcaster'],
['streamer_gamer', 'Streamer / gamer'],
['agency', 'Agency or freelancer'],
['business_marketing', 'Business / marketing team'],
['educator', 'Educator / coach'],
['developer', 'Developer'],
['other', 'Other'],
];
const chip = (on) => `rounded-full border px-3 py-1.5 text-xs transition-colors ${
on ? 'border-brass bg-brass/10 text-ink' : 'border-rule text-ink2 hover:border-brass/60'}`;
// Asked once, right after sign-up, before the clip tutorial (backend:
// cloud/onboarding.py). One screen, every question optional, skippable: it
// must cost the new user seconds, not their first clip.
export default function OnboardingSurvey({ onDone }) {
const [source, setSource] = useState('');
const [sourceOther, setSourceOther] = useState('');
const [goals, setGoals] = useState([]);
const [role, setRole] = useState('');
const [busy, setBusy] = useState(false);
const sending = useRef(false);
const toggleGoal = (g) => setGoals((cur) => (cur.includes(g) ? cur.filter((x) => x !== g) : [...cur, g]));
const answered = !!(source || goals.length || role);
const send = async (skipped) => {
if (sending.current) return;
sending.current = true;
setBusy(true);
const body = skipped ? { skipped: true } : {
source: source || undefined,
source_other: source === 'other' ? sourceOther.trim() || undefined : undefined,
goals,
role: role || undefined,
};
try {
await apiJson('/api/onboarding/survey', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
});
} catch (_) { /* never block onboarding on the survey */ }
if (!skipped) track('SignupSurveyAnswered', { props: { source: source || undefined, role: role || undefined, goals: goals.join(',') || undefined } });
onDone();
};
return (
<Modal isOpen onClose={busy ? undefined : () => send(true)} eyebrow="WELCOME · 3 QUICK QUESTIONS"
title="Help us build what you need" size="lg"
footer={(
<div className="flex items-center justify-between gap-2">
<button onClick={() => send(true)} disabled={busy} className="btn-quiet">Skip</button>
<button onClick={() => send(false)} disabled={busy || !answered} className="btn-primary px-4 py-2 text-xs">
{busy && <Loader2 size={14} className="animate-spin" />} Continue
</button>
</div>
)}>
<div className="space-y-6">
<section>
<h3 className="text-sm text-ink mb-2">What do you want to make with OpenShorts? <span className="text-muted">(pick any)</span></h3>
<div className="flex flex-wrap gap-2">
{GOALS.map(([value, label]) => (
<button key={value} type="button" onClick={() => toggleGoal(value)} className={chip(goals.includes(value))}>
{label}
</button>
))}
</div>
</section>
<section>
<h3 className="text-sm text-ink mb-2">How did you hear about us?</h3>
<div className="flex flex-wrap gap-2">
{SOURCES.map(([value, label]) => (
<button key={value} type="button" onClick={() => setSource(source === value ? '' : value)} className={chip(source === value)}>
{label}
</button>
))}
</div>
{source === 'other' && (
<input value={sourceOther} onChange={(e) => setSourceOther(e.target.value)} maxLength={120}
placeholder="Where?" className="input-field w-full text-sm mt-2" />
)}
</section>
<section>
<h3 className="text-sm text-ink mb-2">What describes you best?</h3>
<div className="flex flex-wrap gap-2">
{ROLES.map(([value, label]) => (
<button key={value} type="button" onClick={() => setRole(role === value ? '' : value)} className={chip(role === value)}>
{label}
</button>
))}
</div>
</section>
</div>
</Modal>
);
}

View file

@ -1,96 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, ArrowRight } from 'lucide-react';
import { apiJson } from '../lib/api';
import Modal from './ui/Modal';
const PLAN_ORDER = ['starter', 'creator', 'pro'];
const FREE_MINUTES = 20;
const fmt = (a, c) => new Intl.NumberFormat('en-US', { style: 'currency', currency: (c || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((a || 0) / 100);
// Welcome popup after sign-up, instead of dumping the user on the pricing page.
// Free is the default (any Google or permanent-email account qualifies), paid
// plans check out inline.
export default function PlanChoiceModal({ onClose }) {
const [plans, setPlans] = useState([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(null);
useEffect(() => {
apiJson('/api/billing/plans')
.then((d) => setPlans(d.plans || []))
.catch(() => setPlans([]))
.finally(() => setLoading(false));
}, []);
const byPlan = (p) => plans.find((x) => x.plan === p && x.interval === 'month');
const checkout = async (price_id) => {
setBusy(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) { setBusy(null); alert(e?.detail || 'Could not start checkout. Please try again.'); }
};
const startFree = () => {
// A signed-in user with a valid account is already on Free — just start.
onClose();
};
return (
<Modal isOpen onClose={onClose} eyebrow="WELCOME" title="Pick how you want to start" size="lg">
{loading ? (
<div className="flex justify-center py-10"><Loader2 className="animate-spin text-brass" /></div>
) : (
<div className="grid sm:grid-cols-2 gap-4">
{/* Free — the default */}
<div className="card p-5 flex flex-col border-brass">
<div className="flex items-center justify-between mb-1">
<h3 className="font-display lowercase text-lg text-ink">free</h3>
<span className="badge-ok">$0</span>
</div>
<p className="text-muted text-xs mb-3 lowercase">try it on your own videos</p>
<ul className="space-y-1.5 text-sm text-ink2 mb-4 flex-1">
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>{FREE_MINUTES} min</b> / month</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span>No credit card</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-muted shrink-0 mt-0.5" /> <span className="text-muted">Watermark · clips kept 7 days</span></li>
</ul>
<button onClick={startFree} className="w-full btn-primary text-sm">
Start free <ArrowRight size={15} />
</button>
<p className="text-center text-[11px] text-muted mt-2 lowercase">no card · start clipping now</p>
</div>
{/* Paid — compact list */}
<div className="card p-5 flex flex-col">
<div className="flex items-center justify-between mb-1">
<h3 className="font-display lowercase text-lg text-ink">paid plans</h3>
<Zap size={16} className="text-brass" />
</div>
<p className="text-muted text-xs mb-3 lowercase">no watermark · more minutes · durable library</p>
<div className="space-y-2 flex-1">
{PLAN_ORDER.map((p) => {
const e = byPlan(p);
if (!e) return null;
return (
<button key={p} onClick={() => checkout(e.price_id)} disabled={busy === e.price_id}
className="w-full flex items-center justify-between border border-rule hover:border-brass rounded-input px-3 py-2 text-left transition-colors disabled:opacity-50">
<span className="text-sm text-ink capitalize">{p} <span className="text-muted">· {e.minutes} min</span></span>
<span className="readout">{busy === e.price_id ? '…' : `${fmt(e.amount, e.currency)}/mo`}</span>
</button>
);
})}
</div>
<button onClick={() => { onClose(); window.location.hash = '#/pricing'; }}
className="text-center text-[11px] text-muted mt-3 lowercase hover:text-ink transition-colors">
see full pricing & yearly →
</button>
</div>
</div>
)}
</Modal>
);
}

View file

@ -1,319 +0,0 @@
import React, { useState } from 'react';
import { ArrowDown, ArrowRight, Check, ChevronDown, Github, MoveRight, Cpu, KeyRound, Send, Server, HardDrive } from 'lucide-react';
import PricingSection from './PricingSection';
// The honest hosted-vs-self-hosted trade-off. The software is identical and open
// source either way, so the plans have to earn their price on hardware, keys and
// setup rather than on features. Timings are measured on our own pipeline: an
// 8-minute input takes ~50s on the server GPU and 5-8 min on CPU.
// The landing page carries its own shorter version of this (Landing.jsx "Two ways
// to use OpenShorts"); this detailed table is only for the standalone #/pricing.
const HOSTED_VS_SELF = [
{
icon: Cpu,
label: 'Speed',
hosted: 'An 8-minute video is clipped in about 50 seconds on our NVIDIA GPU.',
self: '5 to 8 minutes for the same video on a typical CPU, unless you own a CUDA GPU.',
},
{
icon: KeyRound,
label: 'API keys',
hosted: 'The Gemini key is included. Nothing to create, paste or top up.',
self: 'You create and pay for your own Gemini key, plus ElevenLabs for dubbing.',
},
{
icon: Send,
label: 'Auto-posting',
hosted: 'Clips publish to TikTok, Instagram Reels and YouTube Shorts through Postiz.',
self: 'You run your own Postiz instance and connect the credentials there.',
},
{
icon: Server,
label: 'Setup',
hosted: 'Sign in and paste a link. Nothing to install.',
self: 'Docker, 8GB+ RAM and a few GB of model downloads on the first run.',
},
{
icon: HardDrive,
label: 'Storage',
hosted: 'Clips are hosted for you and re-open in any browser.',
self: 'Your own disk and your own backups.',
},
];
// Billing / value questions reused verbatim from Landing.jsx faqs
const FAQS = [
{
question: "Is OpenShorts really free? What's the catch?",
answer: "There is no catch, but there are two different things on offer. (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. What it costs you is hardware and time. On a typical CPU an 8-minute video takes 5 to 8 minutes to process, and you need your own Google Gemini key (required, free tier is 1,500 requests/day), plus ElevenLabs for dubbing if you want it. (2) Hosted at openshorts.app is the same software with the running costs covered: our NVIDIA GPU clips that same 8-minute video in about 50 seconds, the Gemini key is included so there is nothing to create or paste, and your clips are stored and re-openable from any browser. It has a free plan (20 minutes a month, watermark, no credit card) and paid plans from $12/mo for 100 minutes without watermark. So: free if you are happy to run it yourself, paid if you would rather it just ran fast. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)."
},
{
question: "How does OpenShorts compare to Opus Clip?",
answer: "OpenShorts is a free, self-hosted alternative to Opus Clip. Both offer AI viral moment detection and smart vertical cropping. Key differences: OpenShorts is completely free vs Opus Clip's $15-228/month pricing. OpenShorts runs on your infrastructure (full data privacy) vs cloud-only. OpenShorts uses Google Gemini 3.1 Flash-Lite for AI analysis vs Opus Clip's proprietary model. OpenShorts adds AI voice dubbing in 30+ languages, AI-generated video effects, and hook text overlays. The trade-off is that OpenShorts requires Docker self-hosting, while Opus Clip is a ready-to-use cloud service."
},
{
question: "Can OpenShorts generate YouTube thumbnails and titles for free?",
answer: "Yes. OpenShorts includes a free AI YouTube thumbnail generator, a free AI YouTube title generator, and a free AI YouTube description generator — all powered by Google Gemini 3.1 Flash-Lite. Upload your video and the AI suggests 10 viral title options with an interactive refinement chat. Then it generates multiple thumbnail designs using AI image generation — upload a face photo and background image for personalized results. The studio also auto-generates YouTube descriptions with chapter timestamps and lets you publish directly to YouTube. Everything is 100% free with the Gemini free tier."
},
{
question: "Is there a free open source clip generator?",
answer: "Yes — OpenShorts is a 100% free, open source clip generator. Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), OpenShorts lets you generate unlimited clips with no watermarks, no usage limits, and no subscription fees. It also includes a free AI YouTube thumbnail generator, free AI YouTube title generator, and free AI YouTube description generator — features that other clip generators charge extra for. You self-host it with Docker on your own machine for full privacy and control."
},
{
question: "Does API access cost extra?",
answer: "No. Every plan, including the free one, can create API keys in the account page and use the REST API. Calls draw from the same monthly minutes as the dashboard, so automating with a script or an n8n workflow does not change the price of anything. Clips publish to TikTok, Instagram or YouTube through a self-hosted Postiz instance. Full guide at openshorts.app/automate-shorts-api."
},
{
question: "What are the system requirements to run OpenShorts?",
answer: "OpenShorts runs on any system with Docker installed. The recommended setup is 8GB+ RAM and a modern multi-core CPU. GPU acceleration (NVIDIA CUDA) is optional but speeds up video processing significantly. The Docker Compose setup handles all dependencies automatically — Python 3.11, FFmpeg, YOLOv8, MediaPipe, faster-whisper, and the React dashboard. It works on Linux, macOS, and Windows (via WSL2/Docker Desktop)."
}
];
const TRUST_CARDS = [
{
eyebrow: 'open source',
body: (
<>
The full code is public on{' '}
<a
href="https://github.com/mutonby/openshorts"
target="_blank"
rel="noopener noreferrer"
className="text-ink underline decoration-1 underline-offset-2 hover:text-brass transition-colors"
>
GitHub
</a>
, and self-hosting it stays free forever. What a plan here buys is the GPU, the API keys
and the setup, not the software.
</>
),
},
{
eyebrow: 'no watermarks · no per-clip credits',
body: (
<>
Clips export clean — no watermarks. Plans meter minutes of input video per billing
period, never per-clip credits.
</>
),
},
{
eyebrow: 'cancel anytime',
body: (
<>
Start on the free plan — your first video free up to 60 minutes, then 20 minutes a month, no credit card. Billing for paid
plans runs on Stripe — cancel anytime from your account.
</>
),
},
];
const FAQItem = ({ question, answer, isOpen, onClick }) => (
<div>
<button
onClick={onClick}
className="w-full flex items-center justify-between px-1 py-5 text-left"
>
<span className="text-ink font-medium pr-4">{question}</span>
<ChevronDown
size={18}
className={`text-muted flex-shrink-0 transition-transform ${isOpen ? 'rotate-180' : ''}`}
/>
</button>
{isOpen && (
<div className="px-1 pb-6">
<p className="text-muted text-sm leading-relaxed">{answer}</p>
</div>
)}
</div>
);
const DemoFigure = ({ src, label, className = '', children }) => (
<figure className={`border border-rule rounded-card overflow-hidden bg-paper2 ${className}`}>
<div className="relative">
<video
src={src}
autoPlay
muted
loop
playsInline
preload="metadata"
className="block w-full h-auto"
/>
{children}
</div>
<figcaption className="readout px-3 py-2 border-t border-rule">{label}</figcaption>
</figure>
);
// Conversion-focused paywall / pricing page (#/pricing). Wraps <PricingSection/>.
export default function PricingPage({ onRequireLogin }) {
const [openFaq, setOpenFaq] = useState(null);
const scrollToPlans = () => {
document.getElementById('pricing-plans')?.scrollIntoView({ behavior: 'smooth' });
};
return (
<div className="min-h-screen bg-paper text-ink2 animate-fade">
{/* Header */}
<header className="px-6 pt-20 pb-12">
<div className="max-w-6xl mx-auto text-center">
<p className="eyebrow mb-5">Pricing</p>
<h1 className="font-display lowercase text-ink tracking-tight text-4xl md:text-6xl leading-[1.02] mb-5">
start clipping in minutes.
</h1>
<p className="readout">first video free (up to 60 min) · then 20 min/month · no credit card</p>
</div>
</header>
{/* Demo proof strip */}
<section className="px-6 pb-16">
<div className="max-w-4xl mx-auto">
<div className="grid grid-cols-1 md:grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-5 md:gap-6">
<DemoFigure src="/demo/clip-source.mp4" label="input · 16:9" />
<MoveRight size={20} className="text-brass hidden md:block" aria-hidden="true" />
<ArrowDown size={20} className="text-brass md:hidden justify-self-center" aria-hidden="true" />
<DemoFigure
src="/demo/clip-vertical.mp4"
label="output · 9:16 · tracked"
className="w-44 sm:w-48 justify-self-center md:justify-self-auto"
/>
</div>
<p className="text-center text-xs text-muted lowercase mt-4">
real output from the clip generator — same footage, reframed by AI face tracking.
</p>
</div>
</section>
{/* Pricing grid */}
<section id="pricing-plans" className="px-6 py-16 border-t border-rule scroll-mt-8">
<div className="max-w-6xl mx-auto">
<PricingSection onRequireLogin={onRequireLogin} />
</div>
</section>
{/* Hosted vs self-hosted: same software, different running costs. */}
<section className="px-6 py-16 border-t border-rule">
<div className="max-w-5xl mx-auto">
<div className="mb-8">
<p className="eyebrow mb-3">Hosted or self-hosted</p>
<h2 className="font-display text-3xl md:text-4xl lowercase text-ink tracking-tight">
what you are actually paying for
</h2>
<p className="text-muted text-sm mt-3 max-w-2xl leading-relaxed">
The software is the same and it is open source either way. What a plan buys you is the
hardware, the API keys and the setup, so here is exactly what that means.
</p>
</div>
<div className="hidden md:grid grid-cols-[9rem_1fr_1fr] gap-x-6 pb-2 mb-2 border-b border-rule">
<span />
<span className="eyebrow">Hosted on this site</span>
<span className="eyebrow">Self-hosted</span>
</div>
<div className="divide-y divide-rule border-b border-rule">
{HOSTED_VS_SELF.map(({ icon: Icon, label, hosted, self }) => (
<div key={label} className="py-4 grid gap-2 md:grid-cols-[9rem_1fr_1fr] md:gap-x-6 md:items-start">
<div className="flex items-center gap-2 text-ink2">
<Icon size={15} className="text-muted shrink-0" />
<span className="text-sm font-medium">{label}</span>
</div>
<div>
<span className="eyebrow block mb-1 md:hidden">Hosted on this site</span>
<p className="text-sm text-ink2 leading-relaxed">
<Check size={14} className="text-ok inline-block mr-1.5 -mt-0.5" />
{hosted}
</p>
</div>
<div>
<span className="eyebrow block mb-1 mt-2 md:hidden">Self-hosted</span>
<p className="text-sm text-muted leading-relaxed">{self}</p>
</div>
</div>
))}
</div>
<div className="mt-6 flex flex-col sm:flex-row sm:items-center gap-3 justify-between">
<p className="text-xs text-muted leading-relaxed max-w-xl">
Self-hosting is genuinely free and always will be. It costs you a machine, your own API
keys and the time to keep it running.
</p>
<a
href="https://github.com/mutonby/openshorts"
target="_blank" rel="noopener noreferrer"
className="shrink-0 text-sm text-muted hover:text-ink transition-colors inline-flex items-center gap-1.5"
>
<Github size={15} /> View the source
</a>
</div>
</div>
</section>
{/* Trust strip */}
<section className="px-6 py-16 border-t border-rule">
<div className="max-w-5xl mx-auto grid grid-cols-1 md:grid-cols-3 gap-4">
{TRUST_CARDS.map((card) => (
<div key={card.eyebrow} className="card p-6">
<div className="flex items-center gap-2 mb-3">
<Check size={16} className="text-ok shrink-0" />
<span className="eyebrow">{card.eyebrow}</span>
</div>
<p className="text-sm text-muted leading-relaxed">{card.body}</p>
</div>
))}
</div>
</section>
{/* Mini FAQ */}
<section className="px-6 py-16 border-t border-rule">
<div className="max-w-3xl mx-auto">
<div className="mb-10">
<p className="eyebrow mb-3">Billing · FAQ</p>
<h2 className="font-display text-3xl md:text-4xl lowercase text-ink tracking-tight">
common questions
</h2>
</div>
<div className="divide-y divide-rule border-y border-rule">
{FAQS.map((faq, i) => (
<FAQItem
key={i}
question={faq.question}
answer={faq.answer}
isOpen={openFaq === i}
onClick={() => setOpenFaq(openFaq === i ? null : i)}
/>
))}
</div>
</div>
</section>
{/* Closing statement */}
<section className="px-6 py-24 border-t border-rule">
<div className="max-w-3xl mx-auto text-center">
<h2 className="font-display text-4xl md:text-5xl lowercase text-ink tracking-tight mb-10">
twenty free minutes. every month. no card until you decide.
</h2>
<div className="flex flex-wrap items-center justify-center gap-4">
<button onClick={scrollToPlans} className="btn-primary whitespace-nowrap">
start free
<ArrowRight size={16} />
</button>
<a
href="https://github.com/mutonby/openshorts"
target="_blank"
rel="noopener noreferrer"
className="btn-ghost whitespace-nowrap"
>
<Github size={16} />
view source
</a>
</div>
</div>
</section>
</div>
);
}

View file

@ -1,189 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, Cpu, KeyRound, Send, HardDrive } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import SegmentedControl from './ui/SegmentedControl';
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 FREE_MINUTES = 20;
const fmt = (amount, currency) =>
new Intl.NumberFormat('en-US', { style: 'currency', currency: (currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((amount || 0) / 100);
// Free tier + 3 paid tiers 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 (entry) => {
if (!isSignedIn) { onRequireLogin?.(entry.price_id); return; }
setBusyPrice(entry.price_id);
// `source` segments this surface from the two modals (see TopUpModal), which
// now emit the same three events.
const props = { plan: entry.plan, interval: entry.interval, source: 'pricing' };
track('CheckoutStarted', { props });
// Stash the price so we can attach real revenue to the Subscribed goal when
// the user returns from Stripe (see AccountPage's checkout=success handler).
try {
localStorage.setItem('os_pending_checkout', JSON.stringify({
plan: entry.plan, interval: entry.interval, amount: entry.amount, currency: entry.currency,
}));
} catch (_) { /* ignore storage errors */ }
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id: entry.price_id }),
});
track('CheckoutRedirected', { props });
window.location.href = url;
} catch (e) {
track('CheckoutFailed', { props: { ...props, reason: String(e?.detail || e?.message || 'unknown').slice(0, 120) } });
setBusyPrice(null);
alert(e?.detail || 'Could not start checkout. Please try again.');
}
};
if (loading) {
return <div className="flex justify-center py-16"><Loader2 className="animate-spin text-brass" /></div>;
}
const byPlan = (plan) => plans.find((p) => p.plan === plan && p.interval === interval);
return (
<div className="max-w-5xl mx-auto">
<div className="max-w-xs mx-auto mb-10">
<SegmentedControl
size="sm"
value={interval}
onChange={setInterval}
options={[
{ value: 'month', label: 'Monthly' },
{ value: 'year', label: 'Yearly', hint: '2 months free' },
]}
/>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
{/* Free tier — no card, Google sign-in only */}
<div className="relative card p-6 flex flex-col">
<h3 className="font-display lowercase text-xl text-ink">free</h3>
<p className="text-muted text-sm mb-4 lowercase">Try it on your own videos</p>
<div className="mb-4 flex items-baseline gap-1.5">
<span className="font-display text-4xl text-ink tabular-nums">$0</span>
<span className="readout">/mo</span>
</div>
<ul className="space-y-2 text-sm text-ink2 mb-6 flex-1">
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>{FREE_MINUTES} min</b> of video / month</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span>YouTube URL or upload</span></li>
<li className="flex items-start gap-2"><Cpu size={16} className="text-ok shrink-0 mt-0.5" /> <span>Same <b>GPU rendering</b>, about 50s per 8-min video</span></li>
<li className="flex items-start gap-2"><KeyRound size={16} className="text-ok shrink-0 mt-0.5" /> <span>Gemini key included, no setup</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span>No credit card — Google sign-in</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-muted shrink-0 mt-0.5" /> <span className="text-muted">Watermark · clips kept 7 days</span></li>
</ul>
<button
onClick={() => { if (!isSignedIn) { onRequireLogin?.(null); } else { window.location.hash = ''; } }}
className="w-full btn-ghost"
>
Start free
</button>
<p className="text-center text-xs text-muted mt-2 lowercase">free minutes reset monthly.</p>
</div>
{PLAN_ORDER.map((plan) => {
const entry = byPlan(plan);
if (!entry) return null;
const highlight = plan === HIGHLIGHT;
return (
<div
key={plan}
className={`relative card p-6 flex flex-col ${highlight ? 'border-brass' : ''}`}
>
{highlight && (
<span className="absolute -top-3 left-1/2 -translate-x-1/2 badge-float">
Most popular
</span>
)}
<h3 className="font-display lowercase text-xl text-ink">{plan}</h3>
<p className="text-muted text-sm mb-4 lowercase">{PLAN_BLURB[plan]}</p>
<div className="mb-4 flex items-baseline gap-1.5">
<span className="font-display text-4xl text-ink tabular-nums">{fmt(entry.amount, entry.currency)}</span>
<span className="readout">/{interval === 'month' ? 'mo' : 'yr'}</span>
</div>
<ul className="space-y-2 text-sm text-ink2 mb-6 flex-1">
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>{entry.minutes} min</b> of video / month</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>No watermark</b>, no 7-day clip expiry</span></li>
<li className="flex items-start gap-2"><Cpu size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>GPU rendering</b>, about 50s per 8-min video</span></li>
<li className="flex items-start gap-2"><KeyRound size={16} className="text-ok shrink-0 mt-0.5" /> <span>Gemini key + Postiz publishing included</span></li>
<li className="flex items-start gap-2"><Check size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>REST API access</b> for automations</span></li>
{plan === 'pro' && <li className="flex items-start gap-2"><Zap size={16} className="text-brass shrink-0 mt-0.5" /> <span>Priority processing queue</span></li>}
</ul>
<button
onClick={() => checkout(entry)}
disabled={busyPrice === entry.price_id}
className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`}
>
{busyPrice === entry.price_id ? <Loader2 size={18} className="animate-spin" /> : `Get ${plan}`}
</button>
<p className="text-center text-xs text-muted mt-2 lowercase">billed {interval === 'month' ? 'monthly' : 'yearly'}. 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="card p-6">
<div className="mb-4">
<span className="badge-ok"><Check size={12} /> Included in every plan</span>
</div>
<ul className="space-y-2 text-sm text-ink2">
<li className="flex items-start gap-2"><Cpu size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Our NVIDIA GPU does the rendering.</b> An 8-minute video is clipped in about 50 seconds, instead of the 5 to 8 minutes it takes on a typical CPU.</span></li>
<li className="flex items-start gap-2"><KeyRound size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>The Gemini API key is included.</b> Nothing to sign up for, nothing to paste, no per-request quota of your own to babysit.</span></li>
<li className="flex items-start gap-2"><Send size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Publishing is wired up</b> for TikTok, Instagram Reels and YouTube Shorts through your Postiz instance.</span></li>
<li className="flex items-start gap-2"><HardDrive size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>Clips are stored and served for you</b>, ready to re-open and re-edit from any browser.</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span>Full <b>YouTube Studio</b>: titles, thumbnails and descriptions.</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>REST API for automations.</b> Drive the pipeline from a script or an n8n workflow. API calls use the same minutes, nothing extra to buy. <a href="/automate-shorts-api" className="underline underline-offset-2 hover:text-ink" target="_blank" rel="noopener">Guide</a>.</span></li>
</ul>
<p className="text-xs text-muted mt-3 pt-3 border-t border-rule">
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="card p-6">
<div className="mb-4">
<span className="badge-warn"><Zap size={12} /> Bring your own key</span>
</div>
<p className="text-sm text-muted mb-3 leading-relaxed">
<b className="text-ink2">Voice dubbing</b> uses premium generation from
<b className="text-ink2"> ElevenLabs</b>. Connect your own key for it — you're billed by that
provider directly. Your plan still covers the script &amp; orchestration.
</p>
<p className="text-xs text-muted">Managed credits for these are coming later — no keys needed.</p>
</div>
</div>
<p className="text-center text-muted text-xs mt-8 lowercase">
start free right here, upgrade for more minutes and no watermark, or run it yourself on your own hardware.
</p>
</div>
);
}

View file

@ -1,62 +0,0 @@
import React, { useState, useRef, useEffect } from 'react';
import { 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-paper3 border border-rule hover:border-rule2 text-brass flex items-center justify-center text-sm font-medium transition-colors"
>
{initial}
</button>
{open && (
<div className="card absolute right-0 top-full mt-2 w-56 z-30 shadow-none overflow-hidden animate-fade">
<div className="px-4 py-3 border-b border-rule">
<p className="eyebrow">Signed in as</p>
<p className="text-sm text-ink truncate mt-0.5" 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 lowercase text-brass hover:bg-paper3 transition-colors"
>
<Sparkles size={16} /> Start free
</button>
)}
<button
onClick={() => { setOpen(false); window.location.hash = '#/account'; }}
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm lowercase text-ink2 hover:bg-paper3 transition-colors"
>
<CreditCard size={16} className="text-muted" /> Account &amp; billing
</button>
<button
onClick={() => { setOpen(false); logout(); }}
className="w-full flex items-center gap-3 px-4 py-2.5 text-sm lowercase text-ink2 hover:bg-paper3 transition-colors border-t border-rule"
>
<LogOut size={16} className="text-muted" /> Sign out
</button>
</div>
)}
</div>
);
}

View file

@ -7,8 +7,6 @@ import HookModal from './HookModal';
import TranslateModal from './TranslateModal';
import Modal from './ui/Modal';
import SegmentedControl from './ui/SegmentedControl';
import WatermarkModal, { watermarkNoticeDismissed } from './WatermarkModal';
import { useAuth } from '../contexts/AuthContext';
import { renderInBrowser } from '../lib/renderInBrowser';
const QUIET_BTN = 'group flex flex-col items-center justify-center gap-1 py-2.5 sm:py-2 px-1 rounded-input border border-rule hover:bg-paper3 text-[11px] lowercase text-ink2 whitespace-nowrap transition-colors disabled:opacity-45 disabled:cursor-not-allowed';
@ -35,7 +33,7 @@ function formatDuration(clip) {
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
}
export default function ResultCard({ clip, index, jobId, durable, postizKey, postizUrl, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null, onUpgrade = null }) {
export default function ResultCard({ clip, index, jobId, durable, postizKey, postizUrl, geminiApiKey, elevenLabsKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
const [showModal, setShowModal] = useState(false);
// The "why" line is clamped to two lines so cards in a row stay level;
// when it overflows, a hover (desktop) or tap (touch) shows the whole
@ -53,8 +51,6 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
}, [clip.why]);
const [showDescModal, setShowDescModal] = useState(false);
const [showSubtitleModal, setShowSubtitleModal] = useState(false);
const [showWatermarkModal, setShowWatermarkModal] = useState(false);
const { plan } = useAuth();
const videoRef = React.useRef(null);
// Pristine base clip (no burned subtitles/hook), stable regardless of how
// clip.video_url mutates after server edits. Used as the compositing base
@ -144,8 +140,8 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
const [resolution, setResolution] = useState(null);
// Adopt the durable copy only while it matches the current server file, and
// pin the first signed URL seen for that file: /api/history mints a fresh
// signature on every call, and swapping src mid-playback restarts the video.
// pin the first signed URL seen for that file: the durable URL is re-signed
// on every fetch, and swapping src mid-playback restarts the video.
useEffect(() => {
if (durable?.url && durable.filename && durable.filename === serverVideoFile && !hasPlayed) {
setDurableSrc((prev) => prev || durable.url);
@ -298,7 +294,7 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
// Managed (paid) users get the Gemini key resolved server-side;
// only BYOK/self-host needs a local key.
if (!apiKey && !isManaged) {
if (!apiKey) {
throw new Error("Gemini API Key is missing. Please set it in Settings.");
}
const geminiHeaders = apiKey ? { 'X-Gemini-Key': apiKey } : {};
@ -662,8 +658,8 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
}
};
// Managed (cloud plan/trial) users post with the server-side key — no BYOK needed
const canPost = isManaged || !!postizKey;
// Publishing needs the Postiz key; clipping does not.
const canPost = !!postizKey;
const handlePost = async () => {
if (!canPost) {
@ -772,7 +768,7 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
return;
}
// Local /videos/ file gone (e.g. cleaned up after a reload) →
// fall back to the durable R2 copy for managed users. If the
// fall back to the durable copy if one is available. If the
// durable URL hasn't loaded yet, the effect above retries.
if (durable?.url && currentVideoUrl !== durable.url) setCurrentVideoUrl(durable.url);
else setVideoErrored(true);
@ -980,16 +976,7 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
<Share2 size={16} className="shrink-0" /> post
</button>
<button
onClick={(e) => {
e.preventDefault();
// Free clips are watermarked — surface the upsell once
// before the first download, then get out of the way.
if (plan === 'free' && !watermarkNoticeDismissed(jobId)) {
setShowWatermarkModal(true);
return;
}
downloadClip();
}}
onClick={downloadClip}
className={`${QUIET_BTN}${onEditClip ? ' col-span-2' : ''}`}
>
<Download size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
@ -1196,16 +1183,6 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
hasApiKey={!!elevenLabsKey}
/>
{showWatermarkModal && (
<WatermarkModal
source="download"
jobId={jobId}
onUpgrade={onUpgrade}
onClose={() => setShowWatermarkModal(false)}
onContinue={downloadClip}
/>
)}
</div>
);
}

View file

@ -70,11 +70,10 @@ function DragDropZone({ label, accept, onFile, file, onClear, icon }) {
);
}
export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, managed = false, onCreateClips = null }) {
// 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.
export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, onCreateClips = null }) {
// BYOK: the Gemini key always travels as a header.
const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {};
const needsKey = !geminiApiKey && !managed;
const needsKey = !geminiApiKey;
// Step management
const [step, setStep] = useState(0);
const [mode, setMode] = useState(null); // 'video' or 'manual'
@ -376,7 +375,7 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, ma
// --- Publish to YouTube ---
const handlePublish = async () => {
if (!managed && !postizKey) return alert('Please configure your Postiz base URL and API key in Settings first.');
if (!postizKey) return alert('Please configure your Postiz base URL and API key in Settings first.');
const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('No title selected.');
if (!selectedThumbnail) return alert('Please select a thumbnail first.');
@ -494,7 +493,7 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, ma
<StepIndicator steps={STEPS} current={step} />
</div>
{/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */}
{/* Gemini API Key Warning */}
{needsKey && (
<div className="mb-6 p-5 bg-warn/10 rounded-card flex items-start gap-3">
<AlertCircle size={18} className="text-warn shrink-0 mt-0.5" />
@ -1139,7 +1138,7 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, ma
</div>
{/* Publish Button */}
{(!managed && !postizKey) ? (
{!postizKey ? (
<div className="glass-panel p-6 space-y-3">
<div className="flex items-center gap-2 text-warn">
<AlertCircle size={16} />

View file

@ -1,226 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Loader2, Check, Zap, Clock } from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import Modal from './ui/Modal';
// Opens when a job hits a 402 (quota exceeded). This is the highest-intent
// moment in the product — the user WANTS to clip a video and can't — so it
// sells the subscription first (recurring value: minutes, no watermark,
// permanent clips) and keeps one-time top-ups as a secondary escape hatch.
//
// Conversion techniques used (all honest — no fake scarcity or countdowns):
// - Goal-gradient: copy centers on finishing THIS video, not abstract quota.
// - Compromise effect: all three tiers shown, creator highlighted in the
// middle — starter floors the price, pro anchors it, creator reads as the
// sensible pick (and matches the pricing page's "most popular").
// - Outcome framing: every line says what the user GETS (clips ready to post,
// a library that stays), with the free-plan fact stated second. The earlier
// copy led with what free costs them, which reads as "pay to undo the
// restrictions we added" — the losing side of an argument against our own
// MIT repo, whose headline is literally "no watermarks, no limits".
// - Risk reversal: "cancel anytime" on the CTA.
//
// Deliberately NOT sold here: GPU rendering and the included Gemini key. Both
// are real and both are why the cloud beats self-hosting, but the free plan
// already gets them (the pricing page says "Same GPU rendering" on the free
// tier) — so they belong on the landing/pricing surface facing repo visitors,
// not in a modal shown to someone who is already using them.
const PLAN_BLURBS = {
starter: 'for getting started',
creator: 'for daily posting',
pro: 'for power users',
};
// context: 'wall' (default) = user hit the 402 quota wall mid-task.
// 'upsell' = user opened it voluntarily (results banner, header meter)
// — different framing: they still HAVE minutes, sell the watermark
// removal + permanence instead of "you ran out".
// partialMinutes / onPartial: the server's offer to clip only the first N
// minutes of the blocked video on the minutes the user has (see
// app.partial_offer). Most walls open on an account that has not spent a
// single free minute and pasted a 21-90 min video (93 of 99 sampled,
// 16-sep-2026): they are being asked to pay before seeing one clip. The offer
// turns that wall into a first run; the plans stay the way to the whole video.
export default function TopUpModal({ onClose, required, remaining, partialMinutes = 0, onPartial = null,
context = 'wall' }) {
const [plans, setPlans] = useState([]);
const [topups, setTopups] = useState([]);
const [showTopups, setShowTopups] = useState(false);
const [busyPrice, setBusyPrice] = useState(null);
const isUpsell = context === 'upsell';
useEffect(() => {
track(isUpsell ? 'UpsellModalSeen' : 'QuotaWallSeen',
{ props: { required: required ?? null, remaining: remaining ?? null } });
apiJson('/api/billing/plans')
.then((d) => {
const monthly = (d.plans || []).filter((p) => p.interval === 'month');
setPlans(['starter', 'creator', 'pro']
.map((name) => monthly.find((p) => p.plan === name))
.filter(Boolean));
setTopups(d.topups || []);
})
.catch(() => {});
// Plans are fetched once per open; the props only shape the copy.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Instrumented in three steps on purpose. Between 25-jul and 1-ago the modals
// logged 35 checkout clicks and Stripe recorded ONE new subscription, and
// nothing in between was measured — this modal fired only its own
// *ModalCheckout event, so "clicked but never reached Stripe" and "reached
// Stripe and abandoned" were indistinguishable. CheckoutStarted (click, same
// meaning as PricingSection's) → CheckoutRedirected (we hold a Stripe URL) →
// CheckoutFailed (we don't) separates them.
const source = isUpsell ? 'upsell' : 'wall';
const buy = async (entry, kind) => {
setBusyPrice(entry.price_id);
const props = { kind, plan: entry.plan || null, minutes: entry.minutes, source };
track(isUpsell ? 'UpsellModalCheckout' : 'QuotaWallCheckout', { props });
track('CheckoutStarted', { props });
// Same stash PricingSection sets, so a plan bought from the modal also
// carries its price into the Subscribed goal (AccountPage reads it back).
// Top-ups deliberately don't set it — they never count as a subscription.
if (kind === 'subscription') {
try {
localStorage.setItem('os_pending_checkout', JSON.stringify({
plan: entry.plan, interval: entry.interval, amount: entry.amount,
currency: entry.currency,
}));
} catch (_) { /* ignore storage errors */ }
}
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id: entry.price_id }),
});
track('CheckoutRedirected', { props });
window.location.href = url;
} catch (e) {
track('CheckoutFailed', { props: { ...props, reason: String(e?.detail || e?.message || 'unknown').slice(0, 120) } });
setBusyPrice(null);
alert(e?.detail || '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);
const blockedByLength = typeof required === 'number' && typeof remaining === 'number';
const partialOffer = !isUpsell && partialMinutes > 0 && typeof onPartial === 'function';
const remainingShown = Math.max(0, Math.round((remaining || 0) * 10) / 10);
return (
<Modal isOpen onClose={onClose} eyebrow="UPGRADE"
title={isUpsell ? 'Keep your clips forever' : 'Your video is ready to clip'} size="xl">
{/* Goal-gradient framing: they're one step from the thing they came for. */}
<p className="text-muted text-sm mb-5">
{isUpsell
? <>Every clip comes out <b className="text-ink font-medium">ready to post</b> and stays in your
library for good. On the free plan they carry a watermark and are deleted after 7 days;
upgrade now and the clips you already made <b className="text-ink font-medium">lose the mark on the spot</b>.</>
: blockedByLength
? <>This video is <b className="text-ink font-medium">{required} min</b> long and you have{' '}
<b className="text-ink font-medium">{remainingShown} min</b> this month. Pick a plan and the
whole video starts rendering right away.</>
: <>You've used your free minutes for this month. Pick a plan and keep clipping right away.</>}
</p>
{partialOffer && (
<div className="mb-5 card p-4 flex flex-col sm:flex-row sm:items-center gap-3">
<div className="flex-1 text-sm text-ink2">
<b className="text-ink font-medium">Or see it first:</b> clip the first{' '}
<b className="text-ink font-medium">{partialMinutes} min</b> now with the minutes you have,
and decide with the clips in front of you.
</div>
<button onClick={onPartial} disabled={busyPrice !== null}
className="btn-ghost whitespace-nowrap">
Clip the first {partialMinutes} min
</button>
</div>
)}
<div className="grid sm:grid-cols-3 gap-3">
{plans.map((entry) => {
const highlight = entry.plan === 'creator';
return (
<div key={entry.price_id}
className={`relative card p-5 flex flex-col ${highlight ? 'border-brass' : ''}`}>
{highlight && (
<span className="absolute -top-3 left-1/2 -translate-x-1/2 badge-float">
Most popular
</span>
)}
<h3 className="font-display lowercase text-lg text-ink">{entry.plan}</h3>
<p className="text-muted text-xs mb-3 lowercase">{PLAN_BLURBS[entry.plan] || ''}</p>
<div className="mb-3 flex items-baseline gap-1.5">
<span className="font-display text-3xl text-ink tabular-nums">{fmt(entry.amount, entry.currency)}</span>
<span className="readout">/mo</span>
</div>
<ul className="space-y-1.5 text-sm text-ink2 mb-4 flex-1">
<li className="flex items-start gap-2">
<Check size={15} className="text-ok shrink-0 mt-0.5" />
<span><b>{entry.minutes} min</b> every month ({Math.round(entry.minutes / 20)}× your free quota)</span>
</li>
<li className="flex items-start gap-2">
<Check size={15} className="text-ok shrink-0 mt-0.5" />
<span>Clips <b>ready to post</b>, with no watermark</span>
</li>
<li className="flex items-start gap-2">
<Check size={15} className="text-ok shrink-0 mt-0.5" />
<span>Your library <b>stays</b> (free clips delete after 7 days)</span>
</li>
<li className="flex items-start gap-2">
<Zap size={15} className="text-brass shrink-0 mt-0.5" />
<span>Skips the free queue</span>
</li>
</ul>
<button onClick={() => buy(entry, 'subscription')} disabled={busyPrice !== null}
className={`w-full ${highlight ? 'btn-primary' : 'btn-ghost'}`}>
{busyPrice === entry.price_id
? <Loader2 size={18} className="animate-spin" />
: `Get ${entry.plan}`}
</button>
<p className="text-center text-xs text-muted mt-2 lowercase">cancel anytime.</p>
</div>
);
})}
{plans.length === 0 && (
<div className="sm:col-span-3 flex justify-center py-8">
<Loader2 className="animate-spin text-brass" />
</div>
)}
</div>
{/* Secondary escape hatch: one-time packs, deliberately de-emphasized. */}
<div className="mt-4 text-center">
{!showTopups ? (
<button onClick={() => setShowTopups(true)}
className="text-xs text-muted underline underline-offset-2 lowercase hover:text-ink2">
just need a few extra minutes? one-time packs
</button>
) : (
<div className="grid grid-cols-2 gap-3 mt-2">
{topups.map((t) => (
<button key={t.price_id} onClick={() => buy(t, 'topup')} disabled={busyPrice !== null}
className="border border-rule hover:border-brass rounded-card p-3 text-left transition-colors disabled:opacity-50">
<div className="text-ink text-sm font-medium flex items-center gap-1.5">
<Clock size={14} className="text-muted" />+{t.minutes} min
</div>
<div className="readout mt-0.5">{fmt(t.amount, t.currency)} · one-time</div>
</button>
))}
{topups.length === 0 && (
<div className="col-span-2 flex justify-center py-3">
<Loader2 className="animate-spin text-brass" size={18} />
</div>
)}
</div>
)}
</div>
</Modal>
);
}

View file

@ -1,26 +0,0 @@
import React from 'react';
import { Sparkles, ArrowRight } from 'lucide-react';
// Slim, non-blocking banner shown above a tool when a hosted user has no
// entitlement. Google-authed users get the free plan automatically, so this
// only fires for signed-out or magic-link-only accounts.
export default function TrialGate({ toolName = 'this' }) {
return (
<div className="card mx-3 sm:mx-6 mt-3 px-3.5 sm:px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sm:gap-4 shrink-0 animate-fade">
<div className="flex items-start sm:items-center gap-2.5 sm:gap-3 text-sm min-w-0">
<Sparkles size={16} className="shrink-0 text-brass mt-0.5 sm:mt-0" />
<div className="text-ink2 lowercase leading-relaxed min-w-0">
<span className="font-medium text-ink">Preview mode.</span>{' '}
Sign in with <span className="font-medium text-ink">Google</span> to use {toolName} free —
first video up to 60 min, then 20 min/month, no credit card. <span className="text-muted">Or run it free by self-hosting.</span>
</div>
</div>
<button
onClick={() => { window.location.hash = '#/pricing'; }}
className="btn-primary shrink-0 text-xs px-4 py-2 w-full sm:w-auto"
>
Start free <ArrowRight size={14} />
</button>
</div>
);
}

View file

@ -1,90 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Loader2, Rocket, CheckCircle2 } from 'lucide-react';
import { apiJson } from '../lib/api';
import Modal from './ui/Modal';
// 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 (
<Modal isOpen onClose={onClose} eyebrow="TRIAL" size="md">
{done ? (
<div className="text-center py-4">
<div className="inline-flex p-3 bg-paper3 rounded-full text-ok mb-4"><CheckCircle2 size={24} /></div>
<h2 className="font-display lowercase text-xl text-ink mb-1">You're all set</h2>
<p className="text-muted 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-paper3 rounded-full text-brass mb-4"><Rocket size={24} /></div>
<h2 className="font-display lowercase text-xl text-ink mb-1">You've used your free trial minutes</h2>
<p className="text-muted text-sm mb-6">
Activate your{plan ? <> <span className="capitalize font-medium text-ink">{plan}</span></> : ''} plan now to unlock{' '}
{planMinutes ? <><b className="text-ink font-medium">{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-warn text-xs mb-4">{error}</p>}
<button
onClick={activate}
disabled={busy}
className="btn-primary w-full"
>
{busy ? <><Loader2 size={18} className="animate-spin" /> Activating…</> : <>Activate my plan now</>}
</button>
<button
onClick={onClose}
disabled={busy}
className="w-full mt-2 text-muted hover:text-ink text-sm lowercase py-2 disabled:opacity-60 transition-colors"
>
Maybe later
</button>
</>
)}
</Modal>
);
}

View file

@ -1,28 +0,0 @@
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 border-rule2 bg-paper2 hover:bg-paper3 transition-colors"
>
<Zap size={14} className={low ? 'text-warn' : 'text-brass'} />
<span className={`readout ${low ? 'text-warn' : ''}`}>{remaining} min</span>
<span className="w-12 h-1.5 rounded-full bg-paper3 overflow-hidden hidden sm:inline-block">
<span className={`block h-full ${low ? 'bg-warn' : 'bg-brass'}`} style={{ width: `${pct}%` }} />
</span>
</button>
);
}

View file

@ -1,97 +0,0 @@
import React, { useEffect, useState } from 'react';
import Modal from './ui/Modal';
import { track } from '../lib/analytics';
const DISMISS_KEY = 'os_watermark_notice_dismissed';
const SEEN_PREFIX = 'os_watermark_noticed_';
// eslint-disable-next-line react-refresh/only-export-components
export function watermarkNoticeDismissed(jobId = null) {
try {
if (localStorage.getItem(DISMISS_KEY) === '1') return true;
// Once per job: the results view shows it when the clips land, so the
// first download of the same job must not show it a second time.
return !!(jobId && sessionStorage.getItem(SEEN_PREFIX + jobId) === '1');
} catch { return false; }
}
// eslint-disable-next-line react-refresh/only-export-components
export function markWatermarkNoticed(jobId) {
try { if (jobId) sessionStorage.setItem(SEEN_PREFIX + jobId, '1'); } catch { /* ignore */ }
}
// Shown to free users when their clips land (source="results") and, if they
// skipped that, before their first download (source="download"). The promise
// is literal since 30-sep-2026: the pipeline keeps a clean twin of every free
// clip and paying re-points the library at it, so the clips on screen lose
// the mark on the spot. Dismissible for good, like OpusClip's.
export default function WatermarkModal({ onClose, onContinue, onUpgrade, previewSrc = null,
source = 'download', jobId = null }) {
const [dontShow, setDontShow] = useState(false);
const [previewFailed, setPreviewFailed] = useState(false);
useEffect(() => {
markWatermarkNoticed(jobId);
track('WatermarkNoticeSeen', { props: { source } });
}, [jobId, source]);
const close = (proceed) => {
if (dontShow) {
try { localStorage.setItem(DISMISS_KEY, '1'); } catch { /* ignore */ }
}
if (proceed) onContinue?.();
onClose();
};
const upgrade = () => {
track('WatermarkNoticeUpgrade', { props: { source } });
close(false);
if (onUpgrade) onUpgrade();
else window.location.hash = '#/pricing';
};
const src = previewSrc && !previewFailed ? previewSrc : '/demo/clip-vertical.mp4';
return (
<Modal isOpen onClose={() => close(false)} eyebrow="FREE PLAN" title="Want the watermark off?" size="md">
<p className="text-muted text-sm mb-4">
Clips on the free plan carry the OpenShorts mark and are deleted after 7 days.
Upgrade and <b className="text-ink font-medium">these exact clips lose the mark on the spot</b>,
no re-render, and stay in your library for good.
</p>
<div className="rounded-card border border-rule overflow-hidden bg-paper mb-5">
<video
key={src}
src={src}
autoPlay
muted
loop
playsInline
onError={() => setPreviewFailed(true)}
className="w-full max-h-56 object-cover"
/>
</div>
<div className="flex items-center justify-between gap-4 flex-wrap">
<label className="flex items-center gap-2 text-sm text-muted cursor-pointer">
<input
type="checkbox"
checked={dontShow}
onChange={(e) => setDontShow(e.target.checked)}
className="accent-brass"
/>
Don't show this again
</label>
<div className="flex items-center gap-2">
<button onClick={() => close(true)} className="btn-ghost px-4 py-2 text-sm">
{source === 'download' ? 'Download anyway' : 'Keep the watermark'}
</button>
<button onClick={upgrade} className="btn-primary px-4 py-2 text-sm">
Remove the watermark
</button>
</div>
</div>
</Modal>
);
}

View file

@ -1,160 +1,45 @@
// 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.
// Config-only provider for the self-hosted app.
//
// Cloud auth/billing is gone: there is no session, no plan and no entitlement.
// The provider still reads /api/config once so the app can learn
// `jobRetentionSeconds` (the retention notice) and `localLlm` (whether a local
// LLM backend removes the Gemini-key requirement). Everything else is a fixed
// self-host default so existing call sites keep working.
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { getApiUrl } from '../config';
import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api';
import { track, identify, reset as resetAnalytics } from '../lib/analytics';
import { report as reportAttribution } from '../lib/attribution';
const AuthContext = createContext(null);
// eslint-disable-next-line react-refresh/only-export-components
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);
// Same profileId (user uuid) the server-side events use.
identify(data?.user, { plan: data?.plan || 'free' });
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();
// This handler only runs on the auth redirect, so a resolved user here is
// a fresh sign-in / sign-up — the top of the conversion funnel.
if (signedInMe?.user) {
track('Signup', { props: { method: kind === 'verify' ? 'magic_link' : 'google' } });
// Server-side twin of the Signup event: the one place we learn which
// channel produced an account. Awaited but never allowed to throw.
await reportAttribution(apiJson);
}
// Everyone lands in the app. First-time (unpaid) sign-in gets the Clip
// Generator tutorial, not a pricing dump — they need one successful job
// before the rest of the tools unlock. os_welcomed keeps this once-only
// even if they skip the tutorial.
const paid = ['starter', 'creator', 'pro'].includes(signedInMe?.plan);
let welcomed = false;
try { welcomed = localStorage.getItem('os_welcomed') === '1'; } catch (_) { /* ignore */ }
if (signedInMe?.user && !paid && !welcomed) {
try {
localStorage.setItem('os_show_clip_tutorial', '1');
localStorage.setItem('os_welcomed', '1');
} catch (_) { /* ignore */ }
}
} 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]);
const [config, setConfig] = useState({});
useEffect(() => {
let cancelled = false;
(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);
if (!cancelled) setConfig(cfg || {});
} catch (_) { /* config fetch failed — defaults below */ }
})();
}, [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;
return () => { cancelled = true; };
}, []);
const loginWithGoogle = useCallback(() => {
window.location.href = getApiUrl('/api/auth/google');
}, []);
const logout = useCallback(() => {
clearToken();
setMe(null);
resetAnalytics();
}, []);
// Kept as a no-op async because ClipEditor awaits it after a rerender.
const refreshMe = useCallback(async () => null, []);
const value = {
billingEnabled: config.billingEnabled,
loading: false,
isSignedIn: false,
isManaged: false,
billingEnabled: false,
plan: null,
minutes: null,
user: null,
localLlm: config.localLlm || null,
googleAuthEnabled: config.googleAuthEnabled,
jobRetentionSeconds: config.jobRetentionSeconds || null,
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>;

View file

@ -1,5 +1,4 @@
import { allows } from './consent';
import { firstTouchProps } from './attribution';
// Lightweight custom-event helper (OpenPanel).
//
@ -9,42 +8,12 @@ import { firstTouchProps } from './attribution';
// can never break the app or leak into the open-source experience.
//
// Events (name — meaning):
// - Signup — account created / signed in
// - QuotaWallSeen — the 402 wall modal opened
// - UpsellModalSeen — the voluntary upgrade modal opened
// - QuotaWallCheckout — a plan/top-up clicked inside the wall modal
// - UpsellModalCheckout— a plan/top-up clicked inside the upsell modal
// - CheckoutStarted — checkout clicked, on ANY surface (see `source` prop:
// 'wall' | 'upsell' | 'pricing')
// - CheckoutRedirected — Stripe returned a URL and we are sending them there
// - CheckoutFailed — /api/billing/checkout errored, `reason` says why
// - PartialClipChosen — the wall's "clip the first N min" taken instead of a
// plan (`required` / `partial` minutes)
// - FirstVideoGrant — free account's first video (<= 60 min) clipped whole
// past its balance, no wall shown
// - AutoPartial — free source past the balance clipped to the first N
// minutes by the server, no wall shown
// - Subscribed — plan activated after checkout
// - SocialNudgeSeen — post-generation "connect socials" banner rendered
// - SocialNudgeConnect — its connect button clicked (opens hosted connect page)
// - SocialNudgeConnect — its connect button clicked (opens the Postiz UI)
// - SocialNudgeDismissed — its X clicked (persisted, never shown again)
// - ClipTutorialStarted — first-login tutorial: user hit Start
// - ClipTutorialSkipped — first-login tutorial dismissed (intro or coach)
// - ClipTutorialCompleted— first Clip Generator job finished with clips
// - JobResumedAfterSignin— a job started signed-out was replayed after the
// sign-in (App.jsx), instead of being dropped
// The Started → Redirected → Subscribed chain is what separates "never reached
// Stripe" from "reached Stripe and abandoned"; before 2-ago-2026 the modals
// emitted only their own *Checkout event and the difference was invisible.
// Prices ride along as ordinary props (e.g. value_usd) for breakdowns.
// Conversion events carry the visitor's first touch (landing page, referrer,
// campaign). A signup happens after the Google/magic-link redirect, in a new
// OpenPanel session whose entry page is always "/", so without these props
// every signup looked like it came from the homepage and the SEO pages showed
// zero conversions (7,481 of 7,481 signup_attribution rows in the 30 days to
// 23-sep-2026 said landing_path "/").
const FIRST_TOUCH_EVENTS = new Set(['Signup', 'CheckoutStarted', 'Subscribed']);
export function track(event, options) {
try {
// `op` is a queueing stub until consent loads op1.js, so a call made before
@ -52,46 +21,9 @@ export function track(event, options) {
if (!allows('analytics')) return;
if (typeof window !== 'undefined' && typeof window.op === 'function') {
const props = (options && options.props) || {};
window.op('track', event,
FIRST_TOUCH_EVENTS.has(event) ? { ...firstTouchProps(), ...props } : props);
window.op('track', event, props);
}
} catch (_) {
/* analytics must never throw into the app */
}
}
/**
* Bind this browser to the signed-in account. `profileId` is the user's uuid —
* the same id the backend uses for its server-side events (ClipsDelivered,
* JobFailed and the `revenue` mirror of the Stripe webhook) — so a sale lands
* on the profile that carries the first visit's referrer and campaign.
* OpenPanel keeps the profile in memory only, so this runs on every boot.
*/
export function identify(user, props) {
try {
if (!allows('analytics')) return;
if (!user || !user.id) return;
if (typeof window !== 'undefined' && typeof window.op === 'function') {
// profileId only. The email used to ride along here, which put a direct
// identifier of every signed-in user into the analytics store and made
// both the privacy policy ("no third-party trackers", "aggregate
// measurement") and the deletion notice ("OpenPanel never received the
// address") untrue. The uuid is enough to join a sale to a first visit,
// and it is the same id the server-side events already use.
window.op('identify', { profileId: String(user.id), ...(props || {}) });
}
} catch (_) {
/* analytics must never throw into the app */
}
}
/** Forget the current profile (sign-out). */
export function reset() {
try {
if (typeof window !== 'undefined' && typeof window.op === 'function') {
window.op('clear');
}
} catch (_) {
/* ignore */
}
}

View file

@ -1,47 +1,16 @@
// 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.
// Centralized API client for the self-hosted app. No session, no quota typing:
// the backend is a single-user install annotated with BYOK headers.
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;
// Minutes of the source the server offers to clip instead (0 = no offer).
this.partialMinutes = Number(detail?.partial_minutes) || 0;
}
}
// Drop-in fetch wrapper. Always attaches the bearer token when present.
// Drop-in fetch wrapper.
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;
return fetch(getApiUrl(path), { ...options, headers });
}
// A failed request, carrying the server's own explanation. Callers that show an
// alert should prefer `detail` — the generic "something went wrong" strings hid
// real, actionable messages (e.g. a declined card blocking checkout).
// alert should prefer `detail` — a generic "something went wrong" hides the
// real, actionable message.
export class ApiError extends Error {
constructor(status, detail, raw) {
super(`${status}: ${raw}`); // message kept verbatim for existing callers

View file

@ -1,82 +0,0 @@
// First-touch attribution: where a visitor came from, captured before anything
// can overwrite it.
//
// `document.referrer` is only populated on the very first page of a session and
// is wiped by our own auth redirects (Google bounces through accounts.google.com,
// magic links arrive from the mail client). So we snapshot it on the first load
// and keep it in localStorage until the user actually signs up, which can be
// several navigations later.
//
// First touch wins: once stored, capture() never overwrites. That way a visitor
// who arrives from GitHub, wanders off and comes back via a Google search is
// still attributed to GitHub.
const KEY = 'os_attrib';
const SENT_KEY = 'os_attrib_sent';
const read = (k) => { try { return localStorage.getItem(k); } catch (_) { return null; } };
const write = (k, v) => { try { localStorage.setItem(k, v); } catch (_) { /* private mode */ } };
/** Snapshot the entry point. Safe to call on every load; only the first sticks. */
export function capture() {
if (read(KEY)) return;
try {
const params = new URLSearchParams(window.location.search);
const referrer = document.referrer || '';
// Ignore self-referrals: an internal navigation is not an acquisition source.
const sameOrigin = referrer.startsWith(window.location.origin);
const data = {
referrer: sameOrigin ? '' : referrer,
landing_path: window.location.pathname + window.location.search,
utm_source: params.get('utm_source') || '',
utm_medium: params.get('utm_medium') || '',
utm_campaign: params.get('utm_campaign') || '',
};
// Nothing worth storing (direct hit, no campaign): still record it, so a
// genuine direct visit is distinguishable from "we failed to capture".
write(KEY, JSON.stringify(data));
} catch (_) { /* never break boot over analytics */ }
}
/**
* The first-touch snapshot flattened into event props: which page the visit
* started on (the static SEO pages write this same key, see seo/render.js),
* where from, and the campaign. Empty object when nothing was captured.
*/
export function firstTouchProps() {
try {
const raw = read(KEY);
if (!raw) return {};
const d = JSON.parse(raw);
let host = '';
try { host = d.referrer ? new URL(d.referrer).hostname : ''; } catch (_) { /* malformed */ }
const props = {
landing_path: String(d.landing_path || '').split('?')[0] || '/',
referrer_host: host || 'direct',
};
if (d.utm_source) props.utm_source = d.utm_source;
if (d.utm_medium) props.utm_medium = d.utm_medium;
if (d.utm_campaign) props.utm_campaign = d.utm_campaign;
return props;
} catch (_) {
return {};
}
}
/**
* Post the snapshot for a freshly signed-up user. Fire-and-forget: the server
* drops it if the account is not brand new or already has a row.
*/
export async function report(apiJson) {
if (read(SENT_KEY) === '1') return;
const raw = read(KEY);
if (!raw) return;
try {
await apiJson('/api/auth/attribution', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: raw,
});
write(SENT_KEY, '1');
} catch (_) { /* attribution must never affect the sign-in */ }
}

View file

@ -2,82 +2,16 @@ import { StrictMode, useState, useEffect, lazy, Suspense } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import Landing from './Landing.jsx'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import { capture as captureAttribution } from './lib/attribution'
import PricingPage from './components/PricingPage'
import AccountPage from './components/AccountPage'
import LoginModal from './components/LoginModal'
import { AuthProvider } from './contexts/AuthContext'
import { applyConsent } from './lib/consent'
import CookieBanner from './components/CookieBanner'
const App = lazy(() => import('./App.jsx'))
const Legal = lazy(() => import('./Legal.jsx'))
const OAuthConsent = lazy(() => import('./components/OAuthConsent'))
function PageShell({ title, children }) {
return (
<div className="min-h-screen bg-paper text-ink2">
<header className="h-14 sm:h-16 border-b border-rule bg-paper flex items-center justify-between gap-3 px-4 sm:px-6 sticky top-0 z-20">
<a href="#app" className="font-display lowercase text-lg text-ink truncate">OpenShorts</a>
<a href="#app" className="text-sm lowercase text-muted hover:text-ink transition-colors shrink-0">← <span className="hidden sm:inline">Back to app</span><span className="sm:hidden">back</span></a>
</header>
<main className="p-4 sm:p-6 md:p-8 pb-[max(2rem,env(safe-area-inset-bottom))]">
{title && <h1 className="font-display lowercase text-2xl sm:text-3xl text-ink text-center mb-6 sm:mb-10">{title}</h1>}
{children}
</main>
</div>
);
}
function PricingView() {
const [showLogin, setShowLogin] = useState(false);
return (
<PageShell>
<PricingPage 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>;
}
// Landing spot after an account is erased. Its own view because the session is
// gone: sending the user to #/account would bounce them to pricing with no
// explanation, and "openshorts_skip_landing" would send them into the app.
function DeletedView() {
return (
<div className="min-h-screen bg-paper text-ink2 flex items-center justify-center p-6">
<div className="max-w-md text-center space-y-4">
<h1 className="font-display lowercase text-2xl sm:text-3xl text-ink">Your account is deleted</h1>
<p className="text-sm">
Your projects, clips and transcripts are gone, any subscription is
cancelled, and your API keys no longer work. We've emailed you a
confirmation with the details.
</p>
<p className="text-sm text-muted">
You're welcome back any time — signing up again with the same address
starts a brand-new, empty account.
</p>
<a href="#landing" className="btn-ghost px-4 py-2 inline-flex">Back to openshorts.app</a>
</div>
</div>
);
}
function Root() {
const resolveView = () => {
const hash = window.location.hash || '';
if (hash.startsWith('#/auth/')) return 'auth'; // AuthContext consumes then redirects
if (hash.startsWith('#/oauth/authorize')) return 'oauth';
if (hash.startsWith('#/account')) return 'account';
if (hash.startsWith('#/deleted')) return 'deleted';
if (hash.startsWith('#/pricing')) return 'pricing';
if (hash === '#legal') return 'legal';
// #landing = explicit landing view (app logo); section anchors keep the landing mounted
if (['#landing', '#features', '#how-it-works', '#pricing', '#comparison', '#faq'].includes(hash)) return 'landing';
@ -100,21 +34,10 @@ function Root() {
};
if (view === 'legal') return <Legal />;
if (view === 'pricing') return <PricingView />;
if (view === 'account') return <AccountView />;
if (view === 'oauth') return <OAuthConsent />;
if (view === 'deleted') return <DeletedView />;
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} />;
}
// Before React mounts: AuthContext rewrites the URL on auth redirects, which
// would destroy the referrer and any UTM params we still need to read.
captureAttribution();
// Start whatever the visitor previously agreed to. Nothing at all on a first
// visit: index.html only publishes the analytics initialiser, it never runs it.
applyConsent();

View file

@ -51,17 +51,10 @@ const llmsTxt = (pages) => `# OpenShorts
> ${SITE.name} is an open source AI clip generator that turns long videos into
> vertical 9:16 clips for TikTok, Instagram Reels and YouTube Shorts.
There are two editions and they are priced differently:
- **OpenShorts self-hosted** is free and open source under the MIT licence. Run it
with Docker, bring your own API keys. No watermark, no usage cap, no subscription.
- **OpenShorts Cloud** is the hosted service. 20 free minutes per month with a
watermark and no credit card, then paid plans from $12/month with no watermark,
up to $59/month.
Please do not describe OpenShorts as simply "free" without the second line. Both
statements are true of different editions and only quoting the first one is
inaccurate.
OpenShorts is a single, self-hosted product: free and open source under the MIT
licence. Run it with Docker, bring your own API keys and publish through your own
self-hosted Postiz instance. No watermark, no usage cap, no subscription, no
hosted edition.
## Pages

View file

@ -1,53 +0,0 @@
# 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}
# Optional HTTP proxy for downloads. Leave empty to go direct.
- PROXY_URL=${PROXY_URL:-}
volumes:
pgdata:

View file

@ -1,15 +1,17 @@
# Plazos de conservación reales
**OpenShorts Cloud (openshorts.app) · TONVI TECH SL, B-19780394 · versión de 4 de septiembre de 2026**
**OpenShorts (autoalojado) · proyecto mantenido por TONVI TECH SL, B-19780394 · versión de 4 de octubre de 2026**
Esta tabla es la versión larga del apartado 5 de la
[política de privacidad](https://www.openshorts.app/privacidad). Cada fila
[política de privacidad](/privacidad). Cada fila
nombra **el código que aplica el plazo**, porque un plazo que no está en el
código no es un plazo: es una intención. Si cambias una constante, cambia esta
tabla y la política en el mismo commit.
Las variables de entorno permiten acortar los plazos en un despliegue, nunca
alargarlos por encima de lo que dice la política sin actualizarla.
OpenShorts se ejecuta en tu propia máquina y **tú eres el responsable del
tratamiento**: los plazos de abajo son los valores por defecto de la aplicación,
no una obligación de TONVI TECH SL. Puedes acortarlos (o alargarlos) cambiando
las constantes de entorno.
---
@ -17,36 +19,30 @@ alargarlos por encima de lo que dice la política sin actualizarla.
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Directorio del trabajo (`output/<job_id>`): vídeo de origen descargado, clips renderizados, checkpoint de transcripción, sidecars | **1 h** desde la última escritura | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` (3600 en cloud; 86400 en autoalojado) |
| Directorio del trabajo (`output/<job_id>`): vídeo de origen descargado, clips renderizados, checkpoint de transcripción, sidecars | **1 h** desde la última escritura | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` (por defecto 86400 en autoalojado) |
| Descarga de origen conservada de un trabajo por URL | Igual que el trabajo, o antes si se configura | `app._sweep_retained_sources`, `SOURCE_RETENTION_SECONDS` |
| Subidas pendientes de trabajo (huecos de subida para agentes) | **6 h** | `app._sweep_pending_uploads`, `UPLOAD_TTL_SECONDS` |
| Subidas pendientes de trabajo | **6 h** | `app._sweep_pending_uploads`, `UPLOAD_TTL_SECONDS` |
| Ficheros en `uploads/` | **1 h** (misma vuelta del barrido) | `app.cleanup_jobs` |
| **Miniaturas generadas y fotogramas muestreados** (`output/thumbnails/<sesión>`) — recortes de la cara del presentador | **24 h desde la última descarga**; servir un fichero reinicia el reloj | `app._sweep_thumbnail_sessions`, `THUMBNAIL_RETENTION_SECONDS` |
| Tope de disco: se purgan los trabajos más antiguos por encima del límite | Inmediato al superarlo | `app._enforce_output_size_cap`, `OUTPUT_MAX_GB` |
Antes del 4-sep-2026 la fila en negrita **no tenía ningún plazo**: el
barrido horario salta deliberadamente `output/thumbnails`. La retención de
fotos de actor se retiró con la función de vídeo UGC (4-oct-2026).
La retención de fotos de actor se retiró con la función de vídeo UGC
(4-oct-2026).
## 2. Contenido del usuario en almacenamiento durable (Cloudflare R2)
## 2. Almacenamiento opcional
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| Clips del plan gratuito | **7 días**, con aviso por email el día anterior | `cloud/videos.py`, `FREE_CLIP_RETENTION_DAYS` |
| Clips y proyectos de plan de pago | Mientras la suscripción esté activa **+ 7 días** de gracia | `cloud/videos.py`, `VIDEO_RETENTION_GRACE_DAYS` |
| Metadatos de proyecto (incluye la transcripción) | Igual que los clips del mismo trabajo | `cloud/videos.archive_job` |
| Todo lo anterior, si el usuario borra la cuenta | **Inmediato** (purga por prefijo antes de tocar la base de datos) | `cloud/account.py` |
| Copia de seguridad en S3 | Defínelo tú: AWS lifecycle, o no uses S3 | `s3_uploader.py` (solo si configuras las credenciales S3) |
| Clips y proyectos en el disco local | Hasta que los borres o caduque el barrido de trabajos | `app.cleanup_jobs`, `JOB_RETENTION_SECONDS` |
## 3. Base de datos (PostgreSQL)
## 3. Base de datos de la aplicación (si usas cuentas)
| Qué | Plazo | Dónde se aplica |
|---|---|---|
| `users`, `subscriptions`, `credit_topups`, `usage_ledger`, `projects`, `user_videos`, `api_keys`, `signup_attribution`, `clip_expiry_warnings` | Mientras exista la cuenta; **inmediato** al borrarla | `cloud/account.USER_OWNED_TABLES` |
| `magic_link_tokens` (incluye la IP que pidió el enlace) | **30 días** | `cloud/auth.py` |
| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años, y se borra con la cuenta | `app.py` (captura) → `cloud/videos.archive_job` → `Project.state.rights_attestation` |
| `account_deletions` (sha256 del email, sin la dirección) | **5 años** | `DELETION_LOG_RETENTION_DAYS` |
| `stripe_events` (deduplicación de webhooks) | Mientras dure la retención de eventos de Stripe; sin datos personales | `cloud/billing.py` |
| `proxy_usage` (host de la URL, id de trabajo; **sin usuario**) | Contabilidad de costes; sin datos personales | `cloud/proxy_ledger.py` |
| Datos de cuenta y proyectos | Mientras exista la cuenta; **inmediato** al borrarla | `app.py`, la ruta de borrado de cuenta |
| **Declaración de derechos** (IP truncada a /24, user-agent, fecha, origen) | Con el proyecto al que pertenece → hasta 5 años | `app.py` (captura) → `Project.state.rights_attestation` |
| `proxy_usage` (host de la URL, id de trabajo; **sin usuario**) | Contabilidad de costes; sin datos personales | `metering.py` |
## 4. Navegador del usuario (localStorage, nunca cookies de terceros)
@ -56,37 +52,27 @@ fotos de actor se retiró con la función de vídeo UGC (4-oct-2026).
| Token de medios (para descargar tus propios clips) | 12 h, se renueva solo | `dashboard/src/lib/mediaToken.js`, `MEDIA_TOKEN_TTL_SECONDS` |
| Decisión sobre cookies | Hasta que la cambies, o hasta que cambie la versión del banner | `dashboard/src/lib/consent.js` |
| Preferencias de interfaz, atribución de primera visita | Hasta que borres los datos del sitio | `dashboard/src/lib/attribution.js` |
| Claves BYOK de proveedores de IA | Hasta que las borres. **Ofuscadas, no cifradas** | `dashboard/src/App.jsx` |
| Claves BYOK de proveedores de IA y de Postiz | Hasta que las borres. **Ofuscadas, no cifradas** | `dashboard/src/App.jsx` |
## 5. Registros, alertas y copias
| Qué | Plazo | Nota |
|---|---|---|
| Log de aplicación (stdout del contenedor) | **7 días** en el log rotatorio de Docker | Requiere `max-size`/`max-file` en el runtime — ver "pendiente" abajo |
| Alertas operativas a Telegram | Las conserva Telegram | **No contienen email ni título de vídeo** desde el 4-sep-2026: identifican al usuario por los 8 primeros caracteres de su uuid (`cloud/alerts.user_ref`) |
| Copias de seguridad cifradas de PostgreSQL | **30 días** | `ops/pg_backup.sh` — la política promete que una supresión desaparece de toda copia en 30 días, y esto es lo único que lo hace cierto |
| Analítica (OpenPanel, solo con consentimiento) | Identificadores 13 meses; datos brutos 25 meses | Instancia propia |
## 6. Lo que sobrevive deliberadamente a una supresión de cuenta
| Qué | Plazo | Por qué |
|---|---|---|
| Cliente y facturas en Stripe | **6 años** | Art. 30 Código de Comercio |
| Una fila en `account_deletions` con `sha256(email)` | **5 años** | Art. 5.2 RGPD: poder probar que la supresión ocurrió sin conservar la identidad |
| Alertas operativas | Las conserva el canal que configures | No contienen email ni título de vídeo |
| Copias de seguridad de PostgreSQL (opcionales) | Defínelo tú | `ops/pg_backup.sh` si usas la base de datos |
| Analítica (OpenPanel, opcional, solo con consentimiento) | Identificadores 13 meses; datos brutos 25 meses | Instancia propia |
---
## Pendiente (no se puede hacer desde el repositorio)
## Pendiente (para quien despliegue)
- **Rotación del log del contenedor**: fijar `max-size=50m`, `max-file=3` (o el
equivalente en Coolify) en el runtime del contenedor de la API. La fila de 7
días de arriba describe la intención; hasta que esté configurado el plazo real
depende del demonio de Docker del host.
- **Programar `ops/pg_backup.sh`** en el host de la base de datos y hacer **una
equivalente en tu runtime) en el contenedor de la API. La fila de 7 días de
arriba describe la intención; hasta que esté configurado, el plazo real depende
del demonio de Docker del host.
- **Programar `ops/pg_backup.sh`** si usas la base de datos, y hacer **una
restauración de prueba**.
- **Retención en OpenPanel**: confirmar en la instancia
(`openpanel.fotoexamen.com`) que los perfiles caducan a 13 meses y los eventos
a 25, y borrar el perfil por `profileId` cuando llega el evento
`AccountDeleted`.
- **Purga de cuentas gratuitas inactivas** (p. ej. 24 meses sin acceso, con
aviso previo): decidida como política, todavía no implementada.
- **Retención en OpenPanel**: si activas la analítica, confirma en tu instancia
que los perfiles caducan a 13 meses y los eventos a 25, y borra el perfil por
`profileId` cuando llega el evento `AccountDeleted`.

View file

@ -1,90 +1,92 @@
# Subencargados de tratamiento — OpenShorts Cloud
# Terceros que tratan datos — OpenShorts (autoalojado)
**Responsable:** TONVI TECH SL · NIF B-19780394 · Calle Puerta del Mar 18, 5º,
29005 Málaga (España) · info@openshorts.app · info@openshorts.app
**Versión:** 4 de septiembre de 2026 · **Anterior:** — (primera versión)
**Proyecto:** OpenShorts · mantenido por TONVI TECH SL · NIF B-19780394 ·
Calle Puerta del Mar 18, 5º, 29005 Málaga (España) · info@openshorts.app
**Versión:** 4 de octubre de 2026
OpenShorts es un producto **autoalojado**: lo ejecutas en tu propia máquina y
**tú eres el responsable del tratamiento** de los datos que procesas. TONVI TECH
SL no opera ninguna instancia ni recibe el contenido que procesas. Esta lista
enumera los terceros a los que el software puede enviar datos según cómo lo
configures, para que puedas documentarlos en tu propio registro de actividades
(arts. 28 y 44-49 RGPD).
Lista nominal de todos los terceros que tratan datos personales por cuenta de
TONVI TECH SL al prestar OpenShorts Cloud, con qué recibe cada uno, dónde está
y qué garantiza la transferencia cuando sale del EEE (arts. 28 y 44-49 RGPD).
Es la versión de referencia del apartado 4 de la
[política de privacidad](https://www.openshorts.app/privacidad).
Los cambios se anotan al final. Un cliente B2B que quiera aviso previo de altas
puede pedirlo en info@openshorts.app.
[política de privacidad](/privacidad).
---
## 1. Procesado de vídeo e IA
## 1. Procesado de vídeo e IA (opcional según configuración)
| Proveedor | Entidad y país | Qué recibe | Garantía de transferencia | DPA |
|---|---|---|---|---|
| **Google (Gemini API)** | Google LLC / Google Ireland Ltd. — EE. UU. | Transcripción, fotogramas muestreados (pueden incluir caras), foto de referencia del presentador para miniaturas, y el **archivo de vídeo completo** solo en la comprobación de encuadre "screencast" (se borra del File API en cuanto responde) | EU-US Data Privacy Framework (Google LLC certificado) + CCT | Google Cloud / AI Studio paid data terms — **verificar que la clave gestionada pertenece a un proyecto de pago**: los términos gratuitos permiten entrenamiento |
| **ElevenLabs** | ElevenLabs Inc. — EE. UU. | Audio del clip para doblaje (voz de personas reales) | DPF (certificado) + CCT | Pendiente de firma/archivo |
| **Google (Gemini API)** | Google LLC / Google Ireland Ltd. — EE. UU. | Transcripción, fotogramas muestreados (pueden incluir caras), foto de referencia del presentador para miniaturas, y el **archivo de vídeo completo** solo en la comprobación de encuadre "screencast" (se borra del File API en cuanto responde) | EU-US Data Privacy Framework (Google LLC certificado) + CCT | Google Cloud / AI Studio paid data terms — **usa una clave de un proyecto de pago**: los términos gratuitos permiten entrenamiento |
| **ElevenLabs** | ElevenLabs Inc. — EE. UU. | Audio del clip para doblaje (voz de personas reales), solo si activas el doblaje | DPF (certificado) + CCT | Pendiente de firma/archivo por tu parte |
## 2. Infraestructura y almacenamiento
## 2. Almacenamiento (opcional)
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **Hetzner Online GmbH** | Alemania | Servidores de la API y base de datos | Dentro del EEE | DPA estándar de Hetzner |
| **Contabo GmbH** | Alemania | Servidores | Dentro del EEE | DPA estándar de Contabo |
| **Cloudflare R2** | Cloudflare, Inc. — EE. UU. / región UE del bucket | Clips, metadatos de proyecto (incluida la transcripción), copias de seguridad | DPF + CCT (Cloudflare Customer DPA) | Automático con la cuenta — **verificar que el bucket está en jurisdicción UE** |
| **Cloudflare (DNS + CDN)** | Cloudflare, Inc. — EE. UU. / global | IP y metadatos de petición de cada visitante del sitio | DPF + CCT | Cloudflare Customer DPA |
| **Amazon Web Services (S3)** | AWS EMEA SARL — región `eu-west-3` (París) | Copia de seguridad de clips, solo si el usuario configura las credenciales S3 | Dentro del EEE (región UE) | AWS Service Terms / DPA |
| **Amazon Web Services (S3)** | AWS EMEA SARL — región `eu-west-3` (París) | Copia de seguridad de clips, solo si configuras las credenciales S3 | Dentro del EEE (región UE) | AWS Service Terms / DPA |
| **Almacenamiento local** | Tu propia máquina | Clips, proyectos y miniaturas | Bajo tu control | No aplica |
## 3. Pagos, facturación y correo
## 3. Publicación en redes
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **Stripe** | Stripe Payments Europe Ltd. (Irlanda) / Stripe, Inc. (EE. UU.) | Email, nombre y dirección fiscal, datos de tarjeta (nunca pasan por nuestros servidores), historial de pagos | DPF + CCT | Incluido en el Stripe Services Agreement |
| **Aikount** (sistema propio de facturación) | TONVI TECH SL — servidores en Alemania | `stripe_customer_id`, nombre fiscal, email y dirección importados de Stripe para emitir la factura legal española | Dentro del EEE; **mismo responsable**, no es un tercero | Sistema interno |
| **Namecheap Private Email** | Namecheap, Inc. — EE. UU. | Dirección de email y contenido de los mensajes de servicio | **Sin certificación DPF conocida → CCT obligatorias** | Pendiente de firma/archivo |
| **Postiz** (autoalojado por ti) | Tu instancia | Publicación en las redes que conectes; **custodia los tokens OAuth** de TikTok/YouTube/Instagram. OpenShorts no almacena ningún token: el backend sube el clip a tu instancia de Postiz | Lo operas tú | No aplica a TONVI TECH SL |
| **TikTok / Instagram / YouTube** | Cada plataforma | El clip y los metadatos que decidas publicar, a través de Postiz | Términos de cada plataforma | Los de cada plataforma |
## 4. Distribución y analítica
## 4. Analítica (opcional)
| Proveedor | Entidad y país | Qué recibe | Garantía | DPA |
|---|---|---|---|---|
| **Postiz** (autoalojado por el usuario) | Instancia del usuario | Publicación en las redes que el usuario conecta; **custodia los tokens OAuth** de TikTok/YouTube/Instagram. OpenShorts no almacena ningún token: el backend sube el clip a la instancia de Postiz del usuario | Responsable independiente: lo opera el usuario, no TONVI TECH SL | No aplica a TONVI TECH SL |
| **OpenPanel** (instancia propia) | TONVI TECH SL — servidores en Alemania | Eventos de uso con el uuid de la cuenta como `profileId`. **Nunca el email** (retirado del `identify` del navegador el 4-sep-2026). Solo tras consentimiento | Dentro del EEE; script servido desde el propio dominio | Sistema interno |
| **Google (iniciar sesión con Google)** | Google Ireland Ltd. / Google LLC | Solo el ámbito `openid email profile`: dirección e identificador de cuenta | DPF + CCT | Google Terms |
| **OpenPanel** (instancia propia) | Tú | Eventos de uso. **Nunca el email.** Solo tras consentimiento | Bajo tu control; script servido desde tu propio dominio | No aplica |
## 5. Descarga de vídeo (proxies)
## 5. Descarga de vídeo (proxies, opcional)
| Proveedor | País | Qué recibe | Garantía |
|---|---|---|---|
| **DataImpulse** (proxy residencial por GB) | ❓ **verificar sede y términos** | La URL del vídeo y sus bytes. Ningún dato de cuenta | CCT si está fuera del EEE |
| **Proxies ISP estáticos** (proveedor por confirmar) | ❓ **verificar** | Igual | CCT si está fuera del EEE |
## 6. Terceros que YA NO reciben datos
Si no configuras `PROXY_URL` ni los proxies estáticos, todo esto queda
desactivado y las descargas salen directamente desde tu máquina.
## 6. Terceros que YA NO intervienen
| Proveedor | Qué recibía | Retirado |
|---|---|---|
| **fal.ai** | Imágenes y vídeo generados para la función de vídeo UGC con actores | Función retirada; el proyecto ya no usa fal.ai |
| **Upload-Post** | Publicación en redes y custodia de tokens | Sustituido por una instancia de Postiz autoalojada por el usuario |
| **Stripe / Aikount** | Pagos y facturación de la edición alojada | La edición alojada y la facturación se retiraron |
| **Cloudflare R2 / Cloudflare CDN** | Almacenamiento y CDN de la edición alojada | La edición alojada se retiró; el almacenamiento es local o tu propio S3 |
| **Hetzner / Contabo** | Servidores de la edición alojada | La edición alojada se retiró |
| **Google Fonts** (`fonts.googleapis.com`, `fonts.gstatic.com`) | La IP de cada visitante, en cada carga de página, sin consentimiento y sin base jurídica | 4-sep-2026 — las tipografías se sirven desde el propio dominio (`dashboard/public/fonts.css`) |
| **openpanel.dev** (script de terceros) | La IP de cada visitante antes de cualquier consentimiento | 4-sep-2026 — `op1.js` se sirve desde el propio dominio y solo tras aceptar |
| **Telegram Bot API** (Telegram FZ-LLC, Dubái, EAU) | **Direcciones de email de clientes** y títulos de vídeos, en las alertas operativas | 4-sep-2026 — las alertas identifican al usuario por los 8 primeros caracteres de su uuid y ya no citan títulos, de modo que Telegram deja de recibir datos personales. El canal sigue existiendo para alertas técnicas |
| **Telegram Bot API** (Telegram FZ-LLC, Dubái, EAU) | Direcciones de email de clientes y títulos de vídeos, en las alertas operativas | 4-sep-2026 — las alertas identifican al usuario por los 8 primeros caracteres de su uuid y ya no citan títulos |
## 7. Pendiente de verificación o firma
## 7. Pendiente de verificación o firma (para quien despliegue)
Nada de esto se puede hacer desde el repositorio; queda para el responsable:
Nada de esto se puede hacer desde el repositorio; queda para quien opera una
instancia:
1. **Confirmar que la `MANAGED_GEMINI_API_KEY` pertenece a un proyecto de
pago.** Los términos gratuitos de AI Studio permiten usar los datos para
mejorar los modelos, lo que haría falsa la frase "no se entrena con tu
contenido".
2. **Firmar y archivar** los DPA de ElevenLabs y Namecheap
(+ CCT). Guardar los PDF con fecha.
3. **Verificar la jurisdicción del bucket R2** (debe ser UE) y la región de S3.
4. **Identificar al proveedor de proxies estáticos** y el país de DataImpulse,
y firmar CCT si están fuera del EEE.
5. **Confirmar dónde están físicamente los dos servidores de producción.** La política dice
"Hetzner y Contabo, Alemania"; si alguno es hardware propio fuera de un CPD,
hay que decirlo y aplicar cifrado de disco.
6. **Comprobar que la instancia de Postiz** del usuario describe la custodia de
tokens de redes sociales; al ser autoalojada, no pasa por TONVI TECH SL.
1. **Usar una clave de Gemini de un proyecto de pago.** Los términos gratuitos de
AI Studio permiten usar los datos para mejorar los modelos, lo que haría falsa
la frase "no se entrena con tu contenido".
2. **Firmar y archivar** el DPA de ElevenLabs (+ CCT) si activas el doblaje.
Guarda los PDF con fecha.
3. **Identificar al proveedor de proxies estáticos** y el país de DataImpulse, y
firmar CCT si están fuera del EEE.
4. **Comprobar que tu instancia de Postiz** describe la custodia de tokens de
redes sociales; al ser autoalojada, no pasa por TONVI TECH SL.
5. **Sirve los emails de servicio** desde un proveedor con garantías si los
activas.
## Historial de cambios
| Fecha | Cambio |
|---|---|
| 2026-09-04 | Primera versión publicada. Altas documentadas (ya en uso, no listadas antes): fal.ai, Cloudflare CDN/DNS, Aikount, OpenPanel, proxies de descarga, Google OAuth. Bajas: Google Fonts, script de openpanel.dev y datos personales hacia Telegram. |
| 2026-09-04 | Primera versión publicada. Altas documentadas: fal.ai, Cloudflare CDN/DNS, Aikount, OpenPanel, proxies de descarga, Google OAuth. Bajas: Google Fonts, script de openpanel.dev y datos personales hacia Telegram. |
| 2026-10-04 | Baja de fal.ai y de la galería pública UGC/imágenes de actor (función retirada). Sustitución de Upload-Post por una instancia de Postiz autoalojada por el usuario para la publicación en redes. |
| 2026-10-04 | Reformulado para la edición autoalojada: se eliminan la infraestructura alojada (Hetzner/Contabo, Cloudflare R2/CDN), los pagos (Stripe, Aikount), el correo gestionado (Namecheap) y el inicio de sesión con Google. El usuario es el responsable del tratamiento. |

View file

@ -577,13 +577,6 @@ def shape_result(mode: str, data: dict) -> dict:
def _gemini_key():
try:
from cloud import managed_keys
key = managed_keys.gemini_key()
if key:
return key
except Exception:
pass
return os.environ.get("GEMINI_API_KEY", "").strip() or None

View file

@ -1,120 +0,0 @@
"""Cloud-facing job log view.
Self-hosted instances see the raw pipeline output (useful for debugging).
Cloud/paying users get a curated, whitelist-based view: friendly progress
lines only — no file paths, model names, encoder details or pipeline
internals. Anything not matched by a rule is hidden.
Progress (download %, transcription %) updates ITS OWN line instead of
adding one per step, so the view reads as a list of stages. Each line keeps
the time it first appeared.
"""
import re
# Strips any slashy path token (output/…/clip.mp4, /app/uploads/x.mp4, …).
_PATH_RE = re.compile(r'(?:/?[\w.\-]+/)+[\w.\-]+')
def _strip_paths(line):
return _PATH_RE.sub('', line).rstrip(' :')
# Ordered rules; first match wins: (pattern, template, progress kind).
# The template uses the match's groups, or None keeps the (path-stripped)
# line verbatim. A progress kind makes the line update in place.
_RULES = [
# Worker/job lifecycle + errors: keep, minus any paths.
(re.compile(r'^(Job started|Process finished|Process failed|'
r'Execution error|No metadata|❌)'), None, None),
(re.compile(r'Download attempt'), '📥 Downloading video…', 'download'),
(re.compile(r'\[download\]\s+(\d+)(?:\.\d+)?% of'), '📥 Downloading video… {0}%', 'download'),
(re.compile(r'downloading only the first (\d+) min'),
'✂️ Long video: downloading the first {0} min', None),
(re.compile(r'Video downloaded in'), '✅ Video downloaded', None),
(re.compile(r'Audio ready ahead of the video'),
'🎧 Audio ready — transcribing while the video downloads', None),
# Live transcription progress emitted by transcribe_backends.
(re.compile(r'Transcribing… (\d+)%'), '🎙️ Transcribing audio… {0}%', 'asr'),
(re.compile(r'Transcribing (video|audio)'), '🎙️ Transcribing audio…', 'asr'),
(re.compile(r'Analyzing with (?:Gemini|local LLM)'), '🤖 Finding the best moments…', None),
(re.compile(r'Silent video — analyzing'), '🎥 No speech — finding moments in the picture…', None),
(re.compile(r'Choosing a layout'), '🎛️ Choosing the layout…', None),
(re.compile(r'Found (\d+) (?:viral )?clips'), '🔥 Found {0} clips!', None),
(re.compile(r'Processing Clip (\d+)'), '🎬 Creating clip {0}…', None),
(re.compile(r'Clip (\d+) framed'), '🎞️ Clip {0} framed', None),
(re.compile(r'Clip (\d+) ready'), '✅ Clip {0} ready', None),
]
def _match(segment):
"""(text, kind) for one raw segment, or None to hide it."""
stripped = segment.strip()
if not stripped:
return None
for pattern, template, kind in _RULES:
match = pattern.search(stripped)
if match:
if template is None:
return _strip_paths(stripped), kind
return template.format(*match.groups()), kind
return None
def _segments(line):
"""A raw line can hold several outputs: yt-dlp redraws its progress bar
with \\r and no newline, so a parallel print lands on the same line."""
parts = []
for chunk in str(line).split('\r'):
# A print glued to the end of a progress bar: split before each emoji
# marker the pipeline starts its own lines with.
parts.extend(p for p in re.split(r'(?=🎙️|🎧|✅ Video downloaded)', chunk) if p)
return parts
def friendly_log_line(line):
"""Map one raw log line to its cloud-visible form, or None to hide it."""
for seg in _segments(line):
hit = _match(seg)
if hit:
return hit[0]
return None
def friendly_logs_timed(logs, times=None):
"""Curated (text, time) list for cloud users.
Consecutive duplicates collapse, and a progress line (download %,
transcription %) is updated in place instead of repeated; a line keeps the
time it first appeared. ``times`` is a list parallel to ``logs`` (epoch
seconds) or None.
"""
out = [] # [text, time]
live = {} # progress kind -> index in out still being updated
for i, line in enumerate(logs):
t = times[i] if times is not None and i < len(times) else None
for seg in _segments(line):
hit = _match(seg)
if not hit:
continue
text, kind = hit
if kind and kind in live:
out[live[kind]][0] = text
continue
if out and out[-1][0] == text:
continue
out.append([text, t])
# Any other line closes the running progress of other stages only
# when it is a new stage of the same kind; different kinds (the
# download and the early transcription) run side by side.
if kind:
live[kind] = len(out) - 1
elif text.startswith(('✅ Video downloaded', '✂️')):
live.pop('download', None)
elif text.startswith(('🔥', '🤖', '🎥')):
live.pop('asr', None)
return [(text, t) for text, t in out]
def friendly_logs(logs):
"""Curated log list for cloud users (see friendly_logs_timed)."""
return [text for text, _t in friendly_logs_timed(logs)]

View file

@ -842,7 +842,7 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
# signed links; refresh through the host's page so yt-dlp gets the file.
import file_hosts
url = file_hosts.resolve(url)
# Cloud mode rejects these at the probe; this is the self-host path.
# Reject non-video YouTube links before the download starts.
from yt_clients import NotASingleVideo, youtube_non_video_reason
reason = youtube_non_video_reason(url)
if reason:
@ -1080,8 +1080,7 @@ def download_youtube_video(url, output_dir=".", on_audio=None):
last_err = None
used_proxy = False
# Every attempt, with its bytes and failure text: printed as PROXY_ROUTE=
# below so app.py can keep a durable trail of WHY a job reached the paid
# proxy (the container log rotates within the hour; see cloud/proxy_ledger).
# below, which app.py swallows so it never reaches the user's job log.
attempt_log = []
for label, ea, fmt, proxy, cookies in attempts:
# A 403 on the media fetch is usually transient: the googlevideo URL is
@ -1575,7 +1574,7 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
# Global tracker for single-person shots
speaker_tracker = SpeakerTracker(cooldown_frames=30)
# Per-stage wall time (server-side diagnostics; hidden from cloud logs).
# Per-stage wall time (server-side diagnostics).
stage_seconds = {'detect': 0.0, 'write': 0.0}
loop_started = time.time()
@ -1699,7 +1698,7 @@ TRANSCRIPT_CHECKPOINT = ".transcript_checkpoint.json"
def _checkpoint_source_key(input_video, duration):
"""What ties a checkpoint to ONE source. Not the path: a resumed cloud job
"""What ties a checkpoint to ONE source. Not the path: a resumed job
re-downloads to the same name, and the CLI may be pointed at a different
file in a directory where an earlier run died. Name plus duration is what
both the server and a careful CLI user keep stable across the two runs."""

View file

@ -7,8 +7,7 @@ clips: the ``.resume.json`` manifest (which carries the customer's own
deploy marker, the face crops under ``thumbnails/`` and every actor photo a user
had uploaded. ``app.py`` now serves those two prefixes through real handlers
that ask who is calling; this module is the part of that with no FastAPI in it,
so both ``app.py`` and ``mcp_server.py`` can sign a URL without importing each
other.
so the URL-signing call sites in ``app.py`` need no FastAPI import.
Two token shapes, because there are two kinds of consumer:

View file

@ -1,12 +0,0 @@
# 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
dnspython==2.7.0

View file

@ -4,7 +4,7 @@
"description": "Turn long videos (podcasts, webinars, streams) into vertical 9:16 clips with subtitles, re-cut them, and publish them to TikTok, Instagram Reels and YouTube Shorts through a self-hosted Postiz instance.",
"author": {
"name": "OpenShorts",
"url": "https://www.openshorts.app/"
"url": "https://github.com/mutonby/openshorts"
},
"homepage": "https://github.com/mutonby/openshorts/tree/main/skills/openshorts",
"repository": "https://github.com/mutonby/openshorts",

View file

@ -6,7 +6,7 @@ homepage: https://github.com/mutonby/openshorts
metadata:
openclaw:
emoji: "🎬"
primaryEnv: OPENSHORTS_API_KEY
primaryEnv: OPENSHORTS_API_URL
hermes:
category: media
tags: [video, clips, shorts, social-media, publishing, automation]
@ -29,8 +29,8 @@ One surface: the REST API. Point the skill at your self-hosted instance
Self-hosted instances are open by default: no API key is required, but you do
need a Gemini key, either in the server's environment or as an `X-Gemini-Key`
header. If a call returns 401/404 on `/api/me`, assume self-host or anonymous:
there is no minute quota to enforce.
header. There is no account and no minute quota to enforce; read the instance
settings from `GET /api/config` if you need to confirm them.
## The core loop

View file

@ -3,9 +3,3 @@ import sys
# Make the repo root importable so tests can import the app modules directly.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Tests always run the app in self-host (BYOK) mode. app.py freezes
# BILLING_ENABLED at import time and load_dotenv never overrides an existing
# variable, so this must be set here — before any test module imports app — or
# the suite's behavior would depend on the developer's personal .env.
os.environ["BILLING_ENABLED"] = "0"

View file

@ -1,200 +0,0 @@
"""Account erasure (cloud/account.py): the GDPR Art. 17 delete.
The one thing worth testing without a database is coverage. The endpoint tells
the user everything is gone, so any table holding their rows that the delete
list forgets turns that sentence into a false statement — and a table added a
year from now is exactly the kind of thing nobody remembers to add here.
"""
import hashlib
import os
from cloud import account
from cloud.database import Base
from cloud.models import AccountDeletion, User
def _tables_referencing_users():
"""Every table with a foreign key into ``users`` — the ground truth the
delete list has to keep up with."""
found = set()
for table in Base.metadata.tables.values():
for fk in table.foreign_keys:
if fk.column.table.name == User.__tablename__:
found.add(table.name)
return found
class TestCoverage:
def test_every_user_owned_table_is_erased(self):
listed = {m.__tablename__ for m in account.USER_OWNED_TABLES}
missing = _tables_referencing_users() - listed
assert not missing, (
f"{missing} reference users.id but are not erased on account "
f"deletion — add them to account.USER_OWNED_TABLES")
def test_children_are_deleted_before_their_parents(self):
# clip_expiry_warnings has an FK into user_videos, so deleting the
# videos first would trip that constraint.
order = [m.__tablename__ for m in account.USER_OWNED_TABLES]
assert order.index("clip_expiry_warnings") < order.index("user_videos")
def test_the_erasure_record_itself_is_not_erased(self):
# It has no FK to users on purpose (the row it would point at is gone),
# so it must not appear in the delete list either.
assert AccountDeletion not in account.USER_OWNED_TABLES
assert AccountDeletion.__tablename__ not in _tables_referencing_users()
class TestDeletionReason:
"""The reason outlives the account, so it must never carry free text."""
def test_the_ui_offers_exactly_the_reasons_the_server_accepts(self):
repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
card = open(os.path.join(
repo, "dashboard/src/components/DeleteAccountCard.jsx")).read()
for value in account.DELETION_REASONS:
assert f"'{value}'" in card, f"{value} is accepted but never offered"
def test_the_column_cannot_hold_a_typed_sentence(self):
# 32 chars is under every label in the list and far under anything a
# user could write, so a free-text regression fails loudly at the DB.
assert AccountDeletion.reason.type.length == 32
assert max(len(r) for r in account.DELETION_REASONS) <= 32
class TestEmailFingerprint:
def test_is_a_plain_sha256_of_the_normalised_address(self):
assert account.email_fingerprint("user@example.com") == \
hashlib.sha256(b"user@example.com").hexdigest()
def test_does_not_contain_the_address(self):
assert "user@example.com" not in account.email_fingerprint("user@example.com")
def test_survives_the_aliasing_the_account_key_ignores(self):
# Sign-up normalises Gmail dots and +tags, so the fingerprint has to
# match the same way or a deleted user could not be found by the
# address they actually typed.
assert account.email_fingerprint("Foo.Bar+news@gmail.com") == \
account.email_fingerprint("foobar@gmail.com")
def test_different_addresses_differ(self):
assert account.email_fingerprint("a@example.com") != \
account.email_fingerprint("b@example.com")
# --------------------------------------------------------------------------- #
# The endpoint's gates
# --------------------------------------------------------------------------- #
import asyncio # noqa: E402
import pytest # noqa: E402
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
class _FakeUser:
id = "11111111-1111-1111-1111-111111111111"
email = "owner@example.com"
@pytest.fixture
def client(monkeypatch):
"""The endpoint with authentication stubbed out.
Everything past the confirmation gate needs Postgres, so these cover only
what happens before it — which is the part that decides whether an account
gets destroyed.
"""
async def _fake_session_user(request):
return _FakeUser()
monkeypatch.setattr(account, "_session_user", _fake_session_user)
app = FastAPI()
app.include_router(account.router)
return TestClient(app, raise_server_exceptions=False)
def _delete(client, **body):
return client.request("DELETE", "/api/account", json=body)
class TestConfirmationGate:
def test_a_wrong_email_deletes_nothing(self, client):
r = _delete(client, confirm_email="someone.else@example.com")
assert r.status_code == 400
def test_an_empty_confirmation_deletes_nothing(self, client):
# The UI can render before /api/me resolves; an empty box must never
# read as agreement.
assert _delete(client, confirm_email="").status_code == 400
def test_a_missing_confirmation_deletes_nothing(self, client):
assert client.request("DELETE", "/api/account").status_code == 422
def test_the_right_email_gets_past_the_gate(self, client):
# No database here, so "past the gate" is anything but the 400/422 the
# cases above return. What matters is that it stopped rejecting.
assert _delete(client, confirm_email="owner@example.com").status_code \
not in (400, 422)
def test_the_gate_ignores_case_and_gmail_aliasing(self, client, monkeypatch):
# Sign-up normalises the address, so the stored one may not be what the
# user remembers typing.
class _Gmail(_FakeUser):
email = "foobar@gmail.com"
async def _fake(request):
return _Gmail()
monkeypatch.setattr(account, "_session_user", _fake)
assert _delete(client, confirm_email="Foo.Bar+news@GMAIL.com").status_code \
not in (400, 422)
class TestApiKeyAuth:
def test_an_api_key_cannot_delete_the_account_it_belongs_to(self):
# Not the stubbed fixture: this must be the real _session_user.
app = FastAPI()
app.include_router(account.router)
c = TestClient(app, raise_server_exceptions=False)
for headers in ({"Authorization": "Bearer osk_abc123"},
{"X-API-Key": "osk_abc123"}):
r = c.request("DELETE", "/api/account",
json={"confirm_email": "owner@example.com"},
headers=headers)
assert r.status_code == 403
class TestStripeCancel:
def test_an_already_cancelled_subscription_does_not_trap_the_user(self, monkeypatch):
"""Our row can say "active" long after Stripe stopped billing — a
cancellation made in the portal whose webhook never landed. If that
raised, the one account impossible to delete would be the one Stripe
already stopped charging."""
stripe = pytest.importorskip("stripe") # not in the minimal CI deps
class _Row:
stripe_subscription_id = "sub_gone"
status = "active"
plan = "starter"
class _Result:
def scalars(self):
return [_Row()]
class _Session:
async def execute(self, _stmt):
return _Result()
async def __aenter__(self):
return self
async def __aexit__(self, *_a):
return False
def _boom(_sid):
raise stripe.InvalidRequestError("No such subscription", None)
monkeypatch.setattr(account.database, "session", lambda: _Session())
monkeypatch.setattr(stripe.Subscription, "cancel", staticmethod(_boom))
assert asyncio.run(account._cancel_subscriptions("uid")) == "starter"

View file

@ -1,143 +0,0 @@
"""Local-disk purge on account erasure (app._purge_local_jobs_for_user).
Two failure modes matter here and neither shows up in a unit-free reading of
the code: erasing one user's files must not touch another's (the API is
multi-tenant, and the three stores record ownership three different ways), and
a session id or output_dir that walks out of the working directories must not
delete anything at all.
"""
import os
import pytest
import app
MINE = "aaaa-1111"
THEIRS = "bbbb-2222"
def _write(path, body="x"):
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
with open(path, "w") as f:
f.write(body)
@pytest.fixture
def workdir(tmp_path, monkeypatch):
"""A throwaway output/ + uploads/ tree, with the in-memory stores emptied.
app.py holds OUTPUT_DIR / UPLOAD_DIR as relative paths, so chdir is enough
to redirect every write the purge can make.
"""
monkeypatch.chdir(tmp_path)
os.makedirs("output/thumbnails", exist_ok=True)
os.makedirs("uploads", exist_ok=True)
monkeypatch.setattr(app, "jobs", {})
monkeypatch.setattr(app, "saas_jobs", {})
monkeypatch.setattr(app, "thumbnail_sessions", {})
return tmp_path
class TestClipJobs:
def test_erases_jobs_marked_with_an_owner_file(self, workdir):
# No in-memory record: this is a job recovered from disk after a restart.
_write("output/job1/.owner", MINE)
_write("output/job1/clip.mp4")
_write("uploads/job1_source.mp4")
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/job1")
assert not os.path.exists("uploads/job1_source.mp4")
def test_erases_in_memory_jobs_with_no_owner_file(self, workdir):
_write("output/job2/clip.mp4")
app.jobs["job2"] = {"user_id": MINE, "status": "completed"}
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/job2")
assert "job2" not in app.jobs
def test_leaves_another_users_jobs_alone(self, workdir):
_write("output/theirs/.owner", THEIRS)
_write("output/theirs/clip.mp4")
_write("uploads/theirs_source.mp4")
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("output/theirs/clip.mp4")
assert os.path.exists("uploads/theirs_source.mp4")
def test_leaves_unowned_self_host_jobs_alone(self, workdir):
# BYOK jobs carry user_id=None; a str() comparison would match "None".
_write("output/anon/clip.mp4")
app.jobs["anon"] = {"user_id": None, "status": "completed"}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("output/anon/clip.mp4")
class TestOtherStores:
def test_erases_saasshorts_output(self, workdir):
_write("output/saas_s1/final.mp4")
app.saas_jobs["s1"] = {"user_id": MINE, "output_dir": "output/saas_s1"}
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/saas_s1")
assert "s1" not in app.saas_jobs
def test_erases_generated_thumbnails_and_their_source(self, workdir):
# Nothing else ever deletes these: the hourly sweep skips the whole
# thumbnails directory, and they are served publicly at /thumbnails/.
_write("output/thumbnails/t1/thumb.png")
_write("uploads/thumb_t1_video.mp4")
app.thumbnail_sessions["t1"] = {
"user_id": MINE, "video_path": "uploads/thumb_t1_video.mp4"}
app._purge_local_jobs_for_user(MINE)
assert not os.path.exists("output/thumbnails/t1")
assert not os.path.exists("uploads/thumb_t1_video.mp4")
assert "t1" not in app.thumbnail_sessions
def test_leaves_another_users_thumbnails_alone(self, workdir):
_write("output/thumbnails/t2/thumb.png")
app.thumbnail_sessions["t2"] = {"user_id": THEIRS}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("output/thumbnails/t2/thumb.png")
def test_keeps_the_thumbnails_directory_itself(self, workdir):
# It backs a StaticFiles mount; removing it 500s every /thumbnails
# request until the process restarts.
_write("output/thumbnails/t1/thumb.png")
app.thumbnail_sessions["t1"] = {"user_id": MINE}
app._purge_local_jobs_for_user(MINE)
assert os.path.isdir("output/thumbnails")
class TestPathTraversal:
def test_a_poisoned_session_id_deletes_nothing(self, workdir):
_write("secret.txt", "keep me")
app.thumbnail_sessions["../../secret.txt"] = {"user_id": MINE}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("secret.txt")
def test_a_poisoned_output_dir_deletes_nothing(self, workdir):
_write("secret.txt", "keep me")
app.saas_jobs["evil"] = {
"user_id": MINE, "output_dir": "output/../../secret.txt"}
app._purge_local_jobs_for_user(MINE)
assert os.path.exists("secret.txt")

View file

@ -1,171 +0,0 @@
"""Agent uploads (POST/PUT /api/uploads -> process with upload_id) and the
per-job captions switch, through the MCP transport where the agent uses them."""
import asyncio
import os
import shutil
import subprocess
import httpx
import pytest
app_module = pytest.importorskip("app")
def _client():
transport = httpx.ASGITransport(app=app_module.app)
return httpx.AsyncClient(transport=transport, base_url="http://testserver",
headers={"X-Gemini-Key": "test-key"})
def _mcp(tool, arguments):
async def _do():
async with _client() as c:
return await c.post("/mcp", json={"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": tool, "arguments": arguments}})
return asyncio.run(_do())
def _tool_payload(resp):
import json
return json.loads(resp.json()["result"]["content"][0]["text"])
@pytest.fixture()
def dirs(tmp_path, monkeypatch):
out_root = tmp_path / "output"; up_root = tmp_path / "uploads"
out_root.mkdir(); up_root.mkdir()
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
monkeypatch.setattr(app_module, "UPLOAD_DIR", str(up_root))
# Never spawn main.py: capture the job instead.
captured = {}
async def fake_enqueue(*a, **k):
captured["args"] = a; captured["kwargs"] = k
monkeypatch.setattr(app_module, "_media_duration_seconds", lambda p: 120.0)
return out_root, up_root, captured
def test_create_upload_is_an_mcp_tool():
names = [t["name"] for t in __import__("mcp_server").TOOLS]
assert "create_upload" in names
pv = next(t for t in __import__("mcp_server").TOOLS if t["name"] == "process_video")
assert "upload_id" in pv["inputSchema"]["properties"]
assert "captions" in pv["inputSchema"]["properties"]
assert "source_url" not in pv["inputSchema"]["required"]
def test_process_video_needs_a_source():
payload = _tool_payload(_mcp("process_video", {"confirm_rights": True}))
assert "source_url" in payload["error"] and "upload_id" in payload["error"]
def test_put_then_process_with_upload_id_and_captions_off(dirs, monkeypatch):
out_root, up_root, _ = dirs
slot = _tool_payload(_mcp("create_upload", {"filename": "../talk.mp4"}))
assert slot["upload_url"].endswith(f"/api/uploads/{slot['upload_id']}")
assert "talk.mp4" in app_module.pending_uploads[slot["upload_id"]]["path"]
assert ".." not in os.path.basename(app_module.pending_uploads[slot["upload_id"]]["path"])
async def _put(body):
async with _client() as c:
return await c.put(f"/api/uploads/{slot['upload_id']}", content=body)
assert asyncio.run(_put(b"")).status_code == 400
resp = asyncio.run(_put(b"\x00" * 5000))
assert resp.status_code == 200 and resp.json()["bytes"] == 5000
# Intercept the job instead of running main.py.
started = {}
async def fake_put(item):
started["job"] = item
monkeypatch.setattr(app_module.job_queue, "put", fake_put)
payload = _tool_payload(_mcp("process_video", {
"upload_id": slot["upload_id"], "confirm_rights": True, "captions": False}))
assert "job_id" in payload, payload
job = app_module.jobs[payload["job_id"]]
assert job["env"]["AUTO_CAPTIONS"] == "0"
assert slot["upload_id"] not in app_module.pending_uploads
input_path = job["cmd"][job["cmd"].index("-i") + 1]
assert os.path.exists(input_path) and input_path.startswith(str(up_root))
def test_captions_default_leaves_env_alone(dirs, monkeypatch):
slot = _tool_payload(_mcp("create_upload", {}))
async def _put():
async with _client() as c:
return await c.put(f"/api/uploads/{slot['upload_id']}", content=b"x" * 100)
assert asyncio.run(_put()).status_code == 200
async def fake_put(item): pass
monkeypatch.setattr(app_module.job_queue, "put", fake_put)
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True}))
env = app_module.jobs[payload["job_id"]]["env"]
assert "AUTO_CAPTIONS" not in env
assert env["AUTO_HOOK"] == "1" # MCP default matches the dashboard
def test_unknown_or_unfinished_upload_id(dirs):
async def _put():
async with _client() as c:
return await c.put("/api/uploads/nope", content=b"x")
assert asyncio.run(_put()).status_code == 404
slot = _tool_payload(_mcp("create_upload", {}))
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True}))
assert "PUT" in payload["error"]
def test_sweep_expires_old_slots(dirs, monkeypatch):
slot = _tool_payload(_mcp("create_upload", {}))
path = app_module.pending_uploads[slot["upload_id"]]["path"]
open(path, "wb").write(b"x")
assert slot["upload_id"] not in app_module._sweep_pending_uploads(now=__import__("time").time() + 1)
gone = app_module._sweep_pending_uploads(now=__import__("time").time() + app_module.UPLOAD_TTL_SECONDS + 1)
assert slot["upload_id"] in gone and not os.path.exists(path)
def test_delete_upload(dirs):
slot = _tool_payload(_mcp("create_upload", {}))
async def _del():
async with _client() as c:
return await c.delete(f"/api/uploads/{slot['upload_id']}")
assert asyncio.run(_del()).status_code == 200
assert slot["upload_id"] not in app_module.pending_uploads
def test_tmpfiles_link_is_refreshed_through_the_page():
import file_hosts
stale = "https://tmpfiles.org/dl/1787841143.abc/wAwNGnPW0lXW/video.mp4"
fresh = "https://tmpfiles.org/dl/1787841582.def/wAwNGnPW0lXW/video.mp4"
seen = {}
def fetch(url):
seen["page"] = url
return f'<a href="{fresh}">Download</a>'
assert file_hosts.resolve_tmpfiles(stale, fetch=fetch) == fresh
assert seen["page"] == "https://tmpfiles.org/wAwNGnPW0lXW/video.mp4"
assert file_hosts.resolve_tmpfiles("https://tmpfiles.org/wAwNGnPW0lXW/video.mp4", fetch=fetch) == fresh
assert file_hosts.resolve_tmpfiles(stale, fetch=lambda u: "<html>no link</html>") == stale
assert not file_hosts.is_tmpfiles("https://youtube.com/watch?v=x")
def test_auto_hook_reaches_the_job_env(dirs, monkeypatch):
slot = _tool_payload(_mcp("create_upload", {}))
async def _put():
async with _client() as c:
return await c.put(f"/api/uploads/{slot['upload_id']}", content=b"x" * 100)
assert asyncio.run(_put()).status_code == 200
async def fake_put(item): pass
monkeypatch.setattr(app_module.job_queue, "put", fake_put)
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True,
"auto_hook": True, "hook_style": "yellow"}))
env = app_module.jobs[payload["job_id"]]["env"]
assert env["AUTO_HOOK"] == "1" and env["AUTO_HOOK_STYLE"] == "yellow"
def test_auto_hook_false_opts_out(dirs, monkeypatch):
slot = _tool_payload(_mcp("create_upload", {}))
async def _put():
async with _client() as c:
return await c.put(f"/api/uploads/{slot['upload_id']}", content=b"x" * 100)
assert asyncio.run(_put()).status_code == 200
async def fake_put(item): pass
monkeypatch.setattr(app_module.job_queue, "put", fake_put)
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True, "auto_hook": False}))
assert "AUTO_HOOK" not in app_module.jobs[payload["job_id"]]["env"]

View file

@ -1,80 +0,0 @@
"""Failure classification for the high-failure-rate alert."""
from cloud.alerts import _classify_failure
def test_no_audio():
assert _classify_failure("❌ NO_AUDIO: This video has no audio track.") == "no audio"
def test_youtube_bot_block():
assert _classify_failure("ERROR: [youtube] x: Sign in to confirm you're not a bot") == "youtube download"
assert _classify_failure("HTTP Error 403: Forbidden") == "youtube download"
assert _classify_failure("HTTP Error 429: Too Many Requests") == "youtube download"
def test_proxy():
assert _classify_failure("cannot connect to proxy") == "proxy"
assert _classify_failure("402 payment required") == "proxy"
def test_transcription():
assert _classify_failure("File faster_whisper/audio.py IndexError") == "transcription"
assert _classify_failure("av/container/streams.py tuple index out of range") == "transcription"
def test_gemini():
assert _classify_failure("google.genai error 500") == "gemini"
def test_ffmpeg():
assert _classify_failure("ffmpeg failed during reframe") == "ffmpeg/render"
def test_unknown_is_mixed():
assert _classify_failure("something weird happened") == "mixed"
def test_blocked_content_is_not_reported_as_outage():
assert _classify_failure(
"🚫 Gemini blocked this video's content (PROHIBITED_CONTENT)."
) == "blocked content (user video)"
def test_no_usable_clips_is_not_reported_as_outage():
assert _classify_failure(
"RuntimeError: Clip detection failed — Gemini did not return usable clips for this video."
) == "no clips found (user video)"
# --- _job_error_text: which log lines feed the classifier -----------------------
def test_recovered_download_attempts_do_not_mask_the_terminal_error():
"""HD-direct fails on every job (banned server IP) and a later attempt
succeeds; that per-attempt noise must not turn a Gemini failure into a
'youtube download' alert (prod 20-ago)."""
import pytest
app_module = pytest.importorskip("app")
logs = [
"📥 Download attempt: HD-direct",
"⚠️ Download attempt 'HD-direct' failed: ERROR: [youtube] x: Video unavailable.",
"📥 Download attempt: HD-static1",
"✅ Download succeeded (HD-static1).",
"Traceback (most recent call last):",
"RuntimeError: Clip detection failed — Gemini did not return usable clips for this video.",
]
err = app_module._job_error_text(logs)
assert "Video unavailable" not in err
assert _classify_failure(err) == "no clips found (user video)"
def test_terminal_download_failure_still_classifies_as_download():
import pytest
app_module = pytest.importorskip("app")
logs = [
"⚠️ Download attempt 'HD-direct' failed: ERROR: [youtube] x: Video unavailable.",
"❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies)",
"Technical Details: ERROR: [youtube] x: Video unavailable. This content isn't available.",
"Process failed with exit code 1",
]
err = app_module._job_error_text(logs)
assert _classify_failure(err) == "youtube download"

View file

@ -1,42 +0,0 @@
"""API-key token semantics (cloud/api_keys.py).
The raw ``osk_`` value is shown once and only its sha256 is stored, so the
format and hashing rules are load-bearing: a drifting prefix would break
``looks_like_key`` routing in cloud/auth.py, and a non-deterministic hash would
lock every issued key out of the resolver.
"""
from cloud.api_keys import KEY_PREFIX, generate_key, hash_key, looks_like_key
class TestKeyGeneration:
def test_raw_key_carries_the_prefix(self):
raw, _hash, _prefix = generate_key()
assert raw.startswith(KEY_PREFIX)
def test_hash_matches_rehashing_the_raw_value(self):
raw, token_hash, _prefix = generate_key()
assert hash_key(raw) == token_hash
def test_display_prefix_is_a_prefix_of_the_raw_key(self):
raw, _hash, prefix = generate_key()
assert raw.startswith(prefix)
# Long enough to tell keys apart, short enough to be useless to guess.
assert len(prefix) < len(raw) / 3
def test_keys_are_unique(self):
assert generate_key()[0] != generate_key()[0]
def test_raw_key_has_enough_entropy(self):
raw, _hash, _prefix = generate_key()
assert len(raw) >= len(KEY_PREFIX) + 40 # token_urlsafe(32) ≈ 43 chars
class TestLooksLikeKey:
def test_accepts_generated_keys(self):
assert looks_like_key(generate_key()[0])
def test_rejects_jwts_and_junk(self):
assert not looks_like_key("eyJhbGciOiJIUzI1NiJ9.e30.abc")
assert not looks_like_key("")
assert not looks_like_key(None)
assert not looks_like_key(123)

View file

@ -6,8 +6,6 @@
- A metered whole-video URL job carries SOURCE_CAP_MINUTES = the reserved
minutes, in the job env and in the resume manifest.
- main.py and the probe get an environment without the server secrets.
- Thumbnail publish status, thumbnail generation and render status are
owner-only in cloud mode.
- The public /video/{id} page escapes everything it interpolates.
"""
import asyncio
@ -70,7 +68,7 @@ def calls(monkeypatch):
order_probe_result = [{"max_height": 1080, "duration": 600}]
monkeypatch.setattr(app_module, "_probe_youtube_quality", _probe)
monkeypatch.setattr(app_module, "reserve_process_minutes", _reserve)
monkeypatch.setattr(app_module, "_metering", _FakeMetering)
monkeypatch.setattr(app_module, "_metering", _FakeMetering, raising=False)
monkeypatch.setattr(app_module, "_validate_source_url", _allow_url)
return {"order": order, "released": released, "probe_result": order_probe_result}
@ -173,18 +171,30 @@ def test_resumed_job_keeps_its_safety_cap(dirs, monkeypatch):
# Subprocess environment
# --------------------------------------------------------------------------- #
def test_child_env_drops_server_secrets(monkeypatch):
for name in ("STRIPE_SECRET_KEY", "JWT_SECRET", "DATABASE_URL", "SMTP_PASSWORD",
"TELEGRAM_BOT_TOKEN", "AGENTLEDGER_API_KEY", "R2_SECRET_ACCESS_KEY",
"MANAGED_UPLOAD_POST_API_KEY", "GOOGLE_CLIENT_SECRET"):
# Every name in the current denylist is a server credential the yt-dlp /
# ffmpeg child has no business seeing; the pipeline's own config (cookies,
# proxies, Gemini key, encoder) must survive.
secrets = (
"DATABASE_URL", "POSTGRES_PASSWORD", "JWT_SECRET", "STRIPE_SECRET_KEY",
"STRIPE_WEBHOOK_SECRET", "SMTP_USER", "SMTP_PASSWORD",
"TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "GOOGLE_CLIENT_SECRET",
"AGENTLEDGER_API_KEY", "MANAGED_GEMINI_API_KEY", "POSTIZ_API_KEY",
"POSTIZ_URL", "R2_ACCESS_KEY_ID", "R2_SECRET_ACCESS_KEY",
"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "OPENPANEL_CLIENT_SECRET",
"ELEVENLABS_API_KEY",
)
keep = ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL")
for name in secrets:
monkeypatch.setenv(name, "secret")
for name in ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL"):
for name in keep:
monkeypatch.setenv(name, "keep")
env = app_module.child_env()
for name in app_module.CHILD_ENV_DENYLIST:
# Pin the list: a new server secret must be added here and to the denylist.
assert set(app_module.CHILD_ENV_DENYLIST) == set(secrets)
for name in secrets:
assert name not in env
for name in ("YOUTUBE_COOKIES", "PROXY_URL", "STATIC_PROXY_URLS", "GEMINI_API_KEY",
"BGUTIL_SCRIPT_PATH", "FFMPEG_ENCODER", "WHISPER_MODEL"):
for name in keep:
assert env[name] == "keep"
@ -210,7 +220,6 @@ def test_pipeline_code_reads_none_of_the_dropped_secrets():
elif isinstance(node, ast.ImportFrom) and node.module:
names = [node.module.split(".")[0]]
for n in names:
assert n != "cloud", f"{mod} imports cloud/, which reads server secrets"
if n in local:
stack.append(n)
@ -224,59 +233,6 @@ def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch):
assert env["GEMINI_API_KEY"] == "test-key"
# --------------------------------------------------------------------------- #
# Owner checks (cloud mode)
# --------------------------------------------------------------------------- #
class _User:
def __init__(self, uid):
self.id = uid
self.plan = "starter"
@pytest.fixture()
def cloud_as(monkeypatch):
who = {"user": None}
async def _from_request(request):
return who["user"]
monkeypatch.setattr(app_module, "BILLING_ENABLED", True)
monkeypatch.setattr(app_module, "_user_from_request", _from_request)
return who
def test_publish_status_is_owner_only(cloud_as, monkeypatch):
monkeypatch.setattr(app_module, "publish_jobs", {
"p1": {"status": "done", "result": {"ok": 1}, "error": None, "user_id": "owner"}})
cloud_as["user"] = _User("stranger")
assert _client_call("get", "/api/thumbnail/publish/status/p1").status_code == 404
cloud_as["user"] = None
assert _client_call("get", "/api/thumbnail/publish/status/p1").status_code == 404
cloud_as["user"] = _User("owner")
resp = _client_call("get", "/api/thumbnail/publish/status/p1")
assert resp.status_code == 200
assert resp.json() == {"status": "done", "result": {"ok": 1}, "error": None}
def test_render_status_is_owner_only(cloud_as, monkeypatch):
monkeypatch.setattr(app_module, "_render_owners", {"r-1": "owner"})
cloud_as["user"] = _User("stranger")
assert _client_call("get", "/api/render/r-1").status_code == 404
# An id this instance never issued is not proxied at all.
cloud_as["user"] = _User("owner")
assert _client_call("get", "/api/render/unknown-id").status_code == 404
def test_thumbnail_generate_refuses_someone_elses_session(cloud_as, monkeypatch):
async def _gemini(request):
return "k"
monkeypatch.setattr(app_module, "resolve_gemini", _gemini)
monkeypatch.setattr(app_module, "thumbnail_sessions", {"s-1": {"user_id": "owner"}})
cloud_as["user"] = _User("stranger")
resp = _client_call("post", "/api/thumbnail/generate",
data={"session_id": "s-1", "title": "t"})
assert resp.status_code == 404
# --------------------------------------------------------------------------- #
# /video/{id} escaping
# --------------------------------------------------------------------------- #

View file

@ -6,7 +6,6 @@ Users saw "failed" for problems that were entirely ours.
"""
import asyncio
import json
import os
import pytest
@ -24,20 +23,14 @@ def env(tmp_path, monkeypatch):
monkeypatch.setattr(app_module, "_running_jobs", set())
monkeypatch.setattr(app_module, "jobs", {})
monkeypatch.setattr(app_module, "AUTO_RETRY_DELAY_SECONDS", 0)
calls = {"settled": [], "enqueued": []}
calls = {"enqueued": []}
async def fake_settle(job_id, job=None):
calls["settled"].append(job_id)
for name in ("_archive_managed_job", "_notify_job_webhook", "_record_job_alert",
"_track_proxy_usage", "_notify_clips_ready", "_notify_clip_activity"):
async def _noop(*a, **k):
return None
monkeypatch.setattr(app_module, name, _noop)
monkeypatch.setattr(app_module, name, _noop, raising=False)
async def _noop2(*a, **k):
return None
monkeypatch.setattr(app_module, "_autopilot_job_finished", _noop2)
monkeypatch.setattr(app_module, "_settle_reservation", fake_settle)
monkeypatch.setattr(app_module, "_enqueue_job",
lambda job_id, priority=2: calls["enqueued"].append((job_id, priority)))
return root, calls
@ -108,7 +101,6 @@ class TestWrapper:
sem = _run_wrapper(monkeypatch, "j1", "failed")
assert job["status"] == "queued" and job["auto_retries"] == 1
assert calls["enqueued"] == [("j1", 1)]
assert calls["settled"] == [] # reservation kept
assert (d / app_module._RESUME_FILE).exists() # still resumable
assert (d / "My_Video.mp4").exists() and (d / ".transcript_checkpoint.json").exists()
assert not (d / "My_Video_clip_1.mp4").exists()
@ -121,7 +113,7 @@ class TestWrapper:
job["auto_retries"] = 1
_run_wrapper(monkeypatch, "j2", "failed")
assert job["status"] == "failed"
assert calls["settled"] == ["j2"] and calls["enqueued"] == []
assert calls["enqueued"] == []
assert not (d / app_module._RESUME_FILE).exists()
def test_content_failure_is_not_retried(self, env, monkeypatch):
@ -131,10 +123,9 @@ class TestWrapper:
assert job["status"] == "failed" and calls["enqueued"] == []
def test_shutdown_leaves_the_job_for_the_next_instance(self, env, monkeypatch):
root, calls = env
root, _ = env
d, job = _job(root, "j4", [])
sem = _run_wrapper(monkeypatch, "j4", None, raise_cancel=True)
assert calls["settled"] == [] # no refund, no failure
assert (d / app_module._RESUME_FILE).exists()
assert sem._value == 1

View file

@ -1,144 +0,0 @@
"""Autopilot (cloud/autopilot.py): the decisions that run without a person.
Everything here fires on its own schedule and spends the user's minutes, so
the pure rules are pinned down: which channel videos get picked, which clips
get published and when, and how each /api/process answer is recorded.
"""
from datetime import datetime, timedelta, timezone
from cloud import autopilot as ap
NOW = datetime(2026, 9, 22, 18, 0, tzinfo=timezone.utc)
def _video(vid, hours_ago):
ts = (NOW - timedelta(hours=hours_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
return {"id": vid, "timestamp": ts, "permalink": f"https://www.youtube.com/watch?v={vid}"}
class TestPickNewVideos:
def test_only_videos_after_the_baseline(self):
baseline = NOW - timedelta(hours=5)
media = [_video("old", 10), _video("new", 2)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, set(), NOW)] == ["new"]
def test_switching_on_never_picks_the_back_catalogue(self):
media = [_video("a", 1), _video("b", 30)]
assert ap.pick_new_videos(media, NOW, set(), NOW) == []
def test_no_baseline_means_nothing(self):
assert ap.pick_new_videos([_video("a", 1)], None, set(), NOW) == []
def test_already_seen_videos_are_skipped(self):
baseline = NOW - timedelta(days=1)
media = [_video("a", 1), _video("b", 2)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, {"a"}, NOW)] == ["b"]
def test_too_old_even_if_after_baseline(self):
baseline = NOW - timedelta(days=30)
media = [_video("stale", 24 * 5), _video("fresh", 3)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, set(), NOW)] == ["fresh"]
def test_oldest_first(self):
baseline = NOW - timedelta(days=2)
media = [_video("newest", 1), _video("older", 20), _video("middle", 8)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, set(), NOW)] == \
["older", "middle", "newest"]
def test_items_without_id_or_timestamp_are_ignored(self):
baseline = NOW - timedelta(days=1)
media = [{"id": "x"}, {"timestamp": "2026-09-22T17:00:00Z"}, {"id": "y", "timestamp": "garbage"}]
assert ap.pick_new_videos(media, baseline, set(), NOW) == []
class TestRankClips:
def test_best_scores_first(self):
clips = [{"predicted_score": 40}, {"predicted_score": 90}, {"predicted_score": 70}]
assert ap.rank_clips(clips, 2) == [1, 2]
def test_unscored_clips_keep_order_after_scored(self):
clips = [{}, {"predicted_score": "55"}, {}, {"predicted_score": None}]
assert ap.rank_clips(clips, 4) == [1, 0, 2, 3]
def test_n_larger_than_clips(self):
assert ap.rank_clips([{"predicted_score": 1}], 3) == [0]
def test_zero(self):
assert ap.rank_clips([{"predicted_score": 1}], 0) == []
class TestScheduleSlots:
def test_one_a_day_at_the_hour(self):
now = datetime(2026, 9, 22, 8, 0, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 3, hour=17) == [
"2026-09-22T17:00:00", "2026-09-23T17:00:00", "2026-09-24T17:00:00"]
def test_starts_tomorrow_when_the_slot_is_under_an_hour_away(self):
now = datetime(2026, 9, 22, 16, 30, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 1, hour=17) == ["2026-09-23T17:00:00"]
def test_local_timezone(self):
# 08:00 UTC is 10:00 in Madrid (CEST): 17:00 local is still today.
now = datetime(2026, 9, 22, 8, 0, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 1, hour=17, tz_name="Europe/Madrid") == ["2026-09-22T17:00:00"]
def test_unknown_timezone_falls_back_to_utc(self):
now = datetime(2026, 9, 22, 8, 0, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 1, hour=17, tz_name="Not/AZone") == ["2026-09-22T17:00:00"]
class TestOutcomeFromProcess:
def test_job_started(self):
o = ap.outcome_from_process(200, {"job_id": "j1", "status": "queued"})
assert o == {"status": "processing", "reason": None, "job_id": "j1", "retry": False}
def test_quality_gate_is_a_skip(self):
assert ap.outcome_from_process(200, {"needs_confirmation": True})["reason"] == "low_quality"
def test_out_of_minutes_is_a_skip(self):
o = ap.outcome_from_process(402, {"detail": {"error": "quota_exceeded"}})
assert (o["status"], o["reason"], o["retry"]) == ("skipped", "out_of_minutes", False)
def test_job_limit_is_retried_later(self):
o = ap.outcome_from_process(429, {"detail": "max jobs"})
assert o["retry"] is True and o["reason"] == "busy"
def test_short_source(self):
detail = ("This video is only 40s long — clip generation needs at least 45s "
"of material to cut from. It already is short-form content.")
assert ap.outcome_from_process(400, {"detail": detail})["reason"] == "too_short"
def test_other_400_is_unavailable(self):
o = ap.outcome_from_process(400, {"detail": "Could not determine the video duration."})
assert (o["status"], o["reason"]) == ("skipped", "unavailable")
def test_server_error_is_retried(self):
assert ap.outcome_from_process(502, "not json")["retry"] is True
class TestSmallRules:
def test_platforms_are_filtered_and_ordered(self):
assert ap.clean_platforms(["YouTube", "facebook", "tiktok"]) == ["tiktok", "youtube"]
assert ap.clean_platforms(None) == []
def test_only_paid_plans_are_eligible(self):
class U:
def __init__(self, plan, entitled=True):
self.plan, self.entitled = plan, entitled
assert ap.eligible(U("starter"))
assert ap.eligible(U("pro"))
assert not ap.eligible(U("free"))
assert not ap.eligible(U(None))
assert not ap.eligible(U("creator", entitled=False))
assert not ap.eligible(None)
def test_parse_ts(self):
assert ap.parse_ts("2026-09-22T10:01:35Z") == datetime(2026, 9, 22, 10, 1, 35, tzinfo=timezone.utc)
assert ap.parse_ts("nope") is None
assert ap.parse_ts(None) is None
def test_connect_return_targets_are_a_closed_list():
from cloud import social_profiles
assert set(social_profiles.RETURN_TARGETS) == {"account", "autopilot"}
assert all(v.startswith("/#") for v in social_profiles.RETURN_TARGETS.values())

View file

@ -1,93 +0,0 @@
"""Subscription-state gates: who is entitled, who is blocked from checkout, and
who must still be able to reach the billing portal.
Regression cover for the past_due dead end found in prod on 25-jul-2026: a
customer whose card was declined read as a plain free account (no warning, no
portal button) AND was blocked from starting a new checkout — no way out.
"""
from datetime import datetime, timezone, timedelta
from types import SimpleNamespace
import pytest
from cloud import config, metering
def _sub(status="active", period_end=None):
return SimpleNamespace(
status=status,
current_period_end=period_end or (datetime.now(timezone.utc) + timedelta(days=20)),
)
class TestEntitles:
"""Only a live subscription inside its period grants plan minutes."""
@pytest.mark.parametrize("status", ["active", "trialing"])
def test_live_states_entitle(self, status):
assert metering._entitles(_sub(status)) is True
@pytest.mark.parametrize("status", [
"past_due", "unpaid", "incomplete", "paused", "canceled", "incomplete_expired",
])
def test_everything_else_does_not_entitle(self, status):
assert metering._entitles(_sub(status)) is False
def test_expired_period_does_not_entitle(self):
past = datetime.now(timezone.utc) - timedelta(days=1)
assert metering._entitles(_sub("active", period_end=past)) is False
def test_no_subscription_does_not_entitle(self):
assert metering._entitles(None) is False
class TestCheckoutBlockingStates:
"""Block only while Stripe is actually trying to collect."""
@pytest.mark.parametrize("status", ["active", "trialing", "past_due", "unpaid", "paused"])
def test_dunning_or_live_blocks_a_second_subscription(self, status):
assert status in config.CHECKOUT_BLOCKING_STATES
def test_incomplete_does_not_block_the_retry(self):
# Payment abandoned at 3DS/confirm. Nothing is being collected and Stripe
# expires the row within 24h, so blocking only stops the user paying.
assert "incomplete" not in config.CHECKOUT_BLOCKING_STATES
@pytest.mark.parametrize("status", ["canceled", "incomplete_expired"])
def test_terminal_states_do_not_block(self, status):
assert status not in config.CHECKOUT_BLOCKING_STATES
class TestAttentionStates:
"""States the account page must surface so the customer can act."""
@pytest.mark.parametrize("status", ["past_due", "unpaid", "incomplete", "paused"])
def test_broken_payment_is_visible(self, status):
assert status in config.BILLING_ATTENTION_STATES
@pytest.mark.parametrize("status", ["canceled", "incomplete_expired"])
def test_terminal_states_are_not_nagged_about(self, status):
assert status not in config.BILLING_ATTENTION_STATES
def test_none_of_them_entitle_minutes(self):
# The whole point: these look like "free" to the metering layer, which is
# why they have to be reported separately or they vanish from the UI.
for status in config.BILLING_ATTENTION_STATES:
assert metering._entitles(_sub(status)) is False
def test_every_blocking_state_is_either_live_or_flagged(self):
# A state that blocks checkout but is invisible in /api/me would recreate
# the dead end, so the two sets must stay reconciled.
for status in config.CHECKOUT_BLOCKING_STATES:
assert status in ("active", "trialing") or status in config.BILLING_ATTENTION_STATES
class TestNewSubscriberAlert:
"""The 'New subscriber' admin alert must mean money, not a click on pay."""
def test_incomplete_is_silent(self):
assert config.new_subscriber_label("incomplete") is None
@pytest.mark.parametrize("status", ["active", "trialing"])
def test_paid_states_alert(self, status):
assert config.new_subscriber_label(status)

View file

@ -1,228 +0,0 @@
"""The dashboard cancel flow (cloud/cancellation.py): reason + review, then a
cancel at period end.
What must hold: nothing is recorded unless Stripe accepted the cancel, the
reason reaches Stripe in its own vocabulary, the free text never reaches the
Telegram alert, and the UI offers exactly the reasons the server accepts.
"""
import asyncio
import os
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from cloud import alerts, cancellation
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class _Result:
def __init__(self, value):
self.value = value
def scalar_one_or_none(self):
return self.value
class _Session:
def __init__(self, sub, added):
self.sub, self.added = sub, added
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
def begin(self):
return self
async def execute(self, _stmt):
return _Result(self.sub)
def add(self, obj):
self.added.append(obj)
@pytest.fixture
def env(monkeypatch):
sub = SimpleNamespace(
id="sub-row", stripe_subscription_id="sub_123", plan="creator", interval="month",
status="active", cancel_at_period_end=False,
current_period_end=datetime.now(timezone.utc) + timedelta(days=12),
)
state = SimpleNamespace(sub=sub, added=[], stripe_calls=[], alerts=[], stripe_error=None)
user = SimpleNamespace(id="3f9a1c2b-0000-0000-0000-000000000000")
async def _user(_request):
return user
def _modify(sid, feedback, comment):
if state.stripe_error:
raise state.stripe_error
state.stripe_calls.append((sid, feedback, comment))
async def _alert(subject, body):
state.alerts.append((subject, body))
monkeypatch.setattr(cancellation, "get_current_user_required", _user)
monkeypatch.setattr(cancellation.database, "session", lambda: _Session(state.sub, state.added))
monkeypatch.setattr(cancellation, "_stripe_cancel_at_period_end", _modify)
monkeypatch.setattr(cancellation, "RETENTION_COUPON", "coupon_test")
state.offer_blocked = False
state.applied = []
state.resumed = []
monkeypatch.setattr(cancellation, "_stripe_offer_blocked", lambda sid: state.offer_blocked)
monkeypatch.setattr(cancellation, "_stripe_coupon_terms",
lambda cid: {"percent_off": 50, "months": 3})
monkeypatch.setattr(cancellation, "_stripe_apply_retention",
lambda sid, cid: state.applied.append((sid, cid)))
monkeypatch.setattr(cancellation, "_stripe_resume", lambda sid: state.resumed.append(sid))
monkeypatch.setattr(cancellation.analytics, "track", lambda *a, **k: None)
monkeypatch.setattr(alerts, "send_admin_alert", _alert)
return state
def _cancel(**body):
body.setdefault("reason", "too_expensive")
return asyncio.run(cancellation.cancel_subscription(
cancellation.CancelRequest(**body), request=None))
class TestCancel:
def test_cancels_at_period_end_with_the_reason_in_stripe_terms(self, env):
out = _cancel(reason="clip_quality", details="blurry", rating=2, review="meh")
assert out["ok"]
assert env.stripe_calls == [("sub_123", "low_quality", "blurry | meh")]
assert env.sub.cancel_at_period_end is True
def test_feedback_row_is_stored(self, env):
_cancel(reason="missing_feature", details=" ", rating=4, review="good",
review_public_ok=True)
(row,) = env.added
assert row.reason == "missing_feature"
assert row.details is None # whitespace is not feedback
assert row.rating == 4 and row.review == "good" and row.review_public_ok
def test_public_ok_without_a_review_is_not_recorded(self, env):
_cancel(rating=5, review_public_ok=True)
assert env.added[0].review_public_ok is False
def test_stripe_failure_records_nothing(self, env):
env.stripe_error = RuntimeError("stripe down")
with pytest.raises(HTTPException) as e:
_cancel()
assert e.value.status_code == 502
assert env.added == [] and env.alerts == []
assert env.sub.cancel_at_period_end is False
def test_unknown_reason_is_refused(self, env):
with pytest.raises(HTTPException) as e:
_cancel(reason="i hate it")
assert e.value.status_code == 422
assert env.stripe_calls == []
def test_already_canceling_is_refused(self, env):
env.sub.cancel_at_period_end = True
with pytest.raises(HTTPException) as e:
_cancel()
assert e.value.status_code == 409
@pytest.mark.parametrize("status", ["canceled", "incomplete", "incomplete_expired"])
def test_nothing_live_to_cancel(self, env, status):
env.sub.status = status
with pytest.raises(HTTPException) as e:
_cancel()
assert e.value.status_code == 409
def test_alert_never_carries_the_written_text(self, env):
_cancel(details="my name is Alice Smith", review="call me on 555-1234", rating=1)
(subject, body), = env.alerts
assert "Alice" not in body and "555" not in body
assert "3f9a1c2b" in body and "too_expensive" in body and "1/5" in body
def _offer():
return asyncio.run(cancellation.retention_offer(request=None))
def _accept(**body):
body.setdefault("reason", "too_expensive")
return asyncio.run(cancellation.accept_retention_offer(
cancellation.CancelRequest(**body), request=None))
class TestRetentionOffer:
def test_a_live_monthly_plan_gets_the_offer(self, env):
assert _offer() == {"eligible": True, "percent_off": 50, "months": 3}
@pytest.mark.parametrize("field,value", [
("interval", "year"), # would halve a whole year
("status", "trialing"),
("status", "past_due"), # a discount does not fix a failed card
])
def test_no_offer_outside_a_live_monthly_plan(self, env, field, value):
setattr(env.sub, field, value)
assert _offer() == {"eligible": False}
def test_no_second_offer_or_stacked_discount(self, env):
env.offer_blocked = True
assert _offer() == {"eligible": False}
with pytest.raises(HTTPException) as e:
_accept()
assert e.value.status_code == 409
assert env.applied == []
def test_a_stripe_hiccup_means_no_offer_not_a_broken_flow(self, env, monkeypatch):
def boom(_sid):
raise RuntimeError("stripe down")
monkeypatch.setattr(cancellation, "_stripe_offer_blocked", boom)
assert _offer() == {"eligible": False}
def test_taking_it_applies_the_coupon_and_keeps_the_feedback(self, env):
out = _accept(reason="not_using_it", details="busy month", rating=3)
assert out["ok"] and out["percent_off"] == 50
assert env.applied == [("sub_123", cancellation.RETENTION_COUPON)]
assert env.stripe_calls == [] # nothing was cancelled
assert env.sub.cancel_at_period_end is False
(row,) = env.added
assert row.outcome == "retained" and row.reason == "not_using_it"
(subject, body), = env.alerts
assert "busy month" not in body and "50% off" in body
def test_no_coupon_configured_no_offer(self, env, monkeypatch):
monkeypatch.setattr(cancellation, "RETENTION_COUPON", "")
assert _offer() == {"eligible": False}
def test_a_cancel_row_says_so(self, env):
_cancel()
assert env.added[0].outcome == "canceled"
class TestResume:
def test_undoes_a_scheduled_cancel(self, env):
env.sub.cancel_at_period_end = True
assert asyncio.run(cancellation.resume_subscription(request=None))["ok"]
assert env.resumed == ["sub_123"]
assert env.sub.cancel_at_period_end is False
def test_nothing_to_undo(self, env):
with pytest.raises(HTTPException) as e:
asyncio.run(cancellation.resume_subscription(request=None))
assert e.value.status_code == 409
assert env.resumed == []
class TestReasons:
def test_every_reason_maps_to_a_stripe_feedback_value(self):
stripe_enum = {"customer_service", "low_quality", "missing_features", "other",
"switched_service", "too_complex", "too_expensive", "unused"}
assert set(cancellation.CANCEL_REASONS.values()) <= stripe_enum
def test_the_ui_offers_exactly_the_reasons_the_server_accepts(self):
modal = open(os.path.join(REPO, "dashboard/src/components/CancelPlanModal.jsx")).read()
for value in cancellation.CANCEL_REASONS:
assert f"'{value}'" in modal, f"{value} is accepted but never offered"

View file

@ -1,4 +1,4 @@
"""Caption presets: the API, the MCP tool and the dashboard agree on them."""
"""Caption presets: the API and the dashboard agree on them."""
import asyncio
import re
@ -25,44 +25,6 @@ def test_line_budget_shrinks_with_size_and_wide_fonts():
assert line_budget("Montserrat ExtraBold", 44) < line_budget("Anton", 44)
class _FakeResp:
status_code = 200
def json(self):
return {"ok": True}
class _FakeClient:
def __init__(self):
self.body = None
async def post(self, path, json):
assert path == "/api/subtitle"
self.body = json
return _FakeResp()
def _call(**args):
from mcp_server import _tool_add_subtitles
client = _FakeClient()
asyncio.run(_tool_add_subtitles(client, {"job_id": "j", "clip_index": 0, **args}))
return client.body
def test_mcp_forwards_preset_and_new_options():
body = _call(preset="pill", reveal=True, shadow=2, effect="highlight")
assert body["preset"] == "pill"
assert (body["reveal"], body["shadow"], body["effect"]) == (True, 2, "highlight")
assert "max_chars" not in body # the preset's own budget applies
def test_mcp_one_word_and_resize_set_the_line_budget():
assert _call(one_word=True)["max_chars"] == 1
assert _call(font_size=70)["max_chars"] == line_budget("Anton", 70)
# Resizing the one-word preset keeps it one word.
assert "max_chars" not in _call(preset="oneword", font_size=56)
def test_unknown_preset_is_a_400():
import pytest
from fastapi import HTTPException

View file

@ -4,16 +4,14 @@
age-only sweep removed their dir (and source upload) under the worker. The
user got no clips and the minute reservation stayed held for 3 hours.
"""
import asyncio
import os
import time
import types
import pytest
app_module = pytest.importorskip("app")
OLD = 2 * 3600 # older than JOB_RETENTION_SECONDS in cloud (1 h)
OLD = 2 * 3600 # older than the 1 h JOB_RETENTION_SECONDS the fixture sets
@pytest.fixture
@ -128,24 +126,3 @@ class TestUploadSweep:
monkeypatch.setattr(app_module, "UPLOADS_MAX_GB", 1 / 1024 ** 3)
app_module._enforce_uploads_size_cap()
assert live.exists() and not dead.exists()
class TestSettleWithoutEntry:
def test_reservation_released_when_entry_vanished(self, monkeypatch):
calls = []
class FakeMetering:
@staticmethod
async def commit_reservation(rid):
calls.append(("commit", rid))
@staticmethod
async def release_reservation(rid):
calls.append(("release", rid))
monkeypatch.setattr(app_module, "BILLING_ENABLED", True)
monkeypatch.setattr(app_module, "cloud", types.SimpleNamespace(metering=FakeMetering), raising=False)
monkeypatch.setattr(app_module, "jobs", {})
job = {"status": "processing", "reservation_id": "res-1"}
asyncio.run(app_module._settle_reservation("gone", job))
assert calls == [("release", "res-1")]

View file

@ -1,155 +0,0 @@
"""Disposable-domain blocking, email alias normalization and MX verification."""
import asyncio
import pytest
from cloud import email_policy as ep
class TestDisposable:
def test_known_temp_mail_blocked(self):
assert ep.is_disposable("x@mailinator.com") is True
assert ep.is_disposable("y@10minutemail.com") is True
def test_db_observed_domains_blocked(self):
assert ep.is_disposable("a@luckfeed.com") is True
assert ep.is_disposable("b@web-library.net") is True
assert ep.is_disposable("c@onldm.net") is True
def test_real_providers_allowed(self):
for e in ("real@gmail.com", "u@outlook.com", "u@icloud.com", "u@yandex.ru"):
assert ep.is_disposable(e) is False
def test_case_insensitive(self):
assert ep.is_disposable("X@MailInator.CoM") is True
def test_list_loaded(self):
assert ep.disposable_count() > 50
class TestNormalize:
def test_gmail_dots_and_tags_stripped(self):
assert ep.normalize_email("Foo.Bar+promo@gmail.com") == "foobar@gmail.com"
assert ep.normalize_email("a.b.c@googlemail.com") == "abc@googlemail.com"
def test_other_providers_strip_tag_keep_dots(self):
assert ep.normalize_email("user+tag@outlook.com") == "user@outlook.com"
# Dots are significant outside Gmail — must be preserved.
assert ep.normalize_email("first.last@outlook.com") == "first.last@outlook.com"
def test_non_aliasing_provider_untouched(self):
assert ep.normalize_email("normal@yahoo.com") == "normal@yahoo.com"
assert ep.normalize_email("a.b@protonmail.com") == "a.b@protonmail.com"
def test_lowercased(self):
assert ep.normalize_email("USER@Example.COM") == "user@example.com"
class TestClassifyMxHosts:
def test_disposable_infrastructure_caught(self):
# onldm.net-style rotating front domain: MX points at the real provider.
assert ep.classify_mx_hosts(["prd-smtp.10minutemail.com."]) == ep.MX_DISPOSABLE
assert ep.classify_mx_hosts(["mail.mailinator.com"]) == ep.MX_DISPOSABLE
def test_null_mx_means_no_mail(self):
assert ep.classify_mx_hosts(["."]) == ep.MX_NONE
def test_real_provider_ok(self):
assert ep.classify_mx_hosts(["aspmx.l.google.com."]) == ep.MX_OK
assert ep.classify_mx_hosts(["mx1.privateemail.com", "mx2.privateemail.com"]) == ep.MX_OK
def test_suffix_match_not_substring(self):
assert ep.classify_mx_hosts(["not10minutemail.com"]) == ep.MX_OK
def test_any_disposable_host_taints(self):
hosts = ["aspmx.l.google.com.", "backup.guerrillamail.com."]
assert ep.classify_mx_hosts(hosts) == ep.MX_DISPOSABLE
class TestMxVerdict:
"""The resolver is monkeypatched: no network in tests."""
def setup_method(self):
ep._mx_cache.clear()
def test_fail_open_on_resolver_trouble(self, monkeypatch):
pytest.importorskip("dns")
async def boom(domain, rtype):
raise RuntimeError("resolver down")
monkeypatch.setattr(ep, "_resolve", boom)
assert asyncio.run(ep.mx_verdict("u@example.com")) == ep.MX_OK
def test_nxdomain_is_no_mx(self, monkeypatch):
dns = pytest.importorskip("dns")
import dns.resolver
async def nx(domain, rtype):
raise dns.resolver.NXDOMAIN()
monkeypatch.setattr(ep, "_resolve", nx)
assert asyncio.run(ep.mx_verdict("u@no-such-domain.example")) == ep.MX_NONE
def test_no_mx_falls_back_to_a_record(self, monkeypatch):
dns = pytest.importorskip("dns")
import dns.resolver
async def no_mx_but_a(domain, rtype):
if rtype == "MX":
raise dns.resolver.NoAnswer()
return ["1.2.3.4"]
monkeypatch.setattr(ep, "_resolve", no_mx_but_a)
assert asyncio.run(ep.mx_verdict("u@a-record-only.example")) == ep.MX_OK
def test_no_mx_falls_back_to_aaaa_record(self, monkeypatch):
dns = pytest.importorskip("dns")
import dns.resolver
async def ipv6_only(domain, rtype):
if rtype == "AAAA":
return ["::1"]
raise dns.resolver.NoAnswer()
monkeypatch.setattr(ep, "_resolve", ipv6_only)
assert asyncio.run(ep.mx_verdict("u@ipv6-only.example")) == ep.MX_OK
def test_error_verdicts_cached_briefly(self, monkeypatch):
dns = pytest.importorskip("dns")
import dns.resolver
async def nx(domain, rtype):
raise dns.resolver.NXDOMAIN()
monkeypatch.setattr(ep, "_resolve", nx)
assert asyncio.run(ep.mx_verdict("u@transient-blip.example")) == ep.MX_NONE
import time
_, expiry = ep._mx_cache["transient-blip.example"]
# A transient NXDOMAIN must not pin the lockout for the full hour.
assert expiry - time.monotonic() <= ep._MX_ERROR_TTL + 1
def test_mx_blocklist_loaded_from_file(self):
assert "10minutemail.com" in ep._DISPOSABLE_MX
assert len(ep._DISPOSABLE_MX) >= 10
def test_verdict_is_cached_per_domain(self, monkeypatch):
pytest.importorskip("dns")
calls = []
async def counting(domain, rtype):
calls.append(domain)
class R:
exchange = "prd-smtp.10minutemail.com."
return [R()]
monkeypatch.setattr(ep, "_resolve", counting)
assert asyncio.run(ep.mx_verdict("a@onldm.net")) == ep.MX_DISPOSABLE
assert asyncio.run(ep.mx_verdict("b@onldm.net")) == ep.MX_DISPOSABLE
assert calls == ["onldm.net"]
def test_empty_email_is_no_mx(self):
pytest.importorskip("dns")
assert asyncio.run(ep.mx_verdict("")) == ep.MX_NONE

View file

@ -1,164 +0,0 @@
"""Free minutes withdrawn from abusive sign-ups (``User.free_plan_denied``).
Two leaks, both measured in prod on 22-sep-2026:
- a temp-mail farm (~100 rotating front domains, all MX'd to
wabblywabble.com / wallywatts.com): 568 accounts, 4.828 free minutes;
- delete-and-re-register: the ledger is keyed by user id, so a new row for the
same address started with a fresh 20 minutes (15 times, 6 addresses).
"""
import asyncio
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from cloud import account, config, email_policy, metering
def _user(**kw):
base = dict(google_sub=None, email="real@gmail.com", free_plan_denied=None)
base.update(kw)
return SimpleNamespace(**base)
class TestEligibility:
def test_denied_account_gets_no_free_minutes(self):
assert metering.free_plan_eligible(_user(free_plan_denied="disposable_mx")) is False
def test_denied_google_account_gets_no_free_minutes_either(self):
assert metering.free_plan_eligible(
_user(google_sub="g-1", free_plan_denied="recreated_after_deletion")) is False
def test_normal_accounts_are_unchanged(self):
assert metering.free_plan_eligible(_user()) is True
assert metering.free_plan_eligible(_user(google_sub="g-1")) is True
def test_rows_without_the_attribute_still_work(self):
assert metering.free_plan_eligible(SimpleNamespace(google_sub="g", email="a@gmail.com")) is True
class TestFarmMx:
@pytest.mark.parametrize("hosts", [
["mail.wabblywabble.com", "mail.wallywatts.com"],
["mail.wallywatts.com"],
["mx2.den.yt"],
["temp-mail-pro.com"],
["prd-smtp.10minutemail.com"],
])
def test_farm_mx_hosts_are_disposable(self, hosts):
assert email_policy.classify_mx_hosts(hosts) == email_policy.MX_DISPOSABLE
def test_real_mx_hosts_are_fine(self):
assert email_policy.classify_mx_hosts(["gmail-smtp-in.l.google.com"]) == email_policy.MX_OK
assert email_policy.classify_mx_hosts(["mx.yandex.net"]) == email_policy.MX_OK
class _Result:
def __init__(self, value):
self._value = value
def scalar_one_or_none(self):
return self._value
class _Session:
def __init__(self, value):
self.value = value
self.statements = []
async def execute(self, stmt):
self.statements.append(stmt)
return _Result(self.value)
class TestSignupAfterDeletion:
def test_recent_erasure_denies_the_free_plan(self):
s = _Session(value="some-id")
assert asyncio.run(account.free_plan_denial_for_signup(s, "Foo.Bar@gmail.com")) \
== "recreated_after_deletion"
params = s.statements[0].compile().params
# Same fingerprint the erasure stored (normalised address)...
assert account.email_fingerprint("foobar@gmail.com") in params.values()
# ...and only erasures inside the window count.
cutoffs = [v for v in params.values() if isinstance(v, datetime)]
assert cutoffs
expected = datetime.now(timezone.utc) - timedelta(days=config.FREE_REDO_BLOCK_DAYS)
assert abs((cutoffs[0] - expected).total_seconds()) < 60
def test_no_erasure_keeps_the_free_plan(self):
assert asyncio.run(account.free_plan_denial_for_signup(_Session(None), "a@gmail.com")) is None
def test_window_zero_disables_the_check(self, monkeypatch):
monkeypatch.setattr(config, "FREE_REDO_BLOCK_DAYS", 0)
s = _Session("some-id")
assert asyncio.run(account.free_plan_denial_for_signup(s, "a@gmail.com")) is None
assert s.statements == []
class TestMagicLinkSignup:
"""verify_magic_link stamps the new row; an existing row is untouched."""
def _run(self, monkeypatch, existing_user, deleted_before):
from cloud import auth
token_row = SimpleNamespace(used_at=None, email="again@gmail.com",
expires_at=datetime.now(timezone.utc) + timedelta(minutes=5))
added = []
class _Res:
def __init__(self, v):
self.v = v
def scalar_one_or_none(self):
return self.v
class _Sess:
calls = 0
async def execute(self, stmt):
_Sess.calls += 1
return _Res(token_row if _Sess.calls == 1 else existing_user)
def add(self, obj):
obj.id = "new-id"
added.append(obj)
async def flush(self):
pass
def begin(self):
return self
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def _denial(session, email):
return "recreated_after_deletion" if deleted_before else None
async def _load(session, uid):
return SimpleNamespace(entitled=False)
monkeypatch.setattr(auth.database, "session", lambda: _Sess())
monkeypatch.setattr(account, "free_plan_denial_for_signup", _denial)
monkeypatch.setattr(auth, "_load_current_user", _load)
monkeypatch.setattr(auth, "issue_jwt", lambda uid, email: "jwt")
asyncio.run(auth.verify_magic_link(auth.MagicVerifyRequest(token="t")))
return added
def test_new_account_after_deletion_is_denied(self, monkeypatch):
added = self._run(monkeypatch, existing_user=None, deleted_before=True)
assert added[0].free_plan_denied == "recreated_after_deletion"
def test_new_account_without_deletion_is_eligible(self, monkeypatch):
added = self._run(monkeypatch, existing_user=None, deleted_before=False)
assert added[0].free_plan_denied is None
def test_existing_account_is_not_restamped(self, monkeypatch):
existing = SimpleNamespace(id="u1", email="again@gmail.com", free_plan_denied=None,
last_login_at=None)
added = self._run(monkeypatch, existing_user=existing, deleted_before=True)
assert added == []
assert existing.free_plan_denied is None

Some files were not shown because too many files have changed in this diff Show more