Compare commits

...

10 commits

Author SHA1 Message Date
ace54c6e77 chore: rename OpenShorts to Clipwright
Some checks are pending
CI / backend-tests (push) Waiting to run
CI / frontend-build (push) Waiting to run
- Rebrand all text, package/CLI (clipwright_cli), env vars (CLIPWRIGHT_*),
  localStorage keys, Docker container names and webhook header
- Rename/relocate assets, skills/, n8n examples, font map; delete dead MCP
  metadata (server.json, glama.json) and generated egg-info
- Canonical site URL -> https://git.pbento.pt/pedro-bento/clipwright
- Preserve fork provenance (upstream OpenShorts attribution in README/NOTICE/LICENSE)
2026-10-04 18:07:07 +01:00
4e82d60cbc fix: harden Postiz integration and align docs/CLI/n8n after review
- Postiz URL is now required (no built-in host); a key can never be sent to a default instance
- /api/postiz/scheduled normalizes scheduled_date and widens the default window
- Disabled channels are refused for posting; frontend excludes them from connected platforms
- 4xx instead of 500 on missing clip URL / bad schedule date; Postiz error bodies truncated
- Add tests/test_postiz.py (24 tests); fix remaining cloud-removal test drift
- CLI defaults to localhost:8000; n8n workflows fixed against the real routes
- Remove dead media-token auth code, stale copy (download_url/402) and doc drift
2026-10-04 17:25:17 +01:00
edcfeaf9d5 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
2026-10-04 17:02:55 +01:00
fbabb4ec5d refactor: self-hosted fork — Postiz publishing, drop AI Shorts/UGC/agent/autopilot/MCP, fix Studio image API, remove upload cap
- Replace Upload-Post with a self-hosted Postiz client (postiz.py) and /api/postiz/* endpoints
- Remove AI Shorts, UGC gallery, AI Agent tab, Autopilot, MCP/agent layer, and their UIs
- Fix YouTube Studio thumbnail generation (google-genai >=2 Interactions API) and blocking download
- Make the video upload size cap configurable/unlimited (MAX_FILE_SIZE_MB, default 0)
- Update SEO/marketing/docs to the single-product self-hosted reality; lint+build green
2026-10-04 16:30:44 +01:00
juancarlos.cavero
06a119c280 feat(mcp): caption presets and the new caption options in add_subtitles
/api/subtitle takes a named preset (subtitles.CAPTION_PRESETS, the same
looks the dashboard offers); fields sent alongside it override that part.
The MCP add_subtitles tool exposes preset, effect, reveal, one_word, shadow
and border_width, and gives a resized line the budget that keeps it on one
line, as the dashboard does. A test keeps the server and dashboard preset
ids in sync.
2026-10-01 18:35:37 +02:00
juancarlos.cavero
9cc0a0feb0 feat(captions): size control and trending caption presets
The subtitle modal had no size control: the font size was pinned at 24
while clips ship at 44, so re-applying captions from the modal halved them.
It now opens on the shipped look and offers S/M/L/XL, with fewer characters
per line as the text grows so a line still fits the 9:16 frame.

New in generate_ass: a "highlight" effect (opaque box behind the active
word via a second BorderStyle 3 style, black text on light boxes), "reveal"
(words appear as they are spoken), a drop shadow, and an outline of 0 when
a shadow carries the contrast. /api/subtitle takes reveal, shadow,
max_chars (1 = one word at a time) and max_duration.

Presets added: Default, Hormozi, Pill, Lime box, One word, Clean. Anton and
Montserrat are selectable, and the preview uses the burn's scale and line
budget so what plays in the modal is what gets burned.
2026-10-01 17:48:42 +02:00
juancarlos.cavero
cb37ae3aec feat(watermark): serve the free-plan mark as a copy, so paying removes it from existing clips
Every file the pipeline and the clip editor write is now clean. On the free
plan the served file is a wm_<final> copy with the mark burned in
(main.mark_delivery, last step after captions; app._deliver for the editor
endpoints, decided from the caller's plan), and both twins go to R2. An
upgrade re-points the user's library at the clean twins from the Stripe
webhook (cloud.videos.unmark_user_library): no render, no source video,
and the dashboard chases the job result until no served URL carries wm_.

Before, the mark rode the reframe encode, so every derivative inherited it
and the upgrade modal's "upgrade to remove the watermark" was false for the
clips already made. The first cancellation for "clip quality" (29-sep) was a
user who paid 15 minutes after their first job and kept the mark on every
download and restyle.

- /videos guard refuses a marked job's clean deliverables (.marked dotfile),
  so the twin cannot be fetched by stripping the prefix off a URL; editor
  scratch files stay servable. Re-checked after an R2 restore.
- Walk-backs treat wm_ as the outermost layer; _canonical_clip_file globs it.
- Jobs from before this scheme (mark burned into the canonical) never get a
  second copy; a failed mark still serves under the wm_ name.
- Watermark notice once per job when the clips land on a free account, and
  before the first download if skipped; tracked with source=results|download.
  Upsell/banner/win-back copy now promise the instant removal.
2026-10-01 09:35:53 +02:00
juancarlos.cavero
faff66de0b feat(download): skip the static IPs when the probe already saw them bot-checked
Since 30-sep-2026 YouTube bot-checks anonymous requests from every one of
our non-residential IPs per video: the same video fails on the 3 statics
and the server's own IP, with every player client, and the paid residential
proxy answers it. The metering probe learns that verdict first; the
download then repeated four anonymous attempts (~8 s, four more hits on IPs
YouTube is scoring) before reaching the paid proxy for the same answer.
The probe now leaves a one-shot verdict per URL, app.py passes it to the
job as DOWNLOAD_SKIP_STATICS=1 (and into the resume manifest), and
plan_download_attempts drops the free attempts when a paid proxy exists.
2026-09-30 16:30:04 +02:00
juancarlos.cavero
8ee8ae36c6 feat(alerts): page when the YouTube session cookies stop being recognised
The pool probe says UP while one static still answers, and the ledger
alert names IPs, so a rotated cookie session (every download anonymous,
statics bot-checked one by one, jobs on the per-GB proxy) went unnoticed
for ~900 MB on 30-sep-2026. The static probes already fetch the watch
page with the cookies attached; read the ytcfg LOGGED_IN marker yt-dlp
itself uses and open a one-strike incident naming the fix.
2026-09-30 13:27:09 +02:00
victorcavero14
29c54fa04c feat(cancel): retention offer as the last step, resume from the account page
The Stripe portal stops cancelling (its config, 2026-09-28), so the dashboard
flow is the only way out and carries the portal's retention coupon:
- GET /api/billing/retention-offer: live monthly plan, no discount on it, never
  offered before (retention_offer in the Stripe sub metadata). Any Stripe error
  means no offer, never a stuck flow. Coupon id from RETENTION_COUPON_ID.
- POST /api/billing/retention-offer/accept: applies the coupon, stores the
  feedback with outcome=retained, alerts "Cancel saved".
- POST /api/billing/resume + "Keep my subscription": undo a scheduled cancel,
  which the portal did with the cancel feature now off.
- cancellation_feedback.outcome (additive column).
2026-09-28 19:03:38 +02:00
220 changed files with 6863 additions and 27977 deletions

View file

@ -1,23 +1,12 @@
# AWS S3 (optional — for clip backup/gallery)
# AWS S3 (optional — for clip backup)
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.
# DEBUG_LOGS=true
# Pre-flight quality gate: warn before processing a YouTube source below this
# height (720p default; 0 disables). Only applies to URL sources.
# QUALITY_GATE_MIN_HEIGHT=720
@ -75,34 +64,47 @@ 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
# <video src> / <img src> URLs (default 43200 = 12 h).
# MEDIA_URL_TTL_SECONDS: life of the path-signed capability handed to consumers
# that cannot send a header — webhook payloads and MCP tool results
# (default 86400 = 24 h).
# MEDIA_TOKEN_TTL_SECONDS=43200
# MEDIA_URL_TTL_SECONDS=86400
# /videos and /thumbnails are public static mounts in this fork: there is no
# media-token auth. Anyone who holds a job id can fetch that job's clips, and
# the /videos mount refuses non-deliverable files (transcripts, metadata
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
# (JOB_RETENTION_SECONDS).
# Retention for the two kinds of file that had none. Thumbnails and the frames
# sampled to make them are close-ups of a real person; the clock runs from the
# last download. Uploaded actor photos die with the job that used them.
# Retention for thumbnails. Thumbnails and the frames sampled to make them are
# close-ups of a real person; the clock runs from the last download.
# THUMBNAIL_RETENTION_SECONDS=86400
# ACTOR_UPLOAD_RETENTION_SECONDS=3600
# Per-IP rate limiting (rate_limit.py). "<max requests>/<window seconds>".
# Defaults: auth 30/600, process 60/3600, mcp 240/60. Set RATE_LIMIT_ENABLED=0
# Defaults: auth 30/600, process 60/3600. Set RATE_LIMIT_ENABLED=0
# to turn the whole thing off (self-host behind your own firewall).
# RATE_LIMIT_ENABLED=1
# RATE_LIMIT_AUTH=30/600
# RATE_LIMIT_PROCESS=60/3600
# RATE_LIMIT_MCP=240/60
# ---------------------------------------------------------------------------
# Publishing (self-hosted Postiz)
# ---------------------------------------------------------------------------
# Base URL of your own self-hosted Postiz instance (no trailing slash) and its
# API key. Point POSTIZ_URL at your instance; do not rely on any built-in
# default. Required for the server-side publishing, queue and analytics calls
# (the dashboard can also send the user's X-Postiz-Url / X-Postiz-Key headers
# per request). Postiz holds the social platform tokens; Clipwright only
# uploads clip bytes.
# POSTIZ_URL=https://your-postiz-host
# POSTIZ_API_KEY=your_postiz_api_key
# ---------------------------------------------------------------------------
# Upload size
# ---------------------------------------------------------------------------
# Maximum upload size in MB. 0 (the default) means unlimited. Set a positive
# number to cap uploads and reject larger files with HTTP 413.
# MAX_FILE_SIZE_MB=0
# Which hop may declare the client's address in X-Forwarded-For. The Dockerfile
# defaults to the private Docker ranges; narrow it to Traefik's own address on
@ -115,19 +117,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.
# DATABASE_URL=postgres://user:pass@host:5432/openshorts
# the database host, not by the app).
# DATABASE_URL=postgres://user:pass@host:5432/clipwright
# BACKUP_AGE_RECIPIENT=age1...
# BACKUP_DEST=s3://openshorts-backups/pg
# BACKUP_DEST=s3://clipwright-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

@ -1,7 +1,7 @@
name: Publish CLI to PyPI
# Push a tag cli-vX.Y.Z (matching `version` in cli/pyproject.toml) to publish
# the `openshorts` CLI. Uses PyPI Trusted Publishing (OIDC): no API token.
# the `clipwright` CLI. Uses PyPI Trusted Publishing (OIDC): no API token.
on:
push:
tags:
@ -35,7 +35,7 @@ jobs:
- name: Smoke test the wheel
run: |
pip install dist/*.whl
openshorts --help
clipwright --help
- name: Publish
uses: pypa/gh-action-pypi-publish@release/v1
with:

2
.gitignore vendored
View file

@ -39,7 +39,7 @@ output/
.claude/
# skills/ holds third-party installs (symlinks); our own published skill is versioned
skills/*
!skills/openshorts/
!skills/clipwright/
skills-lock.json

View file

@ -1,3 +1,3 @@
[
{ "date": "2026-07-17", "scope": "app", "macrostructure": "Marquee Hero (marketing) / Workbench (app) / Long Document (content)", "theme": "lumen", "drop": "night", "enrichment": "filament-chamber apparatus + meter strip (landing only)", "brief": "OpenShorts · full app + landing redesign, design.md-managed" }
{ "date": "2026-07-17", "scope": "app", "macrostructure": "Marquee Hero (marketing) / Workbench (app) / Long Document (content)", "theme": "lumen", "drop": "night", "enrichment": "filament-chamber apparatus + meter strip (landing only)", "brief": "Clipwright · full app + landing redesign, design.md-managed" }
]

272
CLAUDE.md
View file

@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
OpenShorts is an AI-powered vertical video generator that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. Uses Google Gemini 3.1 Flash-Lite (`gemini-3.1-flash-lite`, overridable with `GEMINI_MODEL`) for viral moment detection and title generation.
Clipwright is an AI-powered vertical video editor that transforms long YouTube videos or local uploads into viral-ready short clips (9:16 format) for TikTok, Instagram Reels, and YouTube Shorts. It also includes YouTube Studio (titles, thumbnails, descriptions) and publishes through a self-hosted Postiz instance. Uses Google Gemini 3.1 Flash-Lite (`gemini-3.1-flash-lite`, overridable with `GEMINI_MODEL`) for viral moment detection and title generation.
## Development Commands
@ -43,7 +43,7 @@ uvicorn app:app --host 0.0.0.0 --port 8000
8. **Hook Overlay** - Text overlays with styled fonts
9. **Voice Dubbing** - Optional ElevenLabs AI translation (30+ languages)
10. **S3 Backup** - Silent background upload
11. **Social Distribution** - Upload-Post API (async upload)
11. **Social Distribution** - Self-hosted Postiz (clip uploaded, then scheduled or posted)
### Key Files
| File | Purpose |
@ -71,7 +71,7 @@ homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build ti
`createRoot().render()` replaces it on mount, so users get the app and
non-executing clients get the copy. **Keep it in sync with `Landing.jsx`.**
- Emits the standalone pages (the `/alternatives` cluster, the clip-generator,
open-source, use-case and automation pages, and `/mcp`; the full list is
open-source and use-case pages; the full list is
`buildPages()` in `seo/pages.js`) as flat `.html` files.
nginx resolves the clean URL through `try_files $uri $uri.html`; serving them as
directories instead makes nginx 301 to a trailing slash and every canonical
@ -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. Clipwright 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
@ -95,13 +94,13 @@ answers describe the paid product as free.
`POST /api/tools/youtube-metadata` = one Gemini text call (tags / titles /
description) with the managed key. Per-IP windows + global daily cap per tool,
24 h cache (also for "no captions"/"unavailable").
- Pages: `seo/tools.js` (hub + 3 tools) and `seo/autopilot-pages.js`
(`/auto-clip`, `/youtube-automation`). A tool page carries `tool: {entry, html}`:
- Pages: `seo/tools.js` (hub + 3 tools). A tool page carries
`tool: {entry, html}`:
the form is in the static HTML, the behaviour is a Vite entry in
`dashboard/tools/*.js` (`vite.config.js` rollupOptions.input) that
`vite-plugin-seo.js` looks up by name in the bundle. The 9:16 converter runs
in the browser with mediabunny/WebCodecs (no upload).
- Attribution: `seo/render.js` writes the same first-touch `os_attrib` key the
- Attribution: `seo/render.js` writes the same first-touch `cw_attrib` key the
app writes, from the static page the visit started on. Before, every signup
was credited to "/" (7,481/7,481 rows, 30 days to 23-sep-2026). Signup,
CheckoutStarted and Subscribed carry `landing_path`/`referrer_host`/utm as
@ -119,7 +118,7 @@ Cada nombre enciende su variable de entorno para **ese** trabajo
`AUTO_LAYOUT=1` (recorte simple y nada más). Sin `layouts` manda el env del
despliegue, que desde el 25-ago-2026 es `AUTO_LAYOUT=1`. El dashboard lo expone
en opciones avanzadas ("vertical layout": auto / split / screencast / none,
`MediaInput.jsx`, recordado en `localStorage.os_layout`).
`MediaInput.jsx`, recordado en `localStorage.cw_layout`).
`auto` activa `layout_picker.py`: **una** llamada a Gemini por vídeo de origen
(no por clip) que elige entre `none` / `screencast` / `split`. Medido sobre el
@ -163,87 +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.
### The quota wall offers the first N minutes (`app.partial_offer`)
The wall (`TopUpModal`, context `wall`) opens on a 402 from `/api/process`.
Measured on 16-sep-2026, 93 of 99 walls were shown to accounts with their
20 free minutes **untouched** that had pasted a 21-90 min video: the user was
asked for $12 before seeing one clip, and 41 of the 68 subscriptions Stripe
created in 30 days expired unpaid, none of them a card decline. So the 402
now carries `partial_minutes` (the floored balance, when it is at least
`PARTIAL_MIN_MINUTES` and shorter than the source), the wall shows "clip the
first N min" next to the plans, and the dashboard resubmits the same job with
`max_minutes=N`. `reserve_process_minutes` then reserves N (never more than
the balance, whatever the client asks) and sets `MAX_SOURCE_MINUTES` for
`main.py`, whose `cap_source_duration` cuts the downloaded/uploaded file **in
place** before anything reads it, so transcription, the layout picker, the
editor and `/api/source` all see a short video. The cut travels in the
resume manifest: a resumed job downloads the source again and would
otherwise process 45 minutes on a 20-minute reservation. `/api/status` and
the process response carry `partial`, and the results view says which part
of the video the clips came from, with the upsell for the rest.
### Free sources past the balance never meet the wall (`app.free_overflow`)
Since 28-sep-2026 the wall above only shows to paid plans and to free
accounts with less than `PARTIAL_MIN_MINUTES` left. For a free account whose
source is longer than its balance, `reserve_process_minutes` decides on its
own (the client sends no `max_minutes`):
- **First video, up to `FIRST_VIDEO_MAX_MINUTES` (60):** clipped whole. Only
the floored balance is reserved (it lands at zero) and the download's safety
cap (`SOURCE_CAP_MINUTES`) is the probed length, not the reservation. Once
per account: `metering.has_processed_before` (any reserved/committed
`process` row; a released one keeps the grant for the retry), and once per
client IP every `FIRST_VIDEO_IP_WINDOW_DAYS` (30): `first_video_grants`
holds an HMAC of the IP (never the IP), is not tied to the user row so an
account deletion does not reset it, and only counts grants whose job
reservation is live. A blocked network gets the first-N-minutes cut. The response
carries `first_video: true`; the dashboard says so and tracks
`FirstVideoGrant`.
- **Anything else:** `max_minutes` becomes the balance, so the job clips the
first N minutes exactly as if the user had taken the wall's offer. Tracked
client-side as `AutoPartial`.
### Lifecycle emails (`cloud/lifecycle.py`)
Welcome (minutes after sign-up), first-clip nudge (24-72 h, nothing
processed), win-back (2-7 days after the first committed video, no plan; with
`WINBACK_PROMO_CODE` when set) and checkout recovery (`checkout.session.expired`
with the `after_expiration.recovery` URL that `create_checkout` now enables).
Each at most once per account: a `lifecycle_emails` row is claimed before the
send (unique `user_id, kind`). The loop sends at most `BATCH` per 10-minute
tick. All four are commercial: `emails.send_commercial_email` skips
`marketing_opt_out` accounts and adds the unsubscribe footer and
`List-Unsubscribe` headers (the out-of-minutes upsell goes through it too).
The Stripe webhook endpoint must have `checkout.session.expired` enabled.
Promotion codes and coupon ids live in the env / Stripe, never in this repo.
### Cancel flow (`cloud/cancellation.py`, `CancelPlanModal.jsx`)
Account → "Cancel subscription" opens three steps: reason (closed list,
`CANCEL_REASONS`, plus an optional detail box), a 1-5 rating with an optional
review (and an "OK to quote publicly" box), then confirm.
`POST /api/billing/cancel` sets `cancel_at_period_end` in Stripe with
`cancellation_details` (our reason mapped to Stripe's feedback enum), and only
after Stripe accepts writes a `cancellation_feedback` row (user-owned, erased
with the account) and flips the local row, so the webhook sees no transition
and the generic churn alert does not fire twice. The alert names the reason and
rating, never the written text (Telegram, see `alerts.user_ref`): read reviews
in the table. The Stripe portal can still cancel without the form; its alert
carries Stripe's own feedback value when the portal asked for one.
### 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: clips, AI avatar /
UGC videos, autopilot, 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
@ -328,7 +246,7 @@ prompt scores garbage silently). Self-host `/api/process` then accepts a
request without `X-Gemini-Key` and `/api/config.localLlm` tells the dashboard
not to demand one. Frame-based stages (`layout_picker`, `screencast_layout`,
`get_visual_clips`) stay on Gemini and degrade as they always did without a
key. Never wired in cloud mode: `BILLING_ENABLED` ignores it.
key. On a self-hosted instance it is always available.
### Thumbnail Studio (`thumbnail.py`, `/api/thumbnail/*`)
@ -435,125 +353,33 @@ portrait clip cannot reproduce the shrink either.
| POST | `/api/hook` | Add text hook overlays |
| POST | `/api/translate` | AI voice dubbing via ElevenLabs |
| GET | `/api/translate/languages` | List supported dubbing languages |
| POST | `/api/social/post` | Post to social media (async upload) |
| POST | `/mcp` | MCP server (JSON-RPC): the pipeline as agent tools |
| POST/GET/DELETE | `/api/keys` | User API keys (cloud mode, session JWT only) |
| DELETE | `/api/account` | Erase the account and everything in it (GDPR art. 17) |
| GET/PUT | `/api/autopilot` | Autopilot settings, connected accounts, recent runs (cloud only) |
| GET | `/api/autopilot/videos` | Latest uploads of the connected YouTube channel + what Autopilot did |
| POST | `/api/autopilot/run` | Clip one channel video now (`{video_id}`) |
| POST | `/api/postiz/post` | Upload a clip to Postiz, then schedule or post it now |
| GET | `/api/postiz/integrations` | List the channels connected in Postiz |
| GET | `/api/postiz/scheduled` | List scheduled posts in a date window |
| DELETE | `/api/postiz/scheduled/{id}` | Delete a scheduled post |
| GET | `/api/postiz/analytics` | Channel analytics (`integration` id required) |
| GET | `/api/postiz/analytics/posts` | Analytics for one published post (`post_id` required) |
### Agent access (MCP, API keys, webhooks)
### Publishing through Postiz
- **API keys** (`cloud/api_keys.py`): `osk_...` tokens, sha256-stored, created in
the dashboard account page. `cloud/auth.get_current_user_optional` accepts
them (`Bearer osk_...` or `X-API-Key`) and resolves the owner, so metering,
entitlement, plan priority and job ownership apply to agents with zero
endpoint changes. Key management itself refuses API-key auth: a leaked key
cannot mint replacements.
- **MCP server** (`mcp_server.py`, mounted always): stateless Streamable-HTTP
JSON-RPC at `/mcp` — no SDK dependency, ~3 methods + 8 tools. Each tool calls
back into this same app in-process (`httpx.ASGITransport`) forwarding the
caller's auth headers, so it can never drift from the REST behavior. Cloud
mode 401s without a resolvable user; self-host stays BYOK-open.
- **stdio transport** (`mcp_stdio.py`): the same `handle_message` / `call_tool`
as a subprocess, for hosts that only launch MCP servers as a command (Glama's
Dockerfile deployments wrap one; a local client can skip the web server).
Two invariants: `sys.stdout` is swapped for stderr **before `app` is
imported**, because the pipeline prints everywhere and one stray line
corrupts the JSON-RPC stream; and the app's lifespan is entered
(`router.lifespan_context`), which `ASGITransport` does not do on its own.
- **OAuth for MCP clients** (`cloud/mcp_oauth.py`, cloud mode only): claude.ai
and ChatGPT connect by URL, so the server publishes RFC 9728/8414 metadata
under `/.well-known/`, accepts dynamic client registration (`POST
/oauth/register`, public clients, PKCE S256 mandatory) and bounces
`GET /oauth/authorize` to the dashboard consent screen (`#/oauth/authorize`),
because the session JWT lives in localStorage on the frontend host and a
bare API GET cannot see it. `POST /api/oauth/authorize` (session auth) mints
the code; `POST /oauth/token` redeems it by **minting an ordinary `osk_`
key** named after the client and returning it as the access token. No new
auth path, no refresh tokens: the key shows up in Account → API keys and
revoking it disconnects the app. The `/mcp` 401 carries
`WWW-Authenticate: Bearer resource_metadata=...` so clients find the flow.
`oauth_codes` is in `USER_OWNED_TABLES`; `oauth_clients` deliberately not.
- **Webhooks**: `POST /api/process` takes `webhook_url` + optional
`webhook_secret` (HMAC-SHA256, `X-OpenShorts-Signature`). Validated with
`postiz.py` is a thin client for a self-hosted [Postiz](https://postiz.com/)
instance. The dashboard sends the user's `X-Postiz-Key` / `X-Postiz-Url`
headers; the backend falls back to the `POSTIZ_API_KEY` / `POSTIZ_URL` env
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`.
### Webhooks
`POST /api/process` takes `webhook_url` + optional
`webhook_secret` (HMAC-SHA256, `X-Clipwright-Signature`). Validated with
`security_utils.assert_public_url` at submit AND at delivery (DNS rebinding).
Fired once per job from `run_job_wrapper` after the R2 archive so the payload
can carry durable download links; survives redeploys via the resume manifest.
Fired once per job from `run_job_wrapper`; survives redeploys via the resume
manifest. Each clip carries `video_url` (the local `/videos/...` path).
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
### Autopilot (`cloud/autopilot.py`, dashboard tab "Autopilot")
Cloud-only retention feature: every new video on the user's connected YouTube
channel becomes clips on its own, and optionally the best ones are scheduled
on their socials, one a day. Paid plans only (it spends minutes unattended).
- **Channel listing** comes from Upload-Post, not scraping:
`GET /api/uploadposts/media?platform=youtube&user=os_<id>` reads the
channel's uploads playlist with the user's own OAuth token, so it includes
videos uploaded straight to YouTube. There is no push from Upload-Post, so a
loop polls (tick 5 min, each user at most once per 55 min).
- **Jobs go through the normal pipeline**: an in-process `POST /api/process`
(`httpx.ASGITransport`, like the MCP server) authenticated with a freshly
issued session JWT for the user. Metering, the probe, the per-plan job
limit, the quality gate and the download proxies apply unchanged. The
per-job content attestation is recorded once as `rights_ack_at`.
- **Guard rails**: only videos published after `enabled_at` (switching on never
clips the back catalogue) and at most 3 days old; 1 automatic job per user
per 24 h; `max_minutes` per video (default 30, sent as the partial-clip
`max_minutes`); YouTube Shorts are skipped (`HEAD /shorts/<id>` answers 200
for a Short and 303 to `/watch` for a regular video; the SOCS consent cookie is required, from the EU servers every request is otherwise a 302 to consent.youtube.com).
- **Dedupe across the deploy handover**: two containers poll at once during a
rolling deploy, so a video is claimed by INSERTing its `autopilot_runs` row
(unique `user_id, video_id`) before anything is submitted. A draining
instance stops polling. A 429 (job limit) or 5xx drops the claim to retry.
- **Completion**: `run_job_wrapper` calls `on_job_finished` after the R2
archive. A guarded UPDATE (`status='processing'` → final) makes it once-only;
it sends the Autopilot email (replacing the generic clips-ready one) and,
with autopublish on, uploads the top `clips_to_publish` clips by
`predicted_score` to Upload-Post in a background task, scheduled one a day at
`publish_hour` in the user's IANA `timezone`. Runs stuck in processing for
6 h are marked `timeout`.
- `AUTOPILOT_DISABLED=1` turns the poller off without touching the API.
- Both tables are in `account.USER_OWNED_TABLES`.
### Account erasure (GDPR art. 17)
`DELETE /api/account` (`cloud/account.py`, dashboard: Account → Delete account)
is immediate and irreversible: there is no recovery window because after the
delete there is nothing left to authenticate a recovery request against. It
refuses API-key auth (a leaked `osk_` must not destroy its own account) and
requires the caller to retype the account email.
The order of the steps is the design, and each one is a failure mode:
**Stripe cancel first**, aborting the whole thing if it fails, so we never erase
a user we are still billing; **R2 before the database**, because those rows are
the only index of which objects are theirs and dropping them first turns a
failed purge into permanent orphans; the DB delete is **one transaction** over
an explicit table list (`USER_OWNED_TABLES`) rather than the declared ON DELETE
CASCADEs, since `create_all` never ALTERs an existing table and a constraint
added after a table shipped exists in the models but not in production.
`tests/test_account_erasure.py` fails if a new table references `users.id`
without joining that list.
`app.py` registers a callback for the local working files, which record
ownership three different ways: the `.owner` file clip jobs write (so jobs
recovered from disk after a restart count too), `saas_jobs`, and
`thumbnail_sessions`. That last one is the only thing that ever deletes
generated thumbnails: the hourly sweep skips their directory and they are
served publicly at `/thumbnails/`.
What deliberately survives: the Stripe customer and its invoices (6-year
retention, Spanish commercial law) and one `account_deletions` row holding a
sha256 of the email as proof the erasure happened, itself purged after 5 years.
The "why are you leaving" answer is a closed list (`DELETION_REASONS`), never
free text — anything the user could type would land in a row designed to
outlive them. Deleting users also made one webhook path reachable that never
was before: `_apply_topup` reads the user id from Stripe metadata, so it now
confirms the row still exists before inserting, or the FK violation makes
Stripe retry the same doomed event for three days.
### Concurrency Model
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.
@ -590,8 +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 inside the reframe encode** (`reframe_v2.render(watermark=)`),
not a pass of its own (most jobs are free plan).
- **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.
@ -636,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
@ -684,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
@ -707,7 +527,19 @@ ones: while it named the pages it knew, a hashtag page and the legacy
`/<vanity>` channel URL went straight through, and one of them walked to
page 23 on the static pool and then paid the per-GB proxy to walk it
again (20-sep-2026).
`PAID_PROXY_DAILY_MB` (default
Since 30-sep-2026 YouTube answers the bot-check to anonymous requests
from every one of our non-residential IPs (the 3 statics and the server's
own IP alike), **per video**: the same video fails on all of them and a few
popular ones pass on all of them, whatever the client (web, mweb, ios,
android_vr, tv, web_embedded, with or without a player PO token). Only an
authenticated session or a residential IP gets through. So when the probe
saw every static bot-checked and the paid proxy answer, the job carries
`DOWNLOAD_SKIP_STATICS=1` (`metering.pop_statics_bot_checked`, also in the
resume manifest) and `plan_download_attempts` goes straight to the paid
attempts instead of repeating four anonymous hits for the same verdict.
The proxy watcher also checks the ytcfg `LOGGED_IN` marker when
`YOUTUBE_COOKIES` is set and pages on the first probe that says the session
is gone. `PAID_PROXY_DAILY_MB` (default
500) is the hard ceiling: past it the paid proxy is dropped from the probe
and from every new job's env until UTC midnight. The watcher probes the
static pool against a real YouTube watch page (playable markers), not

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
@ -85,9 +81,9 @@ COPY . .
# Register the bundled fonts (Anton for Impact) and the UI-name -> real-font
# aliases with fontconfig so libass resolves what the subtitle modal offers.
RUN mkdir -p /usr/local/share/fonts/openshorts \
&& cp fonts/*.ttf /usr/local/share/fonts/openshorts/ \
&& cp fonts/openshorts-fontmap.conf /etc/fonts/conf.d/60-openshorts.conf \
RUN mkdir -p /usr/local/share/fonts/clipwright \
&& cp fonts/*.ttf /usr/local/share/fonts/clipwright/ \
&& cp fonts/clipwright-fontmap.conf /etc/fonts/conf.d/60-clipwright.conf \
&& fc-cache -f
# Create a non-root user (Moved up)

View file

@ -1,6 +1,7 @@
MIT License
Copyright (c) 2024 OpenShorts
Copyright (c) 2024 OpenShorts (original project)
Copyright (c) 2026 Clipwright contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

13
NOTICE
View file

@ -1,8 +1,17 @@
Clipwright
Copyright (c) 2026 Clipwright contributors
This project is a fork of OpenShorts (https://github.com/mutonby/openshorts),
Copyright (c) 2024 OpenShorts, released under the MIT License.
The Clipwright core application is licensed under the MIT License (see LICENSE).
The upstream OpenShorts copyright below is preserved and remains in effect.
----------------------------------------------------------------------
OpenShorts
Copyright (c) 2024 OpenShorts
The OpenShorts core application is licensed under the MIT License (see LICENSE).
EXCEPTION: All content that resides under the "cloud/" directory of this
repository is licensed under the license defined in "cloud/LICENSE"
(the OpenShorts Commercial License), not under the MIT License.

309
README.md
View file

@ -1,80 +1,36 @@
# OpenShorts.app
# Clipwright
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Open Source](https://badges.frapsoft.com/os/v1/open-source.svg?v=103)](https://opensource.org/)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)
[![Docker](https://img.shields.io/badge/Docker-Ready-2496ED?logo=docker&logoColor=white)](https://docs.docker.com/compose/)
[![GitHub stars](https://img.shields.io/github/stars/mutonby/openshorts?style=social)](https://github.com/mutonby/openshorts)
[![Last Commit](https://img.shields.io/github/last-commit/mutonby/openshorts)](https://github.com/mutonby/openshorts/commits/main)
**Self-hosted AI video platform** with 2 tools in one: **Clip Generator** and **YouTube Studio**, publishing through a self-hosted **Postiz** instance.
**Open source AI video platform** with 3 tools in one: **Clip Generator**, **AI Shorts (UGC videos with AI actors)**, and **YouTube Studio**.
![Your podcast, and the vertical clip Clipwright makes of it: both speakers stacked, captions on the seam](screenshots/split-before-after.gif)
![Your podcast, and the vertical clip OpenShorts makes of it: both speakers stacked, captions on the seam](screenshots/split-before-after.gif)
Two people on camera? Clipwright stacks them instead of shrinking the wide shot, puts the captions on the seam where they cover nobody, and switches back to a face-tracked crop when the cut goes to one person. The AI picks the layout per video; nothing to configure.
Two people on camera? OpenShorts stacks them instead of shrinking the wide shot, puts the captions on the seam where they cover nobody, and switches back to a face-tracked crop when the cut goes to one person. The AI picks the layout per video; nothing to configure.
This is a clean, self-hosted fork of [OpenShorts](https://github.com/mutonby/openshorts), renamed Clipwright. You run it on your own machine with Docker and bring your own Gemini and ElevenLabs keys. There is no hosted service, no billing, and no usage cap. Publishing to TikTok, Instagram Reels and YouTube Shorts goes through your own [Postiz](https://postiz.com/) instance.
**Two ways to run it, same software either way:**
| | Self-hosted (this repo) | Hosted on [openshorts.app](https://www.openshorts.app/) |
|---|---|---|
| **Price** | Free forever, MIT | Free plan, paid from $12/mo |
| **Speed** | 5 to 8 min per 8-min video on CPU | About 50s on our NVIDIA GPU |
| **API keys** | Bring your own Gemini, ElevenLabs, fal.ai | Gemini included, nothing to set up |
| **Watermark / limits** | None, ever | Watermark and 20 min/mo on the free plan, neither on paid |
| **Setup** | Docker, 8GB+ RAM, model downloads | Sign in and paste a link |
| **MCP / API for agents** | Same `/mcp` endpoint, but only while your machine is on | Always-on endpoint at [mcp.openshorts.app](https://www.openshorts.app/mcp), API keys in one click |
| **Your data** | Your server | Ours |
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. The hosted plans exist to cover that hardware and those keys, not to unlock features.
https://github.com/user-attachments/assets/b45fa983-16b4-48b5-ac5b-a267836b9ad9
### Video Tutorial: How it works
[![OpenShorts Tutorial](https://img.youtube.com/vi/xlyjD1qCaX0/maxresdefault.jpg)](https://www.youtube.com/watch?v=xlyjD1qCaX0 "Click to watch the video on YouTube")
*Click the image above to watch the full walkthrough.*
> **Fork:** Clipwright is a fork of OpenShorts (<https://github.com/mutonby/openshorts>), MIT-licensed. Upstream copyright is preserved in [LICENSE](LICENSE) and [NOTICE](NOTICE).
---
## 3 Tools in 1 Platform
## 2 Tools in 1 Platform
### 1. Clip Generator
Turn your long-form videos — podcasts, webinars, livestreams, vlogs, interviews — into viral-ready 9:16 shorts for TikTok, Instagram Reels, and YouTube Shorts.
![Clip Results](screenshots/clip-results.png)
### 2. AI Shorts (UGC Video Creator)
Generate marketing videos with AI actors for **any product or business**. No camera, no studio, no influencer budget. Just describe your product or paste a URL.
![AI Shorts Setup](screenshots/ai-shorts.png)
- **Two cost modes**: Low Cost (~$0.65/video) and Premium (~$2/video)
- Works for any business: SaaS, restaurants, e-commerce, coaching, local businesses
- AI-generated actors with lip-sync, voiceover, b-roll, and TikTok-style subtitles
- Choose from a shared avatar gallery or upload your own photo
- Publish directly to TikTok, Instagram, and YouTube
### 3. YouTube Studio
Complete free AI YouTube toolkit: thumbnails, titles, descriptions, and direct publishing.
### 2. YouTube Studio
Free AI YouTube toolkit: thumbnails, titles and descriptions.
![YouTube Studio](screenshots/youtube-studio.png)
- AI thumbnail generator with face overlay
- 10 viral title suggestions with refinement chat
- Auto-generated descriptions with chapter timestamps
- One-click publish to YouTube
### UGC Video Gallery
All generated videos and avatars are saved to a public gallery with SEO pages for each video.
![UGC Gallery](screenshots/ugc-gallery.png)
- Public gallery page with hover-to-play (`/gallery`)
- Individual SEO video pages with og:video meta tags (`/video/{id}`)
- JSON-LD structured data for search engines
- Avatar gallery with prompt history
---
@ -85,37 +41,23 @@ All generated videos and avatars are saved to a public gallery with SEO pages fo
- **Runs fully local if you want**: point `LLM_BASE_URL` at Ollama, LM Studio, vLLM or any OpenAI-compatible server and the moment picker runs on your own model, no Google key needed (see [Run without a Google key](#6-run-without-a-google-key-local-llm-optional))
- **Smart 9:16 Cropping**: AI reframing per scene — TRACK mode (MediaPipe + YOLOv8 face tracking), GENERAL mode (blurred background), SPLIT mode (two speakers stacked, captions on the seam) and SCREENCAST mode (screen over presenter); the layout is picked per video by Gemini or forced from the dashboard
- **Auto Subtitles**: faster-whisper with word-level timestamps, styled and burned into clips
- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages with voice cloning
- **AI Voice Dubbing**: ElevenLabs integration for 30+ languages
- **Hook Text Overlays**: AI-generated attention-grabbing text overlays
- **AI Video Effects**: Gemini-generated FFmpeg filters for professional effects
### AI Shorts Pipeline
1. **Analyze**: Scrape website URL + web research, or generate from manual description
2. **Script**: AI writes viral scripts (hook - problem - solution - CTA format)
3. **Actor**: Generate AI actors with Flux 2 Pro or select from shared gallery
4. **Voice**: ElevenLabs TTS voiceover (English/Spanish, male/female)
5. **Video**: Talking head generation (Hailuo 2.3 Fast img2video + VEED Lipsync)
6. **B-roll**: AI-generated visuals with Ken Burns effect
7. **Composite**: FFmpeg final assembly with subtitles and hook overlays
8. **Publish**: Direct posting to TikTok, Instagram Reels, YouTube Shorts via Upload-Post
### YouTube Studio
- AI-powered title generation with 10 viral options
- Interactive refinement chat for titles
- AI thumbnail generation with custom face + background
- Auto descriptions with chapter timestamps from Whisper transcript
- Direct YouTube publishing via Upload-Post
- Auto descriptions with chapter timestamps from the Whisper transcript
### Social Auto-Publishing
- **One-click posting** to TikTok, Instagram Reels, and YouTube Shorts simultaneously
- **Schedule uploads** for any date and time — plan your content calendar and let OpenShorts publish automatically
- **Multi-platform distribution** — publish to all your social networks at once from a single interface
- Upload-Post integration with async uploads
### Postiz Publishing
- **One-click posting** to TikTok, Instagram Reels, and YouTube Shorts through your self-hosted Postiz instance
- **Schedule uploads** for any date and time — plan your content calendar and let Postiz publish
- **You own the credentials**: Postiz runs on your infrastructure and holds the platform tokens, so Clipwright never has them
### Infrastructure
- S3 cloud backup (private bucket for clips, public bucket for gallery/avatars)
- SEO gallery pages served by FastAPI with JSON-LD structured data
- Shared avatar gallery across all users
- S3 cloud backup (optional; private bucket for clips)
- Async job queue with configurable concurrency
---
@ -123,77 +65,34 @@ All generated videos and avatars are saved to a public gallery with SEO pages fo
## Who Is This For?
- **Content creators** — Turn long videos into shorts automatically, publish to all platforms at once
- **Marketing agencies** — Generate UGC videos for clients at scale, no actors or studios needed
- **SaaS founders** — Create product demos and marketing shorts from just a URL
- **E-commerce brands** — Product videos with AI actors for TikTok Shop, Instagram, YouTube
- **Local businesses** — Restaurants, gyms, real estate, coaching — affordable video marketing
- **Podcasters & educators** — Extract the most engaging moments from episodes and lessons
- **Developers** — Self-host, customize the pipeline, integrate via API
---
## AI Shorts Showcase
Videos generated with OpenShorts AI Shorts — no camera, no studio, no actors:
| | | |
|:---:|:---:|:---:|
| [![Biohacking for Investors](https://test-videos-upload-post.s3.eu-west-3.amazonaws.com/videos/cdceec1b/actor.png)](https://openshorts.app/video/cdceec1b) | [![Secret Weapon for Devs](https://test-videos-upload-post.s3.eu-west-3.amazonaws.com/videos/d3a80b6b/actor.png)](https://openshorts.app/video/d3a80b6b) | [![El Secreto de los Agentes de IA](https://test-videos-upload-post.s3.eu-west-3.amazonaws.com/videos/8ab7de92/actor.png)](https://openshorts.app/video/8ab7de92) |
| **Biohacking for Investors** · LOW COST | **Secret Weapon for Devs** · LOW COST | **El Secreto de los Agentes de IA** · PREMIUM |
> Browse all videos at [openshorts.app/gallery](https://openshorts.app/gallery)
---
## OpenShorts vs Competitors
| Feature | OpenShorts | Opus Clip | CapCut | Vizard | Klap | Descript |
|---------|:---:|:---:|:---:|:---:|:---:|:---:|
| **Price** | **Free self-hosted**<br>from $12/mo hosted | $15-29/mo | $8/mo | $15-20/mo | $23-63/mo | $24-65/mo |
| **Self-hosted** | **Yes** | No | No | No | No | No |
| **Open source** | **Yes** | No | No | No | No | No |
| **Watermark** | **Never self-hosted**<br>free plan only when hosted | Free tier | Some | Free tier | Free tier | Free tier |
| **Upload limits** | **None self-hosted**<br>by plan when hosted | 10-30GB | Credit-based | 60min-10hr | 10-100 vids/mo | 60min-40hr |
| **AI clip detection** | Yes | Yes | Yes | Yes | Yes | Yes |
| **Smart 9:16 reframing** | Yes | Yes | Yes | Yes | Yes | No |
| **Auto subtitles** | Yes | Yes | Yes | Yes | Yes | Yes |
| **Voice dubbing (30+ langs)** | Yes | No | Pro only | No | Pro only | Business only |
| **AI UGC actors** | **Yes** | No | No | No | No | No |
| **AI video effects** | Yes | No | Yes | No | No | No |
| **Hook text overlays** | Yes | No | No | No | No | No |
| **YouTube Studio (titles, thumbnails)** | **Yes** | No | No | No | No | No |
| **Social auto-publishing** | Yes | Pro only | TikTok only | Paid only | Paid only | No |
| **Schedule uploads** | Yes | Pro only | No | Paid only | Paid only | No |
| **Data privacy** | **Your server** | Their cloud | Their cloud | Their cloud | Their cloud | Their cloud |
| **Works with a local LLM (Ollama)** | **Yes** | No | No | No | No | No |
- **Privacy-conscious teams** — The source video stays on your infrastructure
---
## How Much Does It Cost?
Self-hosting OpenShorts is free. You provide the machine and you only pay for the AI APIs you use, and most have generous free tiers:
Self-hosting Clipwright is free. You provide the machine and you only pay for the AI APIs you use, and most have generous free tiers:
| Service | Free Tier | Paid Cost | Used For |
|---------|-----------|-----------|----------|
| **Google Gemini** | Free trial with generous limits | < $0.01 per 10-min video | Viral moment detection, script generation, web research |
| **Google Gemini** | Free trial with generous limits | < $0.01 per 10-min video | Viral moment detection, titles, thumbnails, descriptions |
| **Local LLM (Ollama, LM Studio, vLLM...)** | **Free, your hardware** | $0 | Viral moment detection instead of Gemini (`LLM_BASE_URL`) |
| **fal.ai** | Pay-per-use | ~$0.50-1.50 per AI Short | Actor generation, talking head video, lip-sync |
| **ElevenLabs** | Free tier available | Pay-per-use | Voiceover, voice dubbing |
| **Upload-Post** | **10 free uploads/month** to all networks (no credit card) | Pay-per-use | Auto-publishing to TikTok, Instagram, YouTube |
| **AWS S3** | Optional | ~$0.023/GB | Cloud backup for clips and gallery |
| **ElevenLabs** | Free tier available | Pay-per-use | Voice dubbing |
| **Postiz** | **Open source, self-hosted** | $0 (your hardware) | Publishing to TikTok, Instagram, YouTube |
| **AWS S3** | Optional | ~$0.023/GB | Backup for clips |
**Bottom line:** You can clip videos for practically free with Gemini, and publish 10 videos/month to all social networks at zero cost with Upload-Post.
**Don't want to run any of that?** [openshorts.app](https://www.openshorts.app/) is the same software on our hardware: our NVIDIA GPU clips an 8-minute video in about 50 seconds instead of the 5 to 8 minutes it takes on a typical CPU, the Gemini key is included, and auto-publishing is already wired up. Free plan is 20 minutes a month with a watermark and no credit card; paid plans start at $12/mo for 100 minutes without watermark.
**Bottom line:** you can clip and publish videos for practically free with a Gemini free-tier key and a self-hosted Postiz.
---
## Requirements
- **Docker & Docker Compose**
- **Google Gemini API Key** ([Free — get it here](https://aistudio.google.com/app/apikey)) — required for all AI features
- **fal.ai API Key** ([Pay-per-use](https://fal.ai)) — required for AI Shorts (actor generation, video, lip-sync)
- **ElevenLabs API Key** ([Free tier](https://elevenlabs.io)) — required for voiceover/dubbing
- **Upload-Post API Key** ([free tier](https://upload-post.com)) — required for direct social posting
- **Google Gemini API Key** ([Free — get it here](https://aistudio.google.com/app/apikey)) — required for all AI features unless `LLM_BASE_URL` is set
- **ElevenLabs API Key** ([Free tier](https://elevenlabs.io)) — optional, for voice dubbing
- **Self-hosted Postiz** ([Postiz docs](https://docs.postiz.com/)) — optional, for social publishing
---
@ -201,14 +100,14 @@ Self-hosting OpenShorts is free. You provide the machine and you only pay for th
### 1. Clone
```bash
git clone https://github.com/mutonby/openshorts.git
cd openshorts
git clone https://git.pbento.pt/pedro-bento/clipwright.git
cd clipwright
```
### 2. Configure (optional)
```bash
cp .env.example .env
# Edit .env with your AWS keys for S3 backup
# Edit .env with your AWS keys for S3 backup and your Postiz URL/key
```
### 3. Launch
@ -219,11 +118,9 @@ docker compose up --build
### 4. Open Dashboard
Navigate to **`http://localhost:5175`**
1. Go to **Settings** and enter your API keys (Gemini, fal.ai, ElevenLabs, Upload-Post)
1. Go to **Settings** and enter your API keys (Gemini, ElevenLabs) and your Postiz URL + API key
2. **Clip Generator**: Upload a long-form video to generate viral shorts
3. **AI Shorts**: Describe your product or paste a URL to generate UGC marketing videos
4. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube
5. **UGC Gallery**: Browse all generated videos and avatars
3. **YouTube Studio**: Generate thumbnails, titles, and descriptions for YouTube
### 5. GPU acceleration (optional, NVIDIA)
@ -266,8 +163,8 @@ ASR_GPU_CONCURRENCY=1
**Verify:**
```bash
docker compose up --build -d
docker exec openshorts-backend nvidia-smi -L
docker exec openshorts-backend ffmpeg -hide_banner -f lavfi -i testsrc=size=256x256:rate=1 -frames:v 1 -c:v h264_nvenc -f null -
docker exec clipwright-backend nvidia-smi -L
docker exec clipwright-backend ffmpeg -hide_banner -f lavfi -i testsrc=size=256x256:rate=1 -frames:v 1 -c:v h264_nvenc -f null -
```
The backend log on the first job reports the chosen encoder and transcription device. A CUDA error in whisper (e.g. VRAM exhausted) retries once on CPU automatically. 8 GB of VRAM is enough for `large-v3-turbo` fp16 plus the detection models.
@ -312,105 +209,46 @@ know:
5. **Extract** — FFmpeg precise clip cutting
6. **Reframe** — AI vertical cropping with subject tracking
7. **Effects** — Subtitles, hooks, AI video effects
8. **Publish** — S3 backup + Upload-Post social distribution
8. **Publish** — S3 backup + publishing through Postiz
### AI Shorts
1. **Analyze** — Website scraping + Gemini web research (or manual description)
2. **Script** — Gemini generates viral scripts with segments
3. **Actor** — Flux 2 Pro portrait generation (or gallery/upload)
4. **Voice** — ElevenLabs TTS voiceover
5. **Video** — Hailuo 2.3 Fast img2video + VEED Lipsync (Low Cost) or Kling Avatar v2 (Premium)
6. **B-roll** — Flux 2 Pro image generation + Ken Burns effect
7. **Composite** — FFmpeg assembly with ASS subtitles and hook overlays
8. **Gallery** — Upload to public S3 with metadata for SEO pages
9. **Publish** — Upload-Post to TikTok, Instagram, YouTube
### YouTube Studio
1. **Titles** — Gemini generates 10 options with an interactive refinement chat
2. **Thumbnails** — AI image generation with an optional uploaded face and background
3. **Descriptions** — auto-written from the Whisper transcript with chapter timestamps
---
## Automate It: MCP Server, REST API and Webhooks
## Automate It: REST API and Webhooks
You don't need the dashboard. The whole pipeline is callable by AI agents and scripts.
You don't need the dashboard. The pipeline is callable by scripts and workflows.
### MCP server (`/mcp`)
OpenShorts ships a built-in [MCP](https://modelcontextprotocol.io) server, so Claude, ChatGPT, Cursor or any MCP client can clip and publish videos for you:
**claude.ai and ChatGPT**: paste `https://mcp.openshorts.app/mcp` as a custom connector (Settings → Connectors) and approve the access on openshorts.app. The server does OAuth 2.1 with dynamic client registration, so there is no key to copy; the connection shows up under Account → API keys, where revoking it disconnects the app.
### REST API
```bash
# Claude Code / Cursor / n8n (hosted): create an API key in your account page
claude mcp add --transport http openshorts https://mcp.openshorts.app/mcp \
--header "Authorization: Bearer osk_..."
# Self-hosted (no key needed, BYOK rules apply):
claude mcp add --transport http openshorts http://localhost:8000/mcp
# Self-hosted without running the web server: same tools over stdio
claude mcp add openshorts -- python mcp_stdio.py
```
Tools: `process_video` (URL or `upload_id`; `captions: false` when the source already has subtitles, `auto_hook: false` to skip the hook line, burned by default like the dashboard), `create_upload` (hand the agent a local file: PUT the bytes, then process), `get_job_status`, `list_clips`, `get_quota`, `add_subtitles`, `recut_clip`, `publish_clip`. A prompt like *"clip this podcast and schedule the best 3 to TikTok"* is now a one-liner in your agent of choice.
### REST API + API keys
Hosted accounts can mint `osk_...` API keys (account page). A key authenticates as you everywhere — same plan, same minutes, same job ownership:
```bash
curl -X POST https://api.openshorts.app/api/process \
-H "Authorization: Bearer osk_..." -H "Content-Type: application/json" \
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_url": "https://your-server.com/hooks/clipwright"}'
```
Interactive docs at `/docs` (OpenAPI) on any instance.
### Completion webhooks
Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and you get exactly one `POST` when the job reaches a terminal state — no polling loops in your n8n / Zapier / cron pipelines:
Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and you get exactly one `POST` when the job reaches a terminal state — no polling loops in your n8n / cron pipelines:
```json
{"event": "job.completed", "job_id": "…",
"clips": [{"index": 0, "title": "…", "video_url": "…", "download_url": "…"}]}
"clips": [{"index": 0, "title": "…", "video_url": "…"}]}
```
With a secret, the body is signed: `X-OpenShorts-Signature: sha256=<hmac-sha256(body)>`.
### CLI
The same API from the terminal, zero dependencies (`cli/`):
```bash
pip install openshorts # or: uvx openshorts
export OPENSHORTS_API_KEY=osk_... # hosted
# export OPENSHORTS_API_URL=http://localhost:8000 # self-hosted, no key
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips <job_id>
openshorts publish <job_id> 0 --platforms tiktok,youtube
```
### Agent skill
`skills/openshorts/SKILL.md` follows the open
[Agent Skills](https://agentskills.io) standard, so it works in any
skill-capable agent:
```bash
# Claude Code (and most agents): copy the folder into the skills directory
cp -r skills/openshorts ~/.claude/skills/
# Hermes Agent: install straight from this repo
hermes skills install mutonby/openshorts/skills/openshorts
# OpenClaw: from ClawHub
openclaw skills install @mutonby/openshorts
```
With a secret, the body is signed: `X-Clipwright-Signature: sha256=<hmac-sha256(body)>`.
### n8n
An importable workflow (video URL in, published-ready clips out, no polling)
lives in [`examples/n8n/`](examples/n8n/).
An importable workflow (video URL in, clips out, no polling) lives in
[`examples/n8n/`](examples/n8n/). Publishing in the workflow goes through your
Postiz instance.
---
@ -420,9 +258,9 @@ lives in [`examples/n8n/`](examples/n8n/).
|-------|-----------|
| Backend | Python 3.11, FastAPI, google-genai, faster-whisper, ultralytics (YOLOv8), mediapipe, opencv-python, yt-dlp, FFmpeg, httpx |
| Frontend | React 18, Vite 4, Tailwind CSS 3.4 |
| AI APIs | Google Gemini, fal.ai (Flux, Hailuo, VEED, Kling), ElevenLabs |
| Infrastructure | Docker + Docker Compose, AWS S3 |
| Publishing | Upload-Post API (TikTok, Instagram, YouTube) |
| AI APIs | Google Gemini, ElevenLabs |
| Infrastructure | Docker + Docker Compose, AWS S3 (optional) |
| Publishing | Self-hosted [Postiz](https://postiz.com/) (TikTok, Instagram, YouTube) |
---
@ -431,24 +269,26 @@ lives in [`examples/n8n/`](examples/n8n/).
**Server-side (.env):**
| Variable | Description |
|----------|------------|
| `AWS_ACCESS_KEY_ID` | AWS access key for S3 |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key |
| `AWS_ACCESS_KEY_ID` | AWS access key for S3 (optional) |
| `AWS_SECRET_ACCESS_KEY` | AWS secret key (optional) |
| `AWS_REGION` | AWS region (default: us-east-1) |
| `AWS_S3_BUCKET` | Private bucket for clip backup |
| `AWS_S3_PUBLIC_BUCKET` | Public bucket for gallery/avatars |
| `AWS_S3_BUCKET` | Private bucket for clip backup (optional) |
| `MAX_CONCURRENT_JOBS` | Concurrent processing limit (default: 5) |
| `MAX_FILE_SIZE_MB` | Upload size cap in MB. `0` (default) is unlimited |
| `LLM_BASE_URL` | OpenAI-compatible server for the moment picker (Ollama, vLLM, LM Studio...). Set it and the Gemini key becomes optional |
| `LLM_MODEL` | Model name on that server (default `llama3.1:8b`) |
| `LLM_API_KEY` | Bearer token for that server, if it checks one |
| `LLM_SCORE_BATCH` | Transcript windows per scoring call (default 3 local, 8 Gemini) |
| `POSTIZ_URL` | Base URL of your self-hosted Postiz instance |
| `POSTIZ_API_KEY` | Postiz API key used server-side when the dashboard does not send one |
**Client-side (encrypted in localStorage):**
| Key | Description |
|-----|------------|
| `GEMINI_API_KEY` | Google Gemini — required unless `LLM_BASE_URL` is set (then only for layout picking and silent videos) |
| `FAL_KEY` | fal.ai — required for AI Shorts |
| `ELEVENLABS_API_KEY` | ElevenLabs — required for voiceover/dubbing |
| `UPLOAD_POST_API_KEY` | Upload-Post — required, for social posting |
| `ELEVENLABS_API_KEY` | ElevenLabs — optional, for voice dubbing |
| `postiz_url` | Base URL of your self-hosted Postiz instance |
| `postiz_key_v1` | Postiz API key, sent to the backend as `X-Postiz-Key` |
---
@ -459,30 +299,23 @@ lives in [`examples/n8n/`](examples/n8n/).
- **Auto-Cleanup**: Automatic purging of old jobs (1h retention)
- **Encrypted Keys**: API keys encrypted client-side, never stored server-side
- **Upload Validation**: Image uploads validated for format and minimum size
- **File Limits**: 2GB upload limit protection
- **Configurable File Limits**: `MAX_FILE_SIZE_MB` (0 = unlimited)
---
## Social Media Setup (Upload-Post)
## Social Publishing Setup (Postiz)
1. **Register**: [app.upload-post.com/login](https://app.upload-post.com/login)
2. **Create Profile**: Go to [Manage Users](https://app.upload-post.com/manage-users)
3. **Connect Accounts**: Link TikTok, Instagram, and/or YouTube
4. **Get API Key**: Navigate to [API Keys](https://app.upload-post.com/api-keys)
5. **Use in OpenShorts**: Paste the key in Settings
1. **Deploy Postiz**: run your own instance with Docker (see the [Postiz docs](https://docs.postiz.com/))
2. **Connect accounts**: link TikTok, Instagram and/or YouTube inside Postiz
3. **Create an API key**: in Postiz settings, generate a public API key
4. **Use in Clipwright**: paste the Postiz URL and key in Settings, then use "Test connection" to list the connected channels
---
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=mutonby/openshorts&type=Date)](https://star-history.com/#mutonby/openshorts&Date)
## Contributions
Contributions are welcome! Whether it's adding new AI models, improving the lip-sync pipeline, or building new features — feel free to open a PR.
Contributions are welcome! Whether it's improving the crop and subtitle pipeline or the dashboard — feel free to open a PR.
## License
MIT License for the core application — OpenShorts is yours to use, modify, and scale.
**Exception:** the [`cloud/`](cloud/LICENSE) directory (billing, managed keys, and the hosted-service infrastructure behind the optional `BILLING_ENABLED` flag) is source-available under the OpenShorts Commercial License. You can read it, modify it, and self-host it for personal or internal use, but you can't offer it to third parties as a paid/hosted service. Self-hosting the core app never requires this directory.
MIT License — Clipwright is yours to use, modify, and scale.

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"}

2985
app.py

File diff suppressed because it is too large Load diff

View file

@ -1,4 +1,4 @@
"""Render the OpenShorts watermark lockup (white mark + wordmark) to a PNG.
"""Render the Clipwright watermark lockup (white mark + wordmark) to a PNG.
Pre-rendered at 4x so it downscales cleanly onto any clip size, with a soft
dark shadow so it stays legible over bright footage.
@ -10,7 +10,7 @@ H = 64 * S # lockup height
PAD = 6 * S
font = ImageFont.truetype("/System/Library/Fonts/HelveticaNeue.ttc", int(38 * S), index=1) # Bold
text = "OpenShorts"
text = "Clipwright"
tmp = Image.new("RGBA", (10, 10))
tb = ImageDraw.Draw(tmp).textbbox((0, 0), text, font=font)

View file

@ -1,32 +1,58 @@
# OpenShorts CLI
# Clipwright 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
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips <job_id>
openshorts publish <job_id> 0 --platforms tiktok,youtube
openshorts quota
pip install clipwright # or: uvx clipwright / pipx run clipwright
```
Self-hosted instance? Point it at your own machine and skip the key:
## Use it against your own instance
Clipwright 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
export CLIPWRIGHT_API_URL=http://localhost:8000
clipwright process "https://youtube.com/watch?v=..." --wait
clipwright clips <job_id>
clipwright publish <job_id> 0 --platforms tiktok,youtube
clipwright quota
```
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.
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
`CLIPWRIGHT_API_KEY` (`clw_...`) as a bearer token.
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).
## 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
clipwright publish <job_id> 0 --platforms tiktok,youtube \
--postiz-url https://postiz.example.com --postiz-key <key>
```
## Quota
`clipwright 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
Clipwright POSTs once (HMAC-signed, `X-Clipwright-Signature: sha256=<hex>`) when
the job ends, with each clip's title and `video_url`. Set `PUBLIC_API_URL` on
the server so those links are absolute; otherwise they are relative to your
instance.
The agent-native version of the same surface is the Clipwright skill in
[`skills/clipwright/`](../skills/clipwright/).

View file

@ -1,14 +1,17 @@
"""OpenShorts CLI: clip long videos into vertical shorts from the terminal.
"""Clipwright 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.
Zero dependencies by design so `uvx clipwright` and `pipx run clipwright`
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_URL defaults to https://api.openshorts.app; set to
http://localhost:8000 for a self-hosted instance,
where no key is needed.
CLIPWRIGHT_API_KEY clw_... key for a deploy that requires one (optional;
a self-hosted instance needs none)
CLIPWRIGHT_API_URL defaults 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
@ -19,17 +22,19 @@ import time
import urllib.error
import urllib.request
DEFAULT_API = "https://api.openshorts.app"
DEFAULT_API = "http://localhost:8000"
POLL_SECONDS = 10
def _base():
return os.environ.get("OPENSHORTS_API_URL", DEFAULT_API).rstrip("/")
return os.environ.get("CLIPWRIGHT_API_URL", DEFAULT_API).rstrip("/")
def _request(method, path, body=None):
def _request(method, path, body=None, extra_headers=None):
headers = {"Accept": "application/json"}
key = os.environ.get("OPENSHORTS_API_KEY")
if extra_headers:
headers.update(extra_headers)
key = os.environ.get("CLIPWRIGHT_API_KEY")
if key:
headers["Authorization"] = f"Bearer {key}"
data = None
@ -97,7 +102,7 @@ def cmd_process(args):
if args.wait:
_watch(job_id, as_json=args.json)
else:
print(f"follow it with: openshorts status {job_id} --watch")
print(f"follow it with: clipwright status {job_id} --watch")
def _watch(job_id, as_json=False):
@ -154,20 +159,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 account/quota 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 +187,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}")
@ -190,8 +205,8 @@ def cmd_publish(args):
def main(argv=None):
parser = argparse.ArgumentParser(
prog="openshorts",
description="Clip long videos into vertical shorts via the OpenShorts API.",
prog="clipwright",
description="Clip long videos into vertical shorts via the Clipwright API.",
)
parser.add_argument("--json", action="store_true", help="raw JSON output")
sub = parser.add_subparsers(dest="command", required=True)
@ -201,7 +216,7 @@ def main(argv=None):
p.add_argument("--layouts", help="comma list: auto,split,screencast,speaker_cut,punch_in")
p.add_argument("--format", help="output format, e.g. 1080p")
p.add_argument("--webhook", help="webhook URL fired once when the job ends")
p.add_argument("--webhook-secret", help="HMAC secret for X-OpenShorts-Signature")
p.add_argument("--webhook-secret", help="HMAC secret for X-Clipwright-Signature")
p.add_argument("--wait", action="store_true", help="stream logs until the job ends")
p.set_defaults(func=cmd_process)
@ -214,16 +229,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

@ -1,49 +0,0 @@
Metadata-Version: 2.4
Name: openshorts
Version: 0.1.0
Summary: CLI for OpenShorts: clip long videos into vertical shorts and publish them, from the terminal
Author: OpenShorts
License: MIT
Project-URL: Homepage, https://www.openshorts.app
Project-URL: Source, https://github.com/mutonby/openshorts
Project-URL: Documentation, https://www.openshorts.app/mcp
Keywords: video,clips,shorts,ai,tiktok,youtube-shorts,cli
Classifier: Environment :: Console
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Multimedia :: Video
Requires-Python: >=3.9
Description-Content-Type: text/markdown
# 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.
```bash
pip install openshorts # or: uvx openshorts / pipx run openshorts
export OPENSHORTS_API_KEY=osk_... # from your account page at openshorts.app
openshorts process "https://youtube.com/watch?v=..." --wait
openshorts clips <job_id>
openshorts publish <job_id> 0 --platforms tiktok,youtube
openshorts quota
```
Self-hosted instance? Point it at your own machine and skip the key:
```bash
export OPENSHORTS_API_URL=http://localhost:8000
openshorts process "https://youtube.com/watch?v=..." --wait
```
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.
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).

View file

@ -1,8 +0,0 @@
README.md
openshorts_cli.py
pyproject.toml
openshorts.egg-info/PKG-INFO
openshorts.egg-info/SOURCES.txt
openshorts.egg-info/dependency_links.txt
openshorts.egg-info/entry_points.txt
openshorts.egg-info/top_level.txt

View file

@ -1,2 +0,0 @@
[console_scripts]
openshorts = openshorts_cli:main

View file

@ -1 +0,0 @@
openshorts_cli

View file

@ -3,13 +3,13 @@ requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "openshorts"
name = "clipwright"
version = "0.1.0"
description = "CLI for OpenShorts: clip long videos into vertical shorts and publish them, from the terminal"
description = "CLI for Clipwright: clip long videos into vertical shorts and publish them, from the terminal"
readme = "README.md"
requires-python = ">=3.9"
license = { text = "MIT" }
authors = [{ name = "OpenShorts" }]
authors = [{ name = "Clipwright" }]
keywords = ["video", "clips", "shorts", "ai", "tiktok", "youtube-shorts", "cli"]
classifiers = [
"Environment :: Console",
@ -19,12 +19,12 @@ classifiers = [
]
[project.urls]
Homepage = "https://www.openshorts.app"
Source = "https://github.com/mutonby/openshorts"
Documentation = "https://www.openshorts.app/mcp"
Homepage = "https://git.pbento.pt/pedro-bento/clipwright"
Source = "https://git.pbento.pt/pedro-bento/clipwright"
Documentation = "https://git.pbento.pt/pedro-bento/clipwright/tree/main/cli"
[project.scripts]
openshorts = "openshorts_cli:main"
clipwright = "clipwright_cli:main"
[tool.setuptools]
py-modules = ["openshorts_cli"]
py-modules = ["clipwright_cli"]

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,400 +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
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 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)."""
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
if not _watch_down.get(name):
if _watch_strikes[name] < _PROXY_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 {_PROXY_STRIKES} probes 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
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)
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,753 +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
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"]
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,148 +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.
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
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
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 _clean(text: Optional[str]) -> Optional[str]:
text = (text or "").strip()
return text or None
@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.")
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.")
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),
))
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,70 +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)",
)
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,325 +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.</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,702 +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 = []
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)})
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,465 +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 cancellation made through the dashboard flow. 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)
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,105 +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 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,494 +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
router = APIRouter()
def _clip_title(clip) -> str:
return clip.get("title") or clip.get("video_title_for_youtube_short") or "Short"
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}")
# A captioned hook is a chain (subtitled_<ts>_hooked_<ts>_<clean>):
# the hooked_ intermediate must come back too, or a restored project's
# caption restyle cannot walk back to the hook-only file and would
# silently drop or stack layers.
m = re.match(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$', filename)
if m:
mid_path = os.path.join(output_dir, m.group(1))
if os.path.exists(mid_path):
mid_key = storage.job_key(user_id, job_id, m.group(1))
try:
await asyncio.to_thread(storage.upload_file, mid_path, mid_key)
except Exception as e:
print(f"⚠️ R2 upload failed for {mid_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)
# Same chain rule as archive_job: a captioned hook needs its hooked_
# intermediate archived too, or the restored project cannot re-style.
m = re.match(r'^subtitled_\d+_((?:hooked_\d+_|hook_).+)$', new_filename)
if m:
mid_path = os.path.join(output_dir, m.group(1))
if os.path.exists(mid_path):
try:
await asyncio.to_thread(
storage.upload_file, mid_path,
storage.job_key(user_id, job_id, m.group(1)))
except Exception as e:
print(f"⚠️ R2 upload failed for hook intermediate of {job_id}: {e}")
metadata_r2_key = None
meta_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
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_key = None
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")
if prev and prev not in (entry.get("original_file"), new_filename):
superseded_key = storage.job_key(user_id, job_id, prev)
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))
if superseded_key and superseded_key != new_key:
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

@ -1,11 +1,13 @@
import js from '@eslint/js'
import globals from 'globals'
import react from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
// `public/` holds vendored/minified assets (e.g. op1.js) — not our source.
globalIgnores(['dist', 'public']),
{
files: ['**/*.{js,jsx}'],
extends: [
@ -13,6 +15,7 @@ export default defineConfig([
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
],
plugins: { react },
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
@ -28,6 +31,10 @@ export default defineConfig([
'no-unused-vars': ['error', {
varsIgnorePattern: '^[A-Z_]', argsIgnorePattern: '^_', caughtErrors: 'none',
}],
// Core no-unused-vars does not count JSX tags as references, so a
// destructured component param (`({ icon: Icon }) => <Icon/>`) reads as
// unused. This rule marks those identifiers used.
'react/jsx-uses-vars': 'error',
// Contexts and modals export a hook or a constant next to the component.
'react-refresh/only-export-components': ['error', { allowConstantExport: true }],
},

View file

@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/logo-openshorts.png" />
<link rel="icon" type="image/png" href="/logo-clipwright.png" />
<!-- viewport-fit=cover so the bottom tab bar can pad itself past the iOS home
indicator with env(safe-area-inset-bottom); without it that inset reads 0. -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
@ -21,62 +21,60 @@
<!-- Title and description are kept under 60 and 160 characters (measured, not
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="author" content="OpenShorts" />
<title>Clipwright - 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, no watermark and no cap." />
<meta name="author" content="Clipwright" />
<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,
so pointing this at the apex named a URL that only ever redirects. -->
<link rel="canonical" href="https://www.openshorts.app/" />
<link rel="canonical" href="https://git.pbento.pt/pedro-bento/clipwright/" />
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website" />
<meta property="og:url" content="https://www.openshorts.app/" />
<meta property="og:url" content="https://git.pbento.pt/pedro-bento/clipwright/" />
<meta property="og:title"
content="OpenShorts - Open Source AI Clip Generator" />
content="Clipwright - 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." />
<meta property="og:image" content="https://www.openshorts.app/og-image.png" />
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://git.pbento.pt/pedro-bento/clipwright/og-image.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:site_name" content="OpenShorts" />
<meta property="og:site_name" content="Clipwright" />
<meta property="og:locale" content="en_US" />
<!-- Twitter Cards -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:url" content="https://www.openshorts.app/" />
<meta name="twitter:url" content="https://git.pbento.pt/pedro-bento/clipwright/" />
<meta name="twitter:title"
content="OpenShorts - Open Source AI Clip Generator" />
content="Clipwright - 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." />
<meta name="twitter:image" content="https://www.openshorts.app/og-image.png" />
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://git.pbento.pt/pedro-bento/clipwright/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",
"@graph": [
{
"@type": "WebSite",
"@id": "https://www.openshorts.app/#website",
"url": "https://www.openshorts.app/",
"name": "OpenShorts",
"publisher": { "@id": "https://www.openshorts.app/#organization" },
"@id": "https://git.pbento.pt/pedro-bento/clipwright/#website",
"url": "https://git.pbento.pt/pedro-bento/clipwright/",
"name": "Clipwright",
"publisher": { "@id": "https://git.pbento.pt/pedro-bento/clipwright/#organization" },
"inLanguage": "en-US"
},
{
"@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.",
"url": "https://www.openshorts.app/",
"isPartOf": { "@id": "https://www.openshorts.app/#website" },
"about": { "@id": "https://www.openshorts.app/#software" },
"@id": "https://git.pbento.pt/pedro-bento/clipwright/#webpage",
"name": "Clipwright - 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 open source under MIT, self-hosted with Docker, with no watermark and no cap.",
"url": "https://git.pbento.pt/pedro-bento/clipwright/",
"isPartOf": { "@id": "https://git.pbento.pt/pedro-bento/clipwright/#website" },
"about": { "@id": "https://git.pbento.pt/pedro-bento/clipwright/#software" },
"datePublished": "2024-06-01",
"dateModified": "2026-07-27",
"inLanguage": "en-US",
@ -87,19 +85,19 @@
},
{
"@type": "SoftwareApplication",
"@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.",
"@id": "https://git.pbento.pt/pedro-bento/clipwright/#software",
"name": "Clipwright",
"alternateName": "Clipwright 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. 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/",
"downloadUrl": "https://github.com/mutonby/openshorts",
"codeRepository": "https://github.com/mutonby/openshorts",
"url": "https://git.pbento.pt/pedro-bento/clipwright/",
"downloadUrl": "https://git.pbento.pt/pedro-bento/clipwright",
"codeRepository": "https://git.pbento.pt/pedro-bento/clipwright",
"license": "https://opensource.org/licenses/MIT",
"isAccessibleForFree": true,
"softwareVersion": "2.0",
"screenshot": "https://www.openshorts.app/og-image.png",
"screenshot": "https://git.pbento.pt/pedro-bento/clipwright/og-image.png",
"featureList": [
"AI viral moment detection with Google Gemini 3.1 Flash-Lite",
"Smart 9:16 vertical cropping with MediaPipe face tracking and YOLOv8 fallback",
@ -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,83 +117,33 @@
"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"
}
}
]
}
"author": { "@id": "https://git.pbento.pt/pedro-bento/clipwright/#organization" }
},
{
"@type": "FAQPage",
"@id": "https://www.openshorts.app/#faq",
"@id": "https://git.pbento.pt/pedro-bento/clipwright/#faq",
"mainEntity": [
{
"@type": "Question",
"name": "What is OpenShorts?",
"name": "What is Clipwright?",
"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": "Clipwright 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."
}
},
{
"@type": "Question",
"name": "Is OpenShorts free? What is the catch?",
"name": "Is Clipwright 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."
"text": "There is no catch. Clipwright 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."
}
},
{
"@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."
}
},
{
"@type": "Question",
"name": "How does OpenShorts detect viral moments in videos?",
"name": "How does Clipwright detect viral moments in videos?",
"acceptedAnswer": {
"@type": "Answer",
"text": "It uses a multi-step pipeline. faster-whisper transcribes the video with word-level timestamps. PySceneDetect identifies the scene boundaries. Google Gemini 3.1 Flash-Lite then receives the timestamped transcript and the scene data together, and returns the 3 to 15 strongest segments of 15 to 60 seconds each, scored on hook strength, emotional payload and whether the segment stands alone without its surrounding context. Passing the transcript and the scene boundaries together is what stops a clip from starting mid-shot."
@ -216,12 +162,12 @@
"name": "Is there a free alternative to Opus Clip?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. OpenShorts self-hosted is a free and open source alternative to Opus Clip, MIT licensed, with no watermark and no usage cap, running on your own machine via Docker. As of July 2026 Opus Clip costs $15 per month for the Starter plan with 150 minutes, and $29 per month for Pro with 300 minutes, on top of a watermarked free tier of 60 minutes. Opus Clip bills one credit per minute of source video imported rather than per clip exported. OpenShorts offers comparable AI moment detection using Google Gemini, face-tracked vertical cropping and automatic subtitles, and adds AI voice dubbing into 30+ languages, which Opus Clip does not have. Opus Clip ships a larger caption-style library and needs no setup."
"text": "Yes. Clipwright self-hosted is a free and open source alternative to Opus Clip, MIT licensed, with no watermark and no usage cap, running on your own machine via Docker. As of July 2026 Opus Clip costs $15 per month for the Starter plan with 150 minutes, and $29 per month for Pro with 300 minutes, on top of a watermarked free tier of 60 minutes. Opus Clip bills one credit per minute of source video imported rather than per clip exported. Clipwright offers comparable AI moment detection using Google Gemini, face-tracked vertical cropping and automatic subtitles, and adds AI voice dubbing into 30+ languages, which Opus Clip does not have. Opus Clip ships a larger caption-style library and needs no setup."
}
},
{
"@type": "Question",
"name": "Can OpenShorts add subtitles and translate videos?",
"name": "Can Clipwright add subtitles and translate videos?",
"acceptedAnswer": {
"@type": "Answer",
"text": "Yes. Subtitles are generated with faster-whisper at word-level timestamps and burned into the video with FFmpeg. For translation, ElevenLabs AI dubbing translates the audio into more than 30 languages while preserving the original speaker's voice characteristics, and the dubbed audio is then automatically re-transcribed so the burned-in subtitles are in the target language rather than the original."
@ -232,25 +178,25 @@
"name": "Is there an open source clip generator?",
"acceptedAnswer": {
"@type": "Answer",
"text": "OpenShorts is the open source option in this category, MIT licensed with full source at github.com/mutonby/openshorts, self-hosted with Docker Compose. Opus Clip, Klap, Vizard and Submagic are all closed-source cloud products; as of July 2026 their entry prices are $15, $29, $19.99 and around $14 per month respectively. Self-hosting means the source video never leaves your machine and you can change how the pipeline behaves rather than filing a feature request."
"text": "Clipwright is the open source option in this category, MIT licensed with full source at git.pbento.pt/pedro-bento/clipwright, self-hosted with Docker Compose. Opus Clip, Klap, Vizard and Submagic are all closed-source cloud products; as of July 2026 their entry prices are $15, $29, $19.99 and around $14 per month respectively. Self-hosting means the source video never leaves your machine and you can change how the pipeline behaves rather than filing a feature request."
}
}
]
},
{
"@type": "Organization",
"@id": "https://www.openshorts.app/#organization",
"name": "OpenShorts",
"url": "https://www.openshorts.app/",
"@id": "https://git.pbento.pt/pedro-bento/clipwright/#organization",
"name": "Clipwright",
"url": "https://git.pbento.pt/pedro-bento/clipwright/",
"logo": {
"@type": "ImageObject",
"url": "https://www.openshorts.app/logo-openshorts.png"
"url": "https://git.pbento.pt/pedro-bento/clipwright/logo-clipwright.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": "Clipwright 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",
"https://creatorstoolbox.com/tools/openshorts"
"https://git.pbento.pt/pedro-bento/clipwright",
"https://www.aitoolnet.com/clipwright",
"https://creatorstoolbox.com/tools/clipwright"
]
}
]
@ -292,7 +238,7 @@
// Second gate: hosts allowed to report. A dist/ built with credentials
// stays inert anywhere else (a fork, a mirror, a preview domain), so a
// deployment can never report into somebody else's dashboard.
var ANALYTICS_HOSTS = /^(www\.)?openshorts\.app$/;
var ANALYTICS_HOSTS = /^(www\.)?clipwright\.app$/;
if (!ANALYTICS_HOSTS.test(location.hostname)) return false;
started = true;

View file

@ -10,8 +10,8 @@
# it first.
server {
listen 80;
server_name openshorts.app;
return 301 https://www.openshorts.app$request_uri;
server_name git.pbento.pt;
return 301 https://git.pbento.pt/pedro-bento/clipwright$request_uri;
}
server {
@ -30,17 +30,6 @@ server {
try_files $uri =404;
}
# The public gallery and per-video pages are server-rendered by the backend
# and only exist on api.openshorts.app. The README has always linked them
# here, where they silently served the landing page instead. Send them to
# the host that actually has them rather than answering with the wrong page.
location /gallery {
return 301 https://api.openshorts.app$request_uri;
}
location /video/ {
return 301 https://api.openshorts.app$request_uri;
}
# index.html must NOT be cached — it points at the hashed asset bundle, so a
# stale cached copy keeps loading the previous deploy's JS. (nginx add_header
# doesn't inherit into a location that sets its own, so the security headers

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
{
"name": "openshorts-app",
"name": "clipwright-app",
"private": true,
"version": "0.0.0",
"type": "module",
@ -28,6 +28,7 @@
"@vitejs/plugin-react": "^4.2.1",
"autoprefixer": "^10.4.23",
"eslint": "^9.39.5",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.26",
"globals": "^15.15.0",

View file

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View file

@ -1,4 +1,4 @@
# robots.txt for OpenShorts
# robots.txt for Clipwright
# Search crawlers and AI crawlers are both welcome. Note that the AI crawlers
# below do not execute JavaScript, so what they read is the static HTML shipped
# by the build (the injected homepage content plus the standalone pages under
@ -66,4 +66,4 @@ Allow: /
User-agent: CCBot
Allow: /
Sitemap: https://www.openshorts.app/sitemap.xml
Sitemap: https://git.pbento.pt/pedro-bento/clipwright/sitemap.xml

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

View file

@ -1,301 +0,0 @@
/* /auto-clip and /youtube-automation: the two pages about running a channel's
* clipping without opening the app.
*
* Every rule stated here is a constant in cloud/autopilot.py (checked
* 23-sep-2026); if one changes there, change it here. Screenshots are the real
* Autopilot tab in production with the connected channel's name, handle,
* thumbnails and video titles blurred: that channel belongs to someone who did
* not agree to be on a marketing page. The usage numbers are aggregates over
* all accounts from usage_ledger, nothing per user.
*/
import { SITE } from './data.js'
import { esc } from './render.js'
const PUBLISHED = '2026-09-23'
const faqBlock = (faq) =>
`<h2>Common questions</h2><dl class="faq">${faq
.map((f) => `<dt>${esc(f.q)}</dt><dd>${esc(f.a)}</dd>`)
.join('')}</dl>`
const sources = (items) =>
`<h2>Sources</h2><ul class="sources">${items.map((s) => `<li>${s}</li>`).join('')}</ul>`
/* Checked against GET https://api.openshorts.app/api/billing/plans on
* 23-sep-2026. Autopilot is in every paid plan and in none of the free ones. */
const PLANS = [
['Starter', '$12/month', '100 minutes'],
['Creator', '$29/month', '300 minutes'],
['Pro', '$59/month', '750 minutes'],
]
/* usage_ledger, job_type "process", status committed, 24-aug to 23-sep-2026. */
const USAGE = { jobs: '4,641', minutes: '56,590', median: 12, window: '24 August to 23 September 2026' }
const plansTable = `
<table>
<thead><tr><th>Plan</th><th>Price</th><th>Source video per month</th><th>Autopilot</th></tr></thead>
<tbody>
<tr><td>Free</td><td>$0</td><td>20 minutes, watermarked</td><td>No (clip by hand)</td></tr>
${PLANS.map(([n, p, m]) => `<tr><td class="os">${n}</td><td>${p}</td><td>${m}</td><td class="yes">Yes</td></tr>`).join('\n')}
</tbody>
</table>
<p class="sources">Prices from the OpenShorts billing API, checked 23 September 2026. Yearly plans cost ten times the monthly price.</p>`
const autoClip = () => ({
path: '/auto-clip',
title: 'Auto Clip Your YouTube Videos Into Shorts | OpenShorts',
description:
'Autopilot auto clips every new video on your YouTube channel into vertical shorts with subtitles and can post the best ones daily. Rules, limits, price.',
h1: 'Auto clip: every new YouTube video turned into shorts on its own',
breadcrumb: [{ name: 'Auto clip' }],
published: PUBLISHED,
updated: PUBLISHED,
relatedTitle: 'Related',
related: ['/youtube-automation', '/n8n-youtube-shorts-automation', '/how-openshorts-works'],
cta: {
label: 'Autopilot',
title: 'Connect your channel once',
body: 'Included in every paid plan from $12/month. On the free plan you can still clip any video by hand.',
button: 'Open Autopilot',
href: `${SITE.url}/#app?tab=autopilot`,
},
tldr: [
'Automatic clipping means software watches a long video, picks the moments that stand on their own and cuts them into short vertical clips. OpenShorts does that for any video you paste, and Autopilot does it for every new upload on your YouTube channel without you opening anything.',
'Autopilot checks your channel about once an hour, clips each new video (only videos published after you switch it on, at most one a day, the first 10 to 90 minutes of each), emails you when the clips are ready and, if you turn on autopublish, schedules the best 1 to 5 of them one a day on TikTok, Instagram and YouTube Shorts.',
],
body: `
<h2>What "auto clip" does, step by step</h2>
<ol>
<li><strong>Transcribe.</strong> The audio is transcribed with word-level timestamps, so every clip can start and end on a word.</li>
<li><strong>Find the cuts.</strong> Scene detection marks where the picture changes.</li>
<li><strong>Score the moments.</strong> Google Gemini reads the transcript and rates stretches of 15 to 60 seconds on whether they make sense alone and hold attention, then keeps the 3 to 15 best.</li>
<li><strong>Reframe to 9:16.</strong> Face tracking keeps the speaker in the frame; screen recordings and two-person shots get their own layouts.</li>
<li><strong>Subtitle and title.</strong> Captions are burned in from the transcript and each clip gets a hook and a title.</li>
</ol>
<p>That pipeline is the same whether you paste a link by hand or Autopilot starts
it. The details are on <a href="/how-openshorts-works">how OpenShorts works</a>.
Across all accounts, OpenShorts Cloud ran ${USAGE.jobs} clipping jobs on
${USAGE.minutes} minutes of source video between ${USAGE.window}; the median
source video was ${USAGE.median} minutes long.</p>
<h2>Autopilot: the channel clips itself</h2>
<figure class="shot">
<img src="/screens/autopilot-settings.webp" width="920" height="672" loading="eager"
alt="The Autopilot tab in OpenShorts: a connected YouTube channel, the Autopilot switch turned on with the first 10 minutes of each video selected, and the autopublish switch off.">
<figcaption>The Autopilot tab in production, 23 September 2026. The channel name is blurred because it belongs to a user.</figcaption>
</figure>
<p>You connect your YouTube channel once. From then on Autopilot reads your
channel's uploads through the YouTube account you connected, so it also sees
videos you upload straight to YouTube, and it clips them through the normal
pipeline. The rules are deliberately conservative, because it spends your
plan's minutes while you are not looking:</p>
<ul>
<li><strong>Only new videos.</strong> Switching it on never clips your back catalogue: only videos published after that moment, and only while they are at most 3 days old.</li>
<li><strong>One automatic video a day.</strong> If you publish three videos in a day, the others wait for you. You can still clip up to 5 more a day by hand from the same tab.</li>
<li><strong>A cap per video.</strong> Autopilot clips the first 10, 20, 30, 45, 60 or 90 minutes of each video (30 by default), so a three-hour stream cannot empty your plan.</li>
<li><strong>Shorts are skipped.</strong> A video that is already a Short is not clipped again.</li>
<li><strong>You get an email</strong> when the clips of each video are ready.</li>
</ul>
<figure class="shot">
<img src="/screens/autopilot-channel-videos.webp" width="920" height="454" loading="lazy"
alt="The latest videos list in the Autopilot tab: each upload with its date, a clips count or not clipped, and open or clip it buttons.">
<figcaption>Your latest uploads, what Autopilot did with each, and a "clip it" button for any of them. Titles and thumbnails blurred.</figcaption>
</figure>
<h2>Autopublish: the best clips go out one a day</h2>
<p>Off by default. Turn it on and, for each video, Autopilot takes the 1 to 5
clips with the highest predicted score (3 by default) and schedules them one per
day at the hour you choose, in your own time zone, on the accounts you pick:
TikTok, Instagram and YouTube Shorts. TikTok clips arrive as drafts in your
TikTok inbox, so you open the app to post them. Leave autopublish off and you
review and post the clips yourself.</p>
<h2>What it costs</h2>
<p>Autopilot runs on your plan's minutes, so it is part of the paid plans and not
the free one. A 30-minute cap per video uses at most 30 minutes of your plan for
that video.</p>
${plansTable}
<p>The free plan still includes the clip generator itself: 20 minutes a month,
with a watermark, clipped by hand. Or self-host the
<a href="/open-source-video-clipper">open source video clipper</a> and wire the
same automation yourself with the
<a href="/n8n-youtube-shorts-automation">n8n workflow</a>.</p>
<h2>What it does not do</h2>
<ul>
<li>It only watches YouTube. Podcasts, Twitch VODs or files on your drive have to be pasted or sent through <a href="/automate-shorts-api">the API</a>.</li>
<li>It does not guarantee views. It picks the moments the model scores highest; some weeks those will be the wrong ones, which is why autopublish is off until you turn it on.</li>
<li>It is new: Autopilot launched on 22 September 2026.</li>
</ul>
${faqBlock([
{
q: 'What is auto clipping?',
a: 'Software that watches a long video, finds the moments that work on their own and cuts them into short vertical clips with subtitles, instead of you scrubbing the timeline by hand. OpenShorts returns 3 to 15 clips of 15 to 60 seconds per video.',
},
{
q: 'Can OpenShorts clip my new YouTube videos automatically?',
a: 'Yes. Autopilot checks your connected channel about once an hour and clips each new video on its own: only videos published after you switch it on, at most one a day, up to the minute cap you set.',
},
{
q: 'Does Autopilot post the clips for me?',
a: 'Only if you turn on autopublish. Then it schedules the best 1 to 5 clips of each video one a day on TikTok, Instagram and YouTube Shorts. TikTok clips arrive as drafts you post from the app.',
},
{
q: 'Is automatic clipping free?',
a: 'Clipping a video you paste is free for 20 minutes a month on OpenShorts Cloud, or unlimited if you self-host. Autopilot, which runs on its own, is included in the paid plans from $12/month.',
},
{
q: 'Will it clip my whole back catalogue and burn my minutes?',
a: 'No. It only picks up videos published after you switch it on, at most 3 days old, one a day, and only the first 10 to 90 minutes of each.',
},
])}
${sources([
`Autopilot rules: <code>cloud/autopilot.py</code> in the <a href="${SITE.repo}" rel="noopener">OpenShorts source</a>, checked 23 September 2026.`,
'Usage figures: OpenShorts Cloud billing ledger, all accounts aggregated, 24 August to 23 September 2026.',
])}
`,
faq: [
{ q: 'What is auto clipping?', a: 'Software that finds the moments of a long video that work on their own and cuts them into short vertical clips with subtitles. OpenShorts returns 3 to 15 clips of 15 to 60 seconds per video.' },
{ q: 'Can OpenShorts clip my new YouTube videos automatically?', a: 'Yes. Autopilot checks your connected channel about once an hour and clips each new video: only videos published after you switch it on, at most one a day.' },
{ q: 'Does Autopilot post the clips for me?', a: 'Only if you turn on autopublish. Then it schedules the best 1 to 5 clips of each video one a day on TikTok, Instagram and YouTube Shorts.' },
{ q: 'Is automatic clipping free?', a: 'Clipping a pasted video is free for 20 minutes a month, or unlimited self-hosted. Autopilot is included in the paid plans from $12/month.' },
],
})
const youtubeAutomation = () => ({
path: '/youtube-automation',
title: 'YouTube Automation for Shorts, Step by Step | OpenShorts',
description:
'Automate the repetitive part of a real YouTube channel: clip every upload into Shorts, schedule them, or wire it to n8n, the API or Claude over MCP.',
h1: 'YouTube automation: hand the repetitive work to software, keep the channel yours',
breadcrumb: [{ name: 'YouTube automation' }],
published: PUBLISHED,
updated: PUBLISHED,
relatedTitle: 'Related',
related: ['/auto-clip', '/n8n-youtube-shorts-automation', '/mcp'],
cta: {
label: 'Start with no code',
title: 'Turn on Autopilot for your channel',
body: 'Every new upload clipped on its own, the best clips scheduled one a day if you want. In every paid plan from $12/month.',
button: 'Open Autopilot',
href: `${SITE.url}/#app?tab=autopilot`,
},
tldr: [
'"YouTube automation" means two different things. One is faceless channels that mass-produce videos from templates; YouTube demonetises that as inauthentic content. The other is taking the repetitive work off a real channel: cutting every long video into Shorts, writing the metadata, scheduling the posts. This page is about the second.',
'With OpenShorts there are three ways to automate it: Autopilot in the app (no code), the n8n template (you approve each clip from Telegram), or the REST API and MCP server for your own scripts and for agents like Claude and ChatGPT.',
],
body: `
<h2>What is worth automating on a YouTube channel</h2>
<p>The work that does not need your judgement, every single week:</p>
<ul>
<li><strong>Cutting Shorts from each long video.</strong> Finding the moments, reframing to 9:16, adding subtitles. This is the slowest part to do by hand and the easiest to automate well.</li>
<li><strong>Posting them on a schedule</strong> to YouTube Shorts, TikTok and Instagram, one a day instead of all at once.</li>
<li><strong>The first draft of titles, descriptions and tags.</strong> You still edit them; the free <a href="/youtube-tag-generator">tag, title and description generator</a> writes the draft.</li>
<li><strong>Transcripts</strong> for show notes and blog posts, from the <a href="/youtube-transcript-generator">transcript generator</a>.</li>
</ul>
<p>What should stay yours: the long video itself, and the decision to publish.
YouTube's monetisation policy was changed on 15 July 2025 to name "inauthentic
content", which includes "AI-generated content made with generic or unoriginal
templates giving the impression of mass production". Automating the chores of a
channel you actually make is not that. Generating the channel is.</p>
<h2>Three ways to automate it, from no code to full control</h2>
<table>
<thead><tr><th>Route</th><th>Who it is for</th><th>You approve each post?</th><th>What you need</th></tr></thead>
<tbody>
<tr><td class="os">Autopilot</td><td>Creators who want it done, no setup</td><td>Your choice: autopublish on or off</td><td>A paid plan, your YouTube channel connected</td></tr>
<tr><td class="os">n8n template</td><td>People who already run n8n</td><td>Yes, from Telegram</td><td>n8n, an OpenShorts API key, a Telegram bot</td></tr>
<tr><td class="os">API and MCP</td><td>Developers and AI agents</td><td>Whatever your code decides</td><td>An API key, or a claude.ai / ChatGPT connector</td></tr>
</tbody>
</table>
<h2>Route 1: Autopilot, no code</h2>
<ol>
<li>Sign in to OpenShorts and open the <strong>Autopilot</strong> tab.</li>
<li>Connect your YouTube channel.</li>
<li>Switch Autopilot on, confirm you own the content, and choose how many minutes of each video to clip (10 to 90).</li>
<li>Optionally switch on autopublish: pick TikTok, Instagram and/or YouTube Shorts, how many clips per video (1 to 5) and the hour to post.</li>
</ol>
<figure class="shot">
<img src="/screens/autopilot-settings.webp" width="920" height="672" loading="eager"
alt="The Autopilot settings in OpenShorts: connected channel, Autopilot on with a 10 minute cap, autopublish off.">
<figcaption>Autopilot in production, 23 September 2026. Channel name blurred.</figcaption>
</figure>
<p>From then on Autopilot looks at your channel about once an hour, starts a
job for each new upload it finds and emails you when the clips are ready. The exact rules (one automatic
video a day, only new videos, Shorts skipped) are on the
<a href="/auto-clip">auto clip page</a>.</p>
<h2>Route 2: the n8n template, with a human in the loop</h2>
<figure class="shot">
<img src="/n8n-content-machine-workflow.png" width="950" height="750" loading="lazy"
alt="The OpenShorts content machine workflow open in n8n, from the channel trigger to Telegram approval and weekly analytics.">
<figcaption>The importable n8n workflow: watch the channel, clip, approve from Telegram, drip-publish, report weekly.</figcaption>
</figure>
<p>If you run n8n, the free <a href="/n8n-youtube-shorts-automation">n8n YouTube
Shorts template</a> does the same job with one difference that matters: every
clip reaches your Telegram with Publish and Skip buttons, and nothing goes out
until you tap Publish. It reads your channel's public RSS feed, so it needs no
YouTube API key, and a self-hosted OpenShorts works too: change the base URL in
the workflow.</p>
<h2>Route 3: the API and MCP, for your own code and for agents</h2>
<p>Everything the app does is one HTTP call away. <code>POST /api/process</code>
takes a video URL and a <code>webhook_url</code>, and OpenShorts calls you back
once with the finished clips; the details and a working example are on
<a href="/automate-shorts-api">automate shorts with the API</a>. The same
pipeline is exposed as an MCP server, so Claude, ChatGPT, Cursor or n8n's agent
node can clip and publish when you ask them in plain language.</p>
<figure class="shot">
<img src="/screens/connect-an-agent.webp" width="684" height="366" loading="lazy"
alt="The connect an agent card in the OpenShorts account page, with setup steps for claude.ai and the MCP server URL https://mcp.openshorts.app/mcp.">
<figcaption>Connecting Claude takes one URL: <code>https://mcp.openshorts.app/mcp</code>. The card also has tabs for ChatGPT, Claude Code, Claude Desktop, Cursor, n8n and curl.</figcaption>
</figure>
<p>More on the tools the server exposes on the <a href="/mcp">MCP server page</a>.</p>
<h2>What it costs</h2>
<p>Autopilot, the API and MCP all use the same minutes as the app: 20 free
minutes a month on the free plan (Autopilot itself needs a paid plan), then
$12/month for 100 minutes, $29 for 300 or $59 for 750, as of 23 September 2026.
Self-hosting the MIT licensed code is free with no minute cap; you pay for your
own hardware and API keys.</p>
${faqBlock([
{
q: 'Is YouTube automation allowed?',
a: 'Automating chores on a channel you create is fine. What YouTube does not monetise is inauthentic content: mass-produced, generic or repetitive videos, including AI-generated content made from generic templates. Clipping your own long videos into Shorts is not that.',
},
{
q: 'Can I automate YouTube Shorts from my long videos?',
a: 'Yes. OpenShorts Autopilot clips each new upload on your channel into vertical Shorts with subtitles and can schedule the best ones one a day. The n8n template and the API do the same for people who want to build their own flow.',
},
{
q: 'Do I need to code?',
a: 'No. Autopilot is a switch in the app. The n8n template needs n8n; the API and the MCP server are for developers and AI agents.',
},
{
q: 'Can an AI agent run my channel with OpenShorts?',
a: 'An agent such as Claude or ChatGPT can call OpenShorts over MCP to clip a video, list the clips and publish them. Whether it publishes without asking you is up to how you set it up; the n8n template keeps a human approval step on purpose.',
},
])}
${sources([
'<a href="https://support.google.com/youtube/answer/1311392" rel="noopener">YouTube channel monetization policies</a> (inauthentic content, renamed from repetitious content on 15 July 2025), checked 23 September 2026.',
`Autopilot rules: <code>cloud/autopilot.py</code> in the <a href="${SITE.repo}" rel="noopener">OpenShorts source</a>; plan prices from the OpenShorts billing API, both checked 23 September 2026.`,
])}
`,
faq: [
{ q: 'Is YouTube automation allowed?', a: 'Automating chores on a channel you create is fine. YouTube does not monetise inauthentic content: mass-produced, generic or repetitive videos, including AI-generated content from generic templates.' },
{ q: 'Can I automate YouTube Shorts from my long videos?', a: 'Yes. OpenShorts Autopilot clips each new upload into vertical Shorts with subtitles and can schedule the best ones one a day.' },
{ q: 'Do I need to code?', a: 'No. Autopilot is a switch in the app. The n8n template needs n8n; the API and MCP server are for developers and AI agents.' },
],
})
export function autopilotPages() {
return [autoClip(), youtubeAutomation()]
}

View file

@ -6,49 +6,37 @@
* 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. Clipwright 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 = {
// www is what the apex already redirects to, so it is the canonical host.
url: 'https://www.openshorts.app',
name: 'OpenShorts',
repo: 'https://github.com/mutonby/openshorts',
logo: 'https://www.openshorts.app/logo-openshorts.png',
ogImage: 'https://www.openshorts.app/og-image.png',
url: 'https://git.pbento.pt/pedro-bento/clipwright',
name: 'Clipwright',
repo: 'https://git.pbento.pt/pedro-bento/clipwright',
logo: 'https://git.pbento.pt/pedro-bento/clipwright/logo-clipwright.png',
ogImage: 'https://git.pbento.pt/pedro-bento/clipwright/og-image.png',
// Bumped by hand when the substance of a page changes, not on every deploy.
updated: '2026-08-04',
published: '2024-06-01',
}
/* Profiles that let an engine resolve "OpenShorts" to one entity. The repo has
/* Profiles that let an engine resolve "Clipwright" to one entity. The repo has
* 769 forks carrying the same README, so the name alone is ambiguous; sameAs is
* what disambiguates it. Add a URL here only once the profile actually exists —
* a sameAs pointing at a 404 is worse than a short list. */
export const SAME_AS = [
'https://github.com/mutonby/openshorts',
'https://www.aitoolnet.com/openshorts',
'https://creatorstoolbox.com/tools/openshorts',
'https://git.pbento.pt/pedro-bento/clipwright',
]
/* 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: 'Clipwright',
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.',
},
}
@ -57,9 +45,9 @@ export const EDITIONS = {
* exactly what happens to them. */
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.',
'Clipwright 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. Clipwright 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.',
}
@ -87,7 +75,7 @@ export const PIPELINE_STEPS = [
},
{
title: 'Dubbing and publishing',
body: 'ElevenLabs dubbing translates the audio into 30+ languages while preserving the speaker\'s voice, and the dubbed track is re-transcribed so the subtitles match the new language. Finished clips post directly to TikTok, Instagram Reels and YouTube Shorts.',
body: 'ElevenLabs dubbing translates the audio into 30+ languages while preserving the speaker\'s voice, and the dubbed track is re-transcribed so the subtitles match the new language. Finished clips publish to TikTok, Instagram Reels and YouTube Shorts through a self-hosted Postiz instance.',
},
]
@ -114,13 +102,13 @@ export const COMPETITORS = {
'No setup at all, because it is a cloud service and always has been',
],
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 and an AI UGC generator with lip-synced actors; Opus Clip has neither.',
'Clipwright can be self-hosted, so the source video never leaves your machine. Opus Clip is cloud only.',
'Clipwright is MIT-licensed and auditable. Opus Clip is closed source.',
'Clipwright 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:
'Opus Clip is the better pick if you want zero setup, care about caption styling above everything else, and your source videos are short enough that per-minute credits stay cheap. OpenShorts is the better pick if you want to self-host for privacy or cost, need dubbing, or want to read and change the code.',
'Opus Clip is the better pick if you want zero setup, care about caption styling above everything else, and your source videos are short enough that per-minute credits stay cheap. Clipwright is the better pick if you want to self-host for privacy or cost, need dubbing, or want to read and change the code.',
},
klap: {
name: 'Klap',
@ -134,12 +122,12 @@ export const COMPETITORS = {
'Almost no learning curve, one screen and one export button',
],
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.',
'Clipwright exposes the reframing, subtitle and hook stages so you can change what you do not like; Klap deliberately does not.',
'Clipwright 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:
'Klap is the better pick when speed to a first clip matters more than control. OpenShorts is the better pick when you need to tune the output, self-host, or keep the monthly cost under $29.',
'Klap is the better pick when speed to a first clip matters more than control. Clipwright is the better pick when you need to tune the output, self-host, or keep the monthly cost under $29.',
},
vizard: {
name: 'Vizard',
@ -154,7 +142,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. Clipwright is free, MIT-licensed, with no watermark and no usage cap.',
},
{
q: 'What is Vizard AI used for?',
@ -169,12 +157,12 @@ export const COMPETITORS = {
'Strong multi-language subtitle support',
],
whereWeDiffer: [
'OpenShorts runs the whole pipeline unattended and is designed to be scripted or scheduled; Vizard expects a human in the timeline.',
'OpenShorts is open source and self-hostable; Vizard is a closed cloud product.',
'Clipwright runs the whole pipeline unattended and is designed to be scripted or scheduled; Vizard expects a human in the timeline.',
'Clipwright is open source and self-hostable; Vizard is a closed cloud product.',
'Vizard\'s editor is better than ours if you want to hand-correct each clip before posting.',
],
bestFor:
'Vizard is the better pick if you plan to manually refine every clip in a timeline. OpenShorts is the better pick for volume, automation, or self-hosting.',
'Vizard is the better pick if you plan to manually refine every clip in a timeline. Clipwright is the better pick for volume, automation, or self-hosting.',
},
submagic: {
name: 'Submagic',
@ -195,33 +183,32 @@ export const COMPETITORS = {
'Very fast on short inputs because it is not doing moment detection',
],
whereWeDiffer: [
'OpenShorts does the moment detection Submagic leaves out, so it replaces the pair rather than one half of it.',
'Clipwright does the moment detection Submagic leaves out, so it replaces the pair rather than one half of it.',
'Submagic\'s caption designs are more refined than ours. If captions are the entire reason you are shopping, it is the stronger tool.',
'OpenShorts self-hosted has no per-video cap; every Submagic tier is metered in videos per month.',
'Clipwright self-hosted has no per-video cap; every Submagic tier is metered in videos per month.',
],
bestFor:
'Submagic is the better pick if you already cut your own clips and only want captions. OpenShorts is the better pick if you are starting from long-form video and want the cutting done too.',
'Submagic is the better pick if you already cut your own clips and only want captions. Clipwright is the better pick if you are starting from long-form video and want the cutting done too.',
},
}
/* 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: 'AI UGC video with lip-synced actors', os: 'Yes, from $0.65/video', 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

@ -46,10 +46,7 @@ const FEATURES = [
['Local video upload', 'Podcasts, webinars, livestreams, interviews and vlogs, at full resolution, from a file or a YouTube link.'],
['Self-hosted and private', 'Run it with Docker on your own machine and the source video never leaves your infrastructure.'],
['Free AI YouTube studio', 'AI thumbnail generator, 10 viral title suggestions and auto-written descriptions with chapter timestamps.'],
['Direct social publishing', 'Post to TikTok, Instagram Reels and YouTube Shorts from the dashboard.'],
['MCP server, API and CLI for AI agents', 'Connect Claude, ChatGPT or n8n to an always-on endpoint (mcp.openshorts.app/mcp) and automate clipping end to end, with a REST API, per-user keys, completion webhooks and a zero-dependency CLI (pip install openshorts). Guide at /mcp.'],
['AI UGC video generator', 'The AI writes a script and generates a lip-synced avatar video for any product or business, from $0.65 per video.'],
['AI actors with lip-sync', 'Pick an AI actor or upload a photo to get a talking-head video with matched lip movement.'],
['Direct social publishing', 'Publish to TikTok, Instagram Reels and YouTube Shorts from the dashboard through a self-hosted Postiz instance.'],
]
const STEPS = [
@ -57,36 +54,28 @@ const STEPS = [
['AI finds the best moments', 'Gemini 3.1 Flash-Lite returns 3 to 15 candidate clips of 15 to 60 seconds each.'],
['Smart cropping to vertical 9:16', 'Face-tracked reframing keeps the subject centred without the camera swinging.'],
['Subtitles, hooks and effects', 'Word-level subtitles, an AI hook overlay, optional effects and dubbing into 30+ languages.'],
['Download or post directly', 'Export the clips or publish straight to TikTok, Instagram Reels and YouTube Shorts.'],
['Download or post directly', 'Export the clips or publish straight to TikTok, Instagram Reels and YouTube Shorts through Postiz.'],
]
const FAQ = [
[
'Is OpenShorts free? What is the catch?',
'Is Clipwright 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],
['What is Clipwright and how does it work?', CANONICAL_ANSWERS.whatIsIt + ' ' + CANONICAL_ANSWERS.howItWorks],
[
'How does OpenShorts compare to Opus Clip?',
'Both do AI viral moment detection and smart vertical cropping. OpenShorts is MIT-licensed and can be self-hosted, so the source video never leaves your machine, and it adds voice dubbing into 30+ languages plus an AI UGC generator with lip-synced actors. Opus Clip is closed source and cloud only, starting at $15/month as of July 2026, and it ships a larger caption-style library. Full comparison at /alternatives/opus-clip.',
'How does Clipwright compare to Opus Clip?',
'Both do AI viral moment detection and smart vertical cropping. Clipwright is MIT-licensed and can be self-hosted, so the source video never leaves your machine, and it adds voice dubbing into 30+ languages. Opus Clip is closed source and cloud only, starting at $15/month as of July 2026, and it ships a larger caption-style library. Full comparison at /alternatives/opus-clip.',
],
[
'How does the smart vertical cropping work?',
'TRACK mode follows a single subject with MediaPipe face detection and a YOLOv8 fallback, damped so the crop holds still inside a safe zone rather than chasing every head movement. GENERAL mode handles group shots and landscapes by preserving the full width over a blurred backdrop. A speaker tracker prevents the crop from flipping between people and holds position through brief occlusions.',
],
[
'Can OpenShorts translate and dub videos?',
'Can Clipwright translate and dub videos?',
'Yes, into more than 30 languages through ElevenLabs, preserving the original speaker\'s voice characteristics. After dubbing, the audio is re-transcribed so the burned-in subtitles are in the target language rather than the original.',
],
[
'What is the AI UGC video generator?',
'It generates marketing videos with AI actors for any product or business. You describe the business or paste a website URL, and the AI writes a script, generates a lip-synced actor with voiceover, adds b-roll, subtitles and a hook overlay. Low Cost mode is about $0.65 per video and Premium is about $2.00. It works for restaurants, e-commerce, coaching, local businesses and apps, not only software.',
],
[
'Can I automate OpenShorts from Claude, ChatGPT or n8n?',
'Yes. OpenShorts has a native MCP server at mcp.openshorts.app/mcp plus a REST API with per-user keys and completion webhooks, so an agent can submit a video URL, wait for processing, list the clips and publish them. The hosted endpoint is always on, with the API key created in your account page; the self-hosted edition serves the same /mcp endpoint while your machine is running. A zero-dependency CLI is on PyPI as openshorts. Full guide at /mcp.',
],
[
'What are the system requirements to self-host?',
'Any machine with Docker, realistically 8GB of RAM and a modern multi-core CPU. An NVIDIA GPU is optional and cuts processing time by roughly an order of magnitude. Docker Compose pulls Python 3.11, FFmpeg, YOLOv8, MediaPipe, faster-whisper and the React dashboard. Linux, macOS and Windows via WSL2 are supported.',
@ -99,14 +88,14 @@ 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, or generate UGC marketing videos with AI actors. Online in the cloud with zero setup, or self-hosted with Docker for free. Also a clipping tool for AI agents: Claude, ChatGPT and n8n drive it over <a href="/mcp" style="${S.a}">MCP</a>, or run a channel on autopilot with <a href="/auto-clip" style="${S.a}">Autopilot</a> or 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 your own self-hosted <a href="https://postiz.com/" 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://git.pbento.pt/pedro-bento/clipwright" 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}">
<h2 style="${S.h2}">what openshorts is</h2>
<h2 style="${S.h2}">what clipwright is</h2>
<p style="${S.p};max-width:48rem">${CANONICAL_ANSWERS.whatIsIt}</p>
<p style="${S.p};max-width:48rem">${CANONICAL_ANSWERS.howItWorks}</p>
</div></section>
@ -114,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('Clipwright &middot; $0, forever', EDITIONS.selfHosted.summary)}
</div>
</div></section>
@ -133,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. Clipwright 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. Clipwright 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;
@ -144,14 +132,12 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<a style="${S.a}" href="/youtube-transcript-generator">YouTube transcript generator</a> &middot;
<a style="${S.a}" href="/youtube-tag-generator">YouTube tag generator</a> &middot;
<a style="${S.a}" href="/video-aspect-ratio-converter">Video to 9:16 converter</a> &middot;
<a style="${S.a}" href="/auto-clip">Auto clip</a> &middot;
<a style="${S.a}" href="/youtube-automation">YouTube automation</a> &middot;
<a style="${S.a}" href="/free-ai-clip-generator-no-watermark">No-watermark clip generator</a> &middot;
<a style="${S.a}" href="/open-source-video-clipper">Open source video clipper</a> &middot;
<a style="${S.a}" href="/open-source-ai-video-generator">Open source AI video generator</a> &middot;
<a style="${S.a}" href="/podcast-to-shorts">Podcast to shorts</a> &middot;
<a style="${S.a}" href="/youtube-to-shorts-converter">YouTube to Shorts converter</a> &middot;
<a style="${S.a}" href="/how-openshorts-works">How it works</a> &middot;
<a style="${S.a}" href="/how-clipwright-works">How it works</a> &middot;
<a style="${S.a}" href="/alternatives">All alternatives compared</a> &middot;
<a style="${S.a}" href="/alternativas">Alternativas (ES)</a> &middot;
<a style="${S.a}" href="/opus-clip-pricing">Opus Clip pricing</a> &middot;
@ -160,9 +146,8 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<a style="${S.a}" href="/opus-pro">Opus Pro</a> &middot;
<a style="${S.a}" href="/vizard-ai-video-to-text">Vizard AI video to text</a> &middot;
<a style="${S.a}" href="/submagic-reviews">Submagic review</a> &middot;
<a style="${S.a}" href="/mcp">MCP server &amp; API</a> &middot;
<a style="${S.a}" href="/automate-shorts-api">Automate shorts via API</a> &middot;
<a style="${S.a}" href="/n8n-youtube-shorts-automation">n8n template: channel on autopilot</a>
<a style="${S.a}" href="/n8n-youtube-shorts-automation">n8n template</a>
</p>
</div></section>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -270,12 +270,11 @@ const buildGraph = (page) => {
const NAV = `
<header class="site"><div class="wrap">
<a class="brand" href="${SITE.url}/"><img src="/logo-openshorts.png" alt="OpenShorts logo" width="26" height="26">OpenShorts</a>
<a class="brand" href="${SITE.url}/"><img src="/logo-clipwright.png" alt="Clipwright logo" width="26" height="26">Clipwright</a>
<nav class="nav">
<a href="/free-ai-clip-generator">Clip generator</a>
<a href="/tools" class="keep">Free tools</a>
<a href="/alternatives">Alternatives</a>
<a href="/mcp">MCP &amp; API</a>
<a href="${SITE.repo}" rel="noopener">GitHub</a>
</nav>
<a class="cta" href="${SITE.url}/">Get free clips</a>
@ -284,7 +283,7 @@ const NAV = `
const footer = (_related) => `
<footer class="site"><div class="wrap">
<div class="row">
<a href="${SITE.url}/">OpenShorts</a>
<a href="${SITE.url}/">Clipwright</a>
<a href="${SITE.repo}" rel="noopener">Source on GitHub</a>
<a href="/free-ai-clip-generator">Free AI clip generator</a>
<a href="/free-ai-clip-generator-no-watermark">No-watermark clip generator</a>
@ -293,10 +292,9 @@ const footer = (_related) => `
<a href="/podcast-to-shorts">Podcast to shorts</a>
<a href="/youtube-to-shorts-converter">YouTube to Shorts converter</a>
<a href="/gta-5-clips">GTA 5 clips</a>
<a href="/how-openshorts-works">How it works</a>
<a href="/how-clipwright-works">How it works</a>
<a href="/alternatives">Alternatives compared</a>
<a href="/alternativas">Alternativas (ES)</a>
<a href="/mcp">MCP server and API</a>
<a href="/automate-shorts-api">Automate shorts</a>
</div>
<div class="row">
@ -304,8 +302,6 @@ const footer = (_related) => `
<a href="/youtube-transcript-generator">YouTube transcript generator</a>
<a href="/youtube-tag-generator">YouTube tag, title and description generator</a>
<a href="/video-aspect-ratio-converter">Video to 9:16 converter</a>
<a href="/auto-clip">Auto clip</a>
<a href="/youtube-automation">YouTube automation</a>
</div>
<div class="row">
<a href="/opus-clip-pricing">Opus Clip pricing</a>
@ -315,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>Clipwright 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.
@ -347,7 +342,7 @@ const ANALYTICS = `
var clientId = "%VITE_OPENPANEL_CLIENT_ID%";
var unset = function (v) { return !v || v.charAt(0) === "%"; };
if (unset(apiUrl) || unset(clientId)) return false;
var ANALYTICS_HOSTS = /^(www\\.)?openshorts\\.app$/;
var ANALYTICS_HOSTS = /^(www\\.)?clipwright\\.app$/;
if (!ANALYTICS_HOSTS.test(location.hostname)) return false;
started = true;
window.op("init", {
@ -371,7 +366,7 @@ const ANALYTICS = `
/* First-touch attribution for visits that start on a static page.
*
* The app snapshots where a visitor came from (src/lib/attribution.js, key
* os_attrib) and posts it at signup, but that code only runs once React
* cw_attrib) and posts it at signup, but that code only runs once React
* boots, i.e. on the homepage. A visitor who landed here from Google and then
* clicked through arrived at the app with a same-origin referrer and
* landing_path "/", so every signup was credited to the homepage: 7,481 of
@ -384,7 +379,7 @@ const ATTRIBUTION = `
<script>
(function () {
try {
var K = "os_attrib";
var K = "cw_attrib";
if (localStorage.getItem(K)) return;
var q = new URLSearchParams(location.search);
var r = document.referrer || "";
@ -414,13 +409,12 @@ 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) => {
const c = { ...DEFAULT_CTA, ...(page.cta || {}) }
// Pages about Autopilot send readers to the app tab, not the landing page.
const target = c.href || `${SITE.url}/`
const href = target
return `
@ -467,7 +461,7 @@ export function renderPage(page, related = [], { cta = true, toolScript = '' } =
${page.noindex ? '' : `<link rel="canonical" href="${canonical}">\n`}<meta name="robots" content="${
page.noindex ? 'noindex,follow' : 'index,follow,max-image-preview:large,max-snippet:-1'
}">
<link rel="icon" type="image/png" href="/logo-openshorts.png">
<link rel="icon" type="image/png" href="/logo-clipwright.png">
<link rel="stylesheet" href="/fonts.css">
${ANALYTICS}
${page.noindex ? '' : ATTRIBUTION}
@ -498,7 +492,7 @@ ${
page.noindex
? ''
: `<div class="byline">
By the OpenShorts team<span class="sep">·</span>
By the Clipwright team<span class="sep">·</span>
Published <time datetime="${esc(page.published || SITE.published)}">${esc(page.published || SITE.published)}</time><span class="sep">·</span>
Updated <time datetime="${esc(page.updated || SITE.updated)}">${esc(page.updated || SITE.updated)}</time>
</div>`

View file

@ -1,5 +1,4 @@
/* The free tools (/tools) and the two automation pages built around
* Autopilot (/auto-clip, /youtube-automation).
/* The free tools (/tools) and the three tool pages.
*
* Tool pages carry `tool: { entry, html }`. The html is the tool's real form,
* rendered straight into the static document right under the H1, so it is in
@ -61,17 +60,17 @@ export const TOOLS = [
const toolsHub = () => ({
path: '/tools',
title: 'Free Tools for YouTube and Short-Form Video | OpenShorts',
title: 'Free Tools for YouTube and Short-Form Video | Clipwright',
description:
'Free YouTube tools with no sign-up: transcript generator, tag, title and description generator, and a video to 9:16 converter that runs in your browser.',
h1: 'Free tools for YouTube and short-form video',
lede: 'Three small tools that do one job each, free and without an account. They come from the same team as the OpenShorts clip generator.',
lede: 'Three small tools that do one job each, free and without an account. They come from the same team as the Clipwright clip generator.',
breadcrumb: [{ name: 'Free tools' }],
published: PUBLISHED,
updated: PUBLISHED,
cta: false,
relatedTitle: 'Also on this site',
related: ['/auto-clip', '/youtube-automation', '/free-ai-clip-generator'],
related: ['/free-ai-clip-generator', '/youtube-transcript-generator', '/open-source-video-clipper'],
body: `
<div class="tools-grid">
${TOOLS.map((t) => `<a href="${t.path}"><strong>${esc(t.name)}</strong><span>${esc(t.blurb)}</span></a>`).join('\n')}
@ -94,10 +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. To have every new upload on your channel clipped without opening
anything, see <a href="/auto-clip">auto clip with Autopilot</a>.</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: [],
})
@ -127,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? Clipwright 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>
@ -144,7 +141,7 @@ const EXAMPLES = [
const transcriptPage = () => ({
path: '/youtube-transcript-generator',
title: 'YouTube Transcript Generator: Free, TXT and SRT | OpenShorts',
title: 'YouTube Transcript Generator: Free, TXT and SRT | Clipwright',
description:
'Paste a YouTube link, get the full transcript with timestamps. Copy it or download TXT or SRT. Free, no sign-up, works with auto-generated captions.',
h1: 'YouTube transcript generator',
@ -181,7 +178,7 @@ ${EXAMPLES.map(([id, label, note]) => `<li><button type="button" class="btn-ghos
not processed yet, and channels that turned automatic captions off. Private,
members-only and age-restricted videos cannot be read either. In those cases the
tool says so rather than inventing text. If you need the words anyway, the
<a href="/free-ai-clip-generator">OpenShorts clip generator</a> runs its own
<a href="/free-ai-clip-generator">Clipwright clip generator</a> runs its own
speech recognition with word-level timing and uses it to cut the video into
subtitled vertical clips.</p>
@ -253,7 +250,7 @@ const metadataTool = `
<div id="md-status" class="tool-status" role="status" aria-live="polite" hidden></div>
<div id="md-out" class="out" hidden></div>
<div id="md-cta" class="cta-inline" hidden>
<p>Got the long video done? OpenShorts cuts it into vertical Shorts with subtitles, and its YouTube Studio writes titles from the video itself.</p>
<p>Got the long video done? Clipwright cuts it into vertical Shorts with subtitles, and its YouTube Studio writes titles from the video itself.</p>
<a id="md-cta-btn" class="btn-primary" href="${SITE.url}/">Clip the video</a>
</div>
</section>`
@ -273,7 +270,7 @@ const SAMPLE_TITLES = [
const metadataPage = () => ({
path: '/youtube-tag-generator',
title: 'YouTube Tag, Title and Description Generator | OpenShorts',
title: 'YouTube Tag, Title and Description Generator | Clipwright',
description:
'Free YouTube tag generator that also writes titles and descriptions from a short brief. Stays inside YouTube\'s limits: 100-character titles, 500 for tags.',
h1: 'YouTube tag, title and description generator',
@ -284,7 +281,7 @@ const metadataPage = () => ({
cta: false,
tool: { entry: 'tool-metadata', html: metadataTool },
relatedTitle: 'More free tools',
related: ['/youtube-transcript-generator', '/video-aspect-ratio-converter', '/youtube-automation'],
related: ['/youtube-transcript-generator', '/video-aspect-ratio-converter', '/youtube-to-shorts-converter'],
body: `
<h2>How to use it</h2>
<ol>
@ -330,7 +327,7 @@ ${faqBlock([
},
{
q: 'Which AI writes the titles and descriptions?',
a: 'Google Gemini, the same model family OpenShorts uses to pick clips and write titles in its YouTube Studio.',
a: 'Google Gemini, the same model family Clipwright uses to pick clips and write titles in its YouTube Studio.',
},
{
q: 'Does it work in other languages?',
@ -397,7 +394,7 @@ const verticalTool = `
<p id="vc-info" class="tool-hint"></p>
<p><button type="button" id="vc-download" class="btn-primary">Download</button></p>
<div class="cta-inline">
<p>Is someone talking in it? OpenShorts reframes with face tracking so the speaker stays in the frame, and cuts the long video into clips with subtitles.</p>
<p>Is someone talking in it? Clipwright reframes with face tracking so the speaker stays in the frame, and cuts the long video into clips with subtitles.</p>
<a id="vc-cta-btn" class="btn-primary" href="${SITE.url}/">Try the clip generator</a>
</div>
</div>
@ -406,7 +403,7 @@ const verticalTool = `
const verticalPage = () => ({
path: '/video-aspect-ratio-converter',
title: 'Video Aspect Ratio Converter (16:9 to 9:16) | OpenShorts',
title: 'Video Aspect Ratio Converter (16:9 to 9:16) | Clipwright',
description:
'Convert a video to 9:16 for TikTok, Reels and Shorts in your browser: blurred background, crop or black bars. Free, no upload, no watermark.',
h1: 'Video aspect ratio converter: 16:9 to 9:16 in your browser',
@ -446,7 +443,7 @@ keep a browser tab stable: the first 5 minutes of the video and files up to
<h2>When a fixed crop is not enough</h2>
<p>A fixed crop cannot follow a person who moves, and it cannot show two people
talking at the same time. That is what the
<a href="/youtube-to-shorts-converter">OpenShorts YouTube to Shorts converter</a>
<a href="/youtube-to-shorts-converter">Clipwright YouTube to Shorts converter</a>
does: it tracks faces with MediaPipe so the speaker stays in the frame, can stack
two people talking in a split screen, and cuts the long video into 3 to 15 clips
with subtitles.</p>
@ -473,7 +470,7 @@ ${faqBlock([
${sources([
'<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebCodecs_API" rel="noopener">MDN: WebCodecs API</a>, the browser encoder this tool uses.',
`<a href="https://github.com/Vanilagy/mediabunny" rel="noopener">Mediabunny</a>, the open source library that reads and writes the video files. Face tracking in the clip generator: the project source at <a href="${SITE.repo}" rel="noopener">github.com/mutonby/openshorts</a>.`,
`<a href="https://github.com/Vanilagy/mediabunny" rel="noopener">Mediabunny</a>, the open source library that reads and writes the video files. Face tracking in the clip generator: the project source at <a href="${SITE.repo}" rel="noopener">git.pbento.pt/pedro-bento/clipwright</a>.`,
])}
`,
faq: [

File diff suppressed because it is too large Load diff

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, Bot } from 'lucide-react';
import PricingSection from './components/PricingSection';
import { useAuth } from './contexts/AuthContext';
import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors, Link2 } from 'lucide-react';
import './landing.css';
// 64 deterministic tick heights: gaussian envelope × sine wave (no randomness)
@ -47,10 +45,10 @@ const StepCard = ({ number, title, description }) => (
</div>
);
const ComparisonRow = ({ feature, openshorts, opusclip, kapwing }) => (
const ComparisonRow = ({ feature, clipwright, opusclip, kapwing }) => (
<tr className="border-b border-rule">
<td className="py-3 px-4 text-sm text-ink2">{feature}</td>
<td className="py-3 px-4 text-center">{openshorts}</td>
<td className="py-3 px-4 text-center">{clipwright}</td>
<td className="py-3 px-4 text-center">{opusclip}</td>
<td className="py-3 px-4 text-center">{kapwing}</td>
</tr>
@ -74,17 +72,16 @@ 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();
if (url) {
try { localStorage.setItem('os_pending_url', url); } catch { /* ignore */ }
try { localStorage.setItem('cw_pending_url', url); } catch { /* ignore */ }
}
onLaunchApp();
};
@ -137,23 +134,8 @@ export default function Landing({ onLaunchApp }) {
},
{
icon: Globe,
title: "Direct Social Publishing",
description: "Post to TikTok, Instagram Reels, and YouTube Shorts from the dashboard."
},
{
icon: Bot,
title: "MCP Server, API & CLI for AI Agents",
description: "Connect Claude, ChatGPT or n8n to an always-on endpoint, or run pip install openshorts and clip from the terminal. Same pipeline, no dashboard needed."
},
{
icon: Sparkles,
title: "AI UGC Video Generator",
description: "AI writes the script and generates a lip-synced avatar video — from $0.65/video."
},
{
icon: FileVideo,
title: "AI Actors & Lip-Sync",
description: "Pick an AI actor or upload a photo for a lip-synced talking head video."
title: "Postiz Publishing",
description: "Publish to TikTok, Instagram Reels, and YouTube Shorts through a self-hosted Postiz instance."
}
];
@ -162,65 +144,53 @@ export default function Landing({ onLaunchApp }) {
{ title: "AI Detects the Best Viral Moments", description: "Google Gemini 3.1 Flash-Lite finds 3-15 high-potential clips of 15-60 seconds." },
{ title: "Smart Cropping to Vertical 9:16", description: "AI reframes to vertical with face tracking — subjects stay centered." },
{ title: "Add Subtitles, Hooks & Effects", description: "Auto subtitles, hook overlays, AI effects — optionally dub into 30+ languages." },
{ title: "Download or Post to Social Media", description: "Export your clips or post directly to TikTok, Instagram Reels, and YouTube Shorts." }
{ title: "Download or Post to Social Media", description: "Export your clips or publish to TikTok, Instagram Reels, and YouTube Shorts through Postiz." }
];
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 and fal.ai for AI Shorts if you want those. (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, auto-posting to TikTok, Instagram and YouTube is already wired up, 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: "Is Clipwright really free? What's the catch?",
answer: "There is no catch. Clipwright 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?",
answer: "OpenShorts is a free, open source AI clip generator that transforms your long-form videos — podcasts, webinars, livestreams, vlogs, interviews — into viral-ready short clips in 9:16 vertical format. It uses a multi-step AI pipeline: faster-whisper for transcription with word-level timestamps, PySceneDetect for scene boundary detection, and Google Gemini 3.1 Flash-Lite AI for identifying the most engaging viral moments. According to HubSpot's 2025 State of Marketing report, short-form video delivers the highest ROI of any content format, and repurposing long-form content into shorts increases total reach by up to 300%."
question: "What is Clipwright and how does it work?",
answer: "Clipwright is a free, open source AI clip generator that transforms your long-form videos — podcasts, webinars, livestreams, vlogs, interviews — into viral-ready short clips in 9:16 vertical format. It uses a multi-step AI pipeline: faster-whisper for transcription with word-level timestamps, PySceneDetect for scene boundary detection, and Google Gemini 3.1 Flash-Lite AI for identifying the most engaging viral moments. According to HubSpot's 2025 State of Marketing report, short-form video delivers the highest ROI of any content format, and repurposing long-form content into shorts increases total reach by up to 300%."
},
{
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: "How does Clipwright compare to Opus Clip?",
answer: "Clipwright is a free, self-hosted alternative to Opus Clip. Both offer AI viral moment detection and smart vertical cropping. Key differences: Clipwright is completely free vs Opus Clip's $15-228/month pricing. Clipwright runs on your infrastructure (full data privacy) vs cloud-only. Clipwright uses Google Gemini 3.1 Flash-Lite for AI analysis vs Opus Clip's proprietary model. Clipwright adds AI voice dubbing in 30+ languages, AI-generated video effects, and hook text overlays. The trade-off is that Clipwright requires Docker self-hosting, while Opus Clip is a ready-to-use cloud service."
},
{
question: "How do I turn a long-form video into TikTok or Reels clips?",
answer: "Upload your long-form video into OpenShorts, enter your free Gemini API key, and click Process. The AI transcribes it with faster-whisper, detects the best viral moments using Google Gemini 3.1 Flash-Lite, and crops them to 9:16 vertical format with MediaPipe face tracking. According to Wyzowl's 2025 Video Marketing Statistics report, 91% of businesses use video as a marketing tool, and repurposed short-form clips drive 2.5x more engagement than original content."
answer: "Upload your long-form video into Clipwright, enter your free Gemini API key, and click Process. The AI transcribes it with faster-whisper, detects the best viral moments using Google Gemini 3.1 Flash-Lite, and crops them to 9:16 vertical format with MediaPipe face tracking. According to Wyzowl's 2025 Video Marketing Statistics report, 91% of businesses use video as a marketing tool, and repurposed short-form clips drive 2.5x more engagement than original content."
},
{
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: "Can Clipwright generate YouTube thumbnails and titles for free?",
answer: "Yes. Clipwright 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: "What is the AI UGC Video Generator?",
answer: "OpenShorts includes an AI UGC (User Generated Content) video creator that generates marketing videos with AI actors for any product or business. You describe your product or paste a website URL — the AI writes a viral script, generates a realistic AI actor with lip-synced voiceover, adds b-roll visuals, TikTok-style subtitles, and hook text overlays. The result is a ready-to-post vertical video for TikTok, Instagram Reels, or YouTube Shorts. Two cost modes: Low Cost (~$0.65/video using Hailuo + VEED Lipsync) and Premium (~$2/video using Kling Avatar v2)."
question: "What AI does Clipwright use for viral moment detection?",
answer: "Clipwright uses Google Gemini 3.1 Flash-Lite, Google's latest multimodal AI model, for viral moment detection and title generation. The AI receives the full video transcript with timestamps, scene boundary data from PySceneDetect, and analyzes engagement patterns to identify the 3-15 most shareable moments. Each clip is scored based on emotional impact, hook strength, and viral potential — similar to how platforms like TikTok and YouTube rank content."
},
{
question: "Can I use the AI UGC Video Generator for any type of business?",
answer: "Yes. The AI Shorts generator works for any product, service, or business — not just SaaS. You can use it for restaurants, e-commerce stores, coaching services, local businesses, personal brands, apps, and more. Just describe your business in the text field (e.g. 'Artisan pizza restaurant in Madrid, wood-fired oven, home delivery') or paste your website URL, and the AI generates viral marketing scripts tailored to your business."
},
{
question: "How much does it cost to generate an AI UGC video?",
answer: "OpenShorts itself is free, but the AI Shorts feature uses external APIs (fal.ai for video generation, ElevenLabs for voiceover) that charge per use. Low Cost mode costs approximately $0.65 per video (Flux image $0.05 + ElevenLabs voice $0.10 + Hailuo img2video $0.19 + VEED Lipsync $0.20 + b-roll $0.10). Premium mode costs approximately $2.00 per video using Kling Avatar v2 for higher quality. Both modes are significantly cheaper than hiring UGC creators ($50-500 per video) or using platforms like HeyGen ($24-180/month)."
},
{
question: "What AI does OpenShorts use for viral moment detection?",
answer: "OpenShorts uses Google Gemini 3.1 Flash-Lite, Google's latest multimodal AI model, for viral moment detection and title generation. The AI receives the full video transcript with timestamps, scene boundary data from PySceneDetect, and analyzes engagement patterns to identify the 3-15 most shareable moments. Each clip is scored based on emotional impact, hook strength, and viral potential — similar to how platforms like TikTok and YouTube rank content."
},
{
question: "Can OpenShorts translate and dub videos into other languages?",
answer: "Yes. OpenShorts integrates with ElevenLabs AI dubbing to translate your video audio into over 30 languages while preserving the original speaker's voice characteristics. After dubbing, the system automatically re-transcribes the new audio and generates subtitles in the target language. This makes it easy to repurpose content for global audiences — studies show that dubbed content receives 2-3x more engagement in non-English markets."
question: "Can Clipwright translate and dub videos into other languages?",
answer: "Yes. Clipwright integrates with ElevenLabs AI dubbing to translate your video audio into over 30 languages while preserving the original speaker's voice characteristics. After dubbing, the system automatically re-transcribes the new audio and generates subtitles in the target language. This makes it easy to repurpose content for global audiences — studies show that dubbed content receives 2-3x more engagement in non-English markets."
},
{
question: "How does the smart vertical cropping work?",
answer: "OpenShorts offers two intelligent cropping modes for converting 16:9 horizontal video to 9:16 vertical format. TRACK mode uses MediaPipe face detection with YOLOv8 as fallback to follow a single subject with 'Heavy Tripod' stabilization — the camera moves smoothly like a professional cameraman. GENERAL mode handles group shots and landscapes by creating a blurred background layout. A SpeakerTracker prevents rapid switching between subjects and handles temporary occlusions for smooth results."
answer: "Clipwright offers two intelligent cropping modes for converting 16:9 horizontal video to 9:16 vertical format. TRACK mode uses MediaPipe face detection with YOLOv8 as fallback to follow a single subject with 'Heavy Tripod' stabilization — the camera moves smoothly like a professional cameraman. GENERAL mode handles group shots and landscapes by creating a blurred background layout. A SpeakerTracker prevents rapid switching between subjects and handles temporary occlusions for smooth results."
},
{
question: "Is there a free open source clip generator?",
answer: "Yes — OpenShorts is a 100% free, open source clip generator (also known as open source clipping software or an AI video clipper). 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."
answer: "Yes — Clipwright is a 100% free, open source clip generator (also known as open source clipping software or an AI video clipper). Unlike paid clip generators like Opus Clip ($15-228/month) or Kapwing ($24-79/month), Clipwright 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: "Can I automate OpenShorts from Claude, ChatGPT or n8n?",
answer: "Yes. OpenShorts has a native MCP server at mcp.openshorts.app/mcp plus a REST API with per-user keys and completion webhooks, so an AI agent can run the whole flow: submit a video URL, wait for processing, list the clips and publish them to TikTok, Instagram or YouTube. This is where the hosted service shines: an agent needs an endpoint that is always on, and the hosted one is, with the API key created in your account page in one click. The self-hosted edition serves the same /mcp endpoint, but only while your own machine is running. There is also a zero-dependency CLI (pip install openshorts) and an importable n8n workflow. Full guide at openshorts.app/mcp."
question: "Can I automate Clipwright?",
answer: "Yes. Clipwright 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?",
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)."
question: "What are the system requirements to run Clipwright?",
answer: "Clipwright 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)."
}
];
@ -234,20 +204,19 @@ export default function Landing({ onLaunchApp }) {
<nav className="fixed top-0 w-full z-50 bg-paper border-b border-rule">
<div className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
<a href="/" className="flex items-center gap-2.5 font-display text-xl lowercase text-ink tracking-tight">
<img src="/logo-openshorts.png" alt="OpenShorts logo" className="w-7 h-7" width="28" height="28" />
<span>openshorts</span>
<img src="/logo-clipwright.png" alt="Clipwright logo" className="w-7 h-7" width="28" height="28" />
<span>clipwright</span>
</a>
<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>
</div>
<div className="flex items-center gap-3">
<a
href="https://github.com/mutonby/openshorts"
href="https://git.pbento.pt/pedro-bento/clipwright"
target="_blank"
rel="noopener noreferrer"
className="hidden sm:flex items-center gap-2 text-sm lowercase text-muted hover:text-ink transition-colors"
@ -266,27 +235,24 @@ 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, or generate ugc marketing videos with ai actors. online, in the cloud, zero setup.
also a clipping tool for ai agents: claude, chatgpt and n8n drive it over{' '}
<a href="/mcp" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">mcp</a>,
or run your channel on{' '}
<a href="/auto-clip" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">autopilot</a>{' '}
or with the{' '}
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.com" 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{' '}
<a href="/n8n-youtube-shorts-automation" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">n8n workflow</a>.
just want it free? start with the{' '}
<a href="/free-ai-clip-generator" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">free ai clip generator</a>.
</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">
@ -307,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"
@ -323,9 +289,9 @@ 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"
href="https://git.pbento.pt/pedro-bento/clipwright"
target="_blank"
rel="noopener noreferrer"
className="text-ink2 underline hover:text-ink transition-colors"
@ -336,7 +302,7 @@ export default function Landing({ onLaunchApp }) {
</div>
{/* Apparatus — instrument bezel holding a real 9:16 clip */}
<figure className="apparatus" aria-label="example vertical clip generated by openshorts">
<figure className="apparatus" aria-label="example vertical clip generated by clipwright">
<div className="apparatus-shell">
<span className="apparatus-glow" aria-hidden="true" />
<div className="apparatus-chamber">
@ -413,7 +379,7 @@ export default function Landing({ onLaunchApp }) {
<span className="readout whitespace-nowrap">AI Tracking → 9:16</span>
<span className="crop-leader-line" />
</div>
<figure className="crop-frame crop-frame-9-16 w-[180px] md:w-[210px] flex-none" aria-label="vertical 9:16 clip generated by openshorts">
<figure className="crop-frame crop-frame-9-16 w-[180px] md:w-[210px] flex-none" aria-label="vertical 9:16 clip generated by clipwright">
<video
src="/demo/clip-vertical.mp4"
autoPlay
@ -427,46 +393,40 @@ 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} />
launch clipwright <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, ElevenLabs and fal.ai keys', 'You install it, you maintain it, you back it up', 'Free forever, and always will be'].map((f, i) => (
{['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) => (
<li key={i} className="flex items-center gap-2 text-sm text-muted"><Check size={14} className="text-ok shrink-0" />{f}</li>
))}
</ul>
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer"
<a href="https://git.pbento.pt/pedro-bento/clipwright" target="_blank" rel="noopener noreferrer"
className="btn-ghost whitespace-nowrap">
<Github size={16} /> view on github
</a>
@ -475,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">
@ -506,12 +454,12 @@ export default function Landing({ onLaunchApp }) {
</ul>
</div>
<div className="card p-8">
<p className="eyebrow mb-4">02 · AI Shorts</p>
<Sparkles size={20} className="text-brass mb-4" />
<h3 className="font-display text-2xl lowercase text-ink mb-2">AI Shorts</h3>
<p className="text-muted text-sm leading-relaxed mb-4">UGC marketing videos with AI actors for any business.</p>
<p className="eyebrow mb-4">02 · Publishing</p>
<Globe size={20} className="text-brass mb-4" />
<h3 className="font-display text-2xl lowercase text-ink mb-2">Postiz Publishing</h3>
<p className="text-muted text-sm leading-relaxed mb-4">Publish finished clips through a self-hosted Postiz instance.</p>
<ul className="space-y-1.5">
{['AI actor generation + lip-sync', 'B-roll + TikTok-style subtitles', 'From $0.65 per video'].map((f, i) => (
{['TikTok, Instagram Reels & YouTube Shorts', 'Self-hosted, you own the credentials', 'Schedule or post now'].map((f, i) => (
<li key={i} className="flex items-center gap-2 text-xs text-muted"><Check size={12} className="text-ok shrink-0" />{f}</li>
))}
</ul>
@ -534,8 +482,8 @@ 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 + UGC Video Creator">
The free open source clip generator & AI UGC video creator. A smart AI video clipper for TikTok, Reels & Shorts.
<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">
{features.map((feature, i) => (
@ -548,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 social publishing — you never touch an API key. 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">
@ -559,7 +507,7 @@ export default function Landing({ onLaunchApp }) {
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">Google Gemini API</h3>
<div className="mb-3"><span className="badge-ok">Free tier: 1,500 req/day</span></div>
<p className="text-muted text-sm leading-relaxed">Powers all AI features: viral moment detection, title generation, video effects, YouTube thumbnail creation, and description writing. The core engine of OpenShorts.</p>
<p className="text-muted text-sm leading-relaxed">Powers all AI features: viral moment detection, title generation, video effects, YouTube thumbnail creation, and description writing. The core engine of Clipwright.</p>
</div>
<div className="card p-6 relative">
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">Optional</span>
@ -575,29 +523,9 @@ export default function Landing({ onLaunchApp }) {
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
<Globe size={18} className="text-brass" />
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">Upload-Post API</h3>
<div className="mb-3"><span className="badge-ok">Free tier included</span></div>
<p className="text-muted text-sm leading-relaxed">Enables direct publishing to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://www.upload-post.com" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Social media API</a> that lets you post your clips and thumbnails without leaving OpenShorts.</p>
</div>
</div>
<div className="grid md:grid-cols-2 gap-5 mt-5">
<div className="card p-6 relative">
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">AI Shorts</span>
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
<Zap size={18} className="text-brass" />
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">fal.ai API</h3>
<div className="mb-3"><span className="badge-ok">Pay-per-use from $0.04</span></div>
<p className="text-muted text-sm leading-relaxed">Powers AI Shorts: generates AI actor images (Flux), talking head videos (Hailuo/Kling), and lip-sync (VEED). Required only for the AI UGC video generator.</p>
</div>
<div className="card p-6 relative">
<span className="readout absolute top-4 right-4 border border-rule rounded-full px-2.5 py-1">AI Shorts</span>
<div className="w-10 h-10 rounded-input bg-paper3 flex items-center justify-center mb-4">
<Languages size={18} className="text-brass" />
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">ElevenLabs TTS</h3>
<div className="mb-3"><span className="badge-ok">Free tier included</span></div>
<p className="text-muted text-sm leading-relaxed">Generates natural voiceovers for AI Shorts from the script. Multiple voice options for male and female actors in English and Spanish.</p>
<h3 className="font-display text-xl lowercase text-ink mb-1">Self-hosted Postiz</h3>
<div className="mb-3"><span className="badge-ok">You run it</span></div>
<p className="text-muted text-sm leading-relaxed">Publishes finished clips to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://postiz.com" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Postiz</a> runs on your own infrastructure and holds the platform credentials, so Clipwright never has them.</p>
</div>
</div>
</div>
@ -606,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">
@ -620,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">
@ -631,7 +559,6 @@ export default function Landing({ onLaunchApp }) {
{ name: "MediaPipe", desc: "Face Tracking" },
{ name: "FFmpeg", desc: "Video Processing" },
{ name: "ElevenLabs", desc: "Voice & TTS" },
{ name: "fal.ai", desc: "AI Video Gen" },
{ name: "React + Vite", desc: "Dashboard" },
{ name: "Docker", desc: "Deployment" }
].map((tech, i) => (
@ -647,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">
Clipwright 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">
@ -656,28 +583,27 @@ export default function Landing({ onLaunchApp }) {
<tr className="border-b border-rule2">
<th className="py-3 px-4 text-left text-sm text-muted font-medium">Feature</th>
<th className="py-3 px-4 text-center text-sm font-medium">
<span className="text-brass">OpenShorts</span>
<span className="text-brass">Clipwright</span>
</th>
<th className="py-3 px-4 text-center text-sm text-muted font-medium">Opus Clip</th>
<th className="py-3 px-4 text-center text-sm text-muted font-medium">Kapwing</th>
</tr>
</thead>
<tbody>
<ComparisonRow feature="Price" openshorts={<span className="text-ok font-medium">$0 Free</span>} opusclip={xIcon} kapwing={xIcon} />
<ComparisonRow feature="AI Viral Moment Detection" openshorts={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="Smart Vertical Cropping" openshorts={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="Auto Subtitles" openshorts={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="AI Voice Dubbing (30+ langs)" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI Video Effects" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={checkMuted} />
<ComparisonRow feature="Hook Text Overlays" openshorts={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="Self-Hosted / Privacy" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">Cloud only</span>} kapwing={<span className="text-muted text-sm">Cloud only</span>} />
<ComparisonRow feature="No Watermark" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">Free tier only</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="Open Source" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI YouTube Thumbnail Generator" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="AI Title & Description Generator" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="AI UGC Video Generator" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI Actors with Lip-Sync" openshorts={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="Usage Limits" openshorts={<span className="text-ok text-sm">Unlimited</span>} opusclip={<span className="text-muted text-sm">Per plan</span>} kapwing={<span className="text-muted text-sm">Per plan</span>} />
<ComparisonRow feature="Price" clipwright={<span className="text-ok font-medium">$0 Free</span>} opusclip={xIcon} kapwing={xIcon} />
<ComparisonRow feature="AI Viral Moment Detection" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="Smart Vertical Cropping" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="Auto Subtitles" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="AI Voice Dubbing (30+ langs)" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI Video Effects" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={checkMuted} />
<ComparisonRow feature="Hook Text Overlays" clipwright={checkIcon} opusclip={checkMuted} kapwing={checkMuted} />
<ComparisonRow feature="Self-Hosted / Privacy" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Cloud only</span>} kapwing={<span className="text-muted text-sm">Cloud only</span>} />
<ComparisonRow feature="No Watermark" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Free tier only</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="Open Source" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">No</span>} />
<ComparisonRow feature="AI YouTube Thumbnail Generator" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">No</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="AI Title & Description Generator" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Limited</span>} kapwing={<span className="text-muted text-sm">Paid</span>} />
<ComparisonRow feature="Postiz Social Publishing" clipwright={checkIcon} opusclip={<span className="text-muted text-sm">Built-in</span>} kapwing={<span className="text-muted text-sm">Limited</span>} />
<ComparisonRow feature="Usage Limits" clipwright={<span className="text-ok text-sm">Unlimited</span>} opusclip={<span className="text-muted text-sm">Per plan</span>} kapwing={<span className="text-muted text-sm">Per plan</span>} />
</tbody>
</table>
</div>
@ -687,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 Clipwright?">
Creators, marketers, and agencies scaling short-form video production.
</SectionHeader>
<div className="grid md:grid-cols-3 gap-5">
@ -709,7 +635,7 @@ export default function Landing({ onLaunchApp }) {
},
{
title: "Businesses & Brands",
description: "UGC-style marketing videos with AI actors — from $0.65 per video.",
description: "Turn every long video into a week of posts and schedule them through self-hosted Postiz.",
icon: Sparkles
}
].map((useCase, i) => (
@ -726,8 +652,8 @@ 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">
Everything you need to know about OpenShorts, from setup to features.
<SectionHeader eyebrow="10 · FAQ" title="Frequently Asked Questions">
Everything you need to know about Clipwright, from setup to features.
</SectionHeader>
<div className="divide-y divide-rule border-y border-rule">
{faqs.map((faq, i) => (
@ -747,21 +673,14 @@ 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
launch clipwright
<ArrowRight size={16} />
</button>
)}
<a
href="https://github.com/mutonby/openshorts"
href="https://git.pbento.pt/pedro-bento/clipwright"
target="_blank"
rel="noopener noreferrer"
className="btn-ghost whitespace-nowrap"
@ -783,13 +702,11 @@ export default function Landing({ onLaunchApp }) {
<a href="/youtube-transcript-generator" className="hover:text-ink transition-colors">youtube transcript generator</a>
<a href="/youtube-tag-generator" className="hover:text-ink transition-colors">youtube tag generator</a>
<a href="/video-aspect-ratio-converter" className="hover:text-ink transition-colors">video to 9:16 converter</a>
<a href="/auto-clip" className="hover:text-ink transition-colors">auto clip</a>
<a href="/youtube-automation" className="hover:text-ink transition-colors">youtube automation</a>
<a href="/free-ai-clip-generator-no-watermark" className="hover:text-ink transition-colors">no watermark</a>
<a href="/open-source-video-clipper" className="hover:text-ink transition-colors">open source video clipper</a>
<a href="/podcast-to-shorts" className="hover:text-ink transition-colors">podcast to shorts</a>
<a href="/youtube-to-shorts-converter" className="hover:text-ink transition-colors">youtube to shorts</a>
<a href="/how-openshorts-works" className="hover:text-ink transition-colors">how it works</a>
<a href="/how-clipwright-works" className="hover:text-ink transition-colors">how it works</a>
<a href="/alternatives" className="hover:text-ink transition-colors">alternatives</a>
<a href="/alternativas" className="hover:text-ink transition-colors">alternativas</a>
<a href="/alternatives/opus-clip" className="hover:text-ink transition-colors">vs opus clip</a>
@ -799,17 +716,16 @@ export default function Landing({ onLaunchApp }) {
<a href="/opus-pro" className="hover:text-ink transition-colors">opus pro</a>
<a href="/vizard-ai-video-to-text" className="hover:text-ink transition-colors">vizard ai video to text</a>
<a href="/submagic-reviews" className="hover:text-ink transition-colors">submagic review</a>
<a href="/mcp" className="hover:text-ink transition-colors">mcp server & api</a>
<a href="/automate-shorts-api" className="hover:text-ink transition-colors">automate shorts</a>
<a href="/n8n-youtube-shorts-automation" className="hover:text-ink transition-colors">n8n workflow</a>
</nav>
<div className="border-t border-rule pt-6 flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-center gap-3">
<img src="/logo-openshorts.png" alt="OpenShorts" className="w-6 h-6" />
<span className="text-sm text-muted">OpenShorts — Free Open Source Clip Generator & AI UGC Video Creator</span>
<img src="/logo-clipwright.png" alt="Clipwright" className="w-6 h-6" />
<span className="text-sm text-muted">Clipwright — Free Open Source Clip Generator & Postiz Publishing</span>
</div>
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm lowercase text-muted">
<a href="https://github.com/mutonby/openshorts" target="_blank" rel="noopener noreferrer" className="hover:text-ink transition-colors">GitHub</a>
<a href="https://git.pbento.pt/pedro-bento/clipwright" target="_blank" rel="noopener noreferrer" className="hover:text-ink transition-colors">GitHub</a>
<a href="#features" className="hover:text-ink transition-colors">Features</a>
<a href="#faq" className="hover:text-ink transition-colors">FAQ</a>
<a href="/terms" className="hover:text-ink transition-colors whitespace-nowrap">Terms</a>

View file

@ -7,7 +7,7 @@ import { ArrowLeft, FileText, Shield, Landmark, Flag, RotateCcw } from 'lucide-r
// links, so the SPA route (#legal) and the crawlable pages never drift: the
// full text lives in exactly one place.
const LAST_UPDATED = '2026-09-04';
const SUPPORT_EMAIL = 'info@openshorts.app';
const SUPPORT_URL = 'https://git.pbento.pt/pedro-bento/clipwright';
const DOCS = [
{
@ -27,7 +27,7 @@ const DOCS = [
{
icon: Landmark,
title: 'Legal Notice',
desc: 'Who operates openshorts.app: TONVI TECH SL, Málaga, Spain (LSSI-CE art. 10).',
desc: 'Who operates git.pbento.pt/pedro-bento/clipwright: TONVI TECH SL, Málaga, Spain (LSSI-CE art. 10).',
href: '/legal-notice',
es: '/aviso-legal',
},
@ -100,10 +100,10 @@ export default function Legal() {
</div>
<p className="text-sm text-muted">
openshorts.app is operated by TONVI TECH SL (CIF B-19780394), Calle Puerta del Mar 18,
git.pbento.pt/pedro-bento/clipwright is operated by TONVI TECH SL (CIF B-19780394), Calle Puerta del Mar 18,
29005 Málaga, Spain. Questions:{' '}
<a className="underline underline-offset-2 hover:text-brass transition-colors" href={`mailto:${SUPPORT_EMAIL}`}>
{SUPPORT_EMAIL}
<a className="underline underline-offset-2 hover:text-brass transition-colors" href={SUPPORT_URL}>
{SUPPORT_URL}
</a>
. Self-hosted instances are operated by their administrators under the MIT License; these
documents govern the hosted service only.

View file

@ -1,242 +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 McpConnectCard from './McpConnectCard';
import DeleteAccountCard from './DeleteAccountCard';
import SocialAnalyticsCard from './SocialAnalyticsCard';
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 */ }
}
}
// First time a plan activates, take the user straight to connect their
// socials. Guard with a flag so top-up checkouts don't re-trigger it.
if (paidPlan && !localStorage.getItem('os_socials_prompted')) {
localStorage.setItem('os_socials_prompted', '1');
try {
const { access_url } = await apiJson('/api/social/connect', { method: 'POST' });
if (access_url) { window.location.href = access_url; return; }
} catch (_) { /* fall through to the account page */ }
}
window.location.hash = '#/account';
}
}, 2000);
return () => clearInterval(t);
}, [refreshMe]);
useEffect(() => {
apiJson('/api/billing/plans').then((d) => setTopups(d.topups || [])).catch(() => {});
}, []);
const openPortal = useCallback(async () => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/portal', { method: 'POST' });
window.location.href = url;
} catch (e) { setBusy(false); alert('Could not open billing portal.'); }
}, []);
const buyTopup = useCallback(async (price_id) => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }),
});
window.location.href = url;
} catch (e) { setBusy(false); alert(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) rather than the portal's, so
the one moment a customer says what went wrong is not lost. */}
{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>
)}
</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 />}
<SocialAnalyticsCard />
{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>
)}
<McpConnectCard cloud />
<ApiKeysCard />
<DeleteAccountCard />
</div>
);
}

View file

@ -1,27 +0,0 @@
import React from 'react';
import { KeyRound, ArrowRight } from 'lucide-react';
// Banner for advanced tools (AI Shorts, AI Agent) that use fal.ai + ElevenLabs.
// These are BYOK: the plan covers the script/orchestration, the user brings their
// own keys for the premium generation. If they have no plan yet, also nudge trial.
export default function AdvancedBanner({ needsPlan, onKeys }) {
return (
<div className="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">
<KeyRound size={16} className="shrink-0 text-warn mt-0.5 sm:mt-0" />
<div className="text-ink2 lowercase leading-relaxed min-w-0">
<span className="font-medium text-ink">Advanced tool.</span>{' '}
{needsPlan
? <>Sign in with <span className="font-medium text-ink">Google</span> to unlock free. This tool also uses your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys (you pay those providers).</>
: <>AI video &amp; voice generation use your own <span className="font-medium text-ink normal-case">fal.ai + ElevenLabs</span> keys — add them in Settings. Script &amp; orchestration are included in your plan.</>}
</div>
</div>
<button
onClick={needsPlan ? () => { window.location.hash = '#/pricing'; } : onKeys}
className="btn-quiet shrink-0 text-xs px-3 py-1.5 w-full sm:w-auto"
>
{needsPlan ? <>See plans <ArrowRight size={14} /></> : 'Add keys'}
</button>
</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,483 +0,0 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
Rocket, Youtube, Loader2, RefreshCw, Play, CheckCircle2, AlertTriangle,
Clock, Scissors, Send, ExternalLink, FolderOpen, Lock,
} from 'lucide-react';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
// Autopilot: every new video on the user's connected YouTube channel is turned
// into shorts automatically, and optionally the best ones are scheduled on
// their socials, one a day. The channel comes from the Upload-Post connection
// the app already uses for posting (GET /api/uploadposts/media under the hood),
// so there is nothing to paste: connect once, switch it on.
const PLATFORM_LABELS = { tiktok: 'TikTok', instagram: 'Instagram', youtube: 'YouTube Shorts' };
const ERROR_TEXT = {
plan_required: 'Autopilot is paused: it needs an active Starter, Creator or Pro plan.',
youtube_not_connected: 'Connect your YouTube channel so Autopilot can see your new videos.',
youtube_reauth_required: 'YouTube asked to reconnect your channel. Reconnect it to keep Autopilot running.',
channel_unavailable: 'We could not read your channel on the last check. We will try again shortly.',
};
const REASON_TEXT = {
youtube_short: 'already a short',
private_video: 'private on YouTube — set it to Unlisted to clip it',
out_of_minutes: 'out of minutes',
too_short: 'too short to clip',
unavailable: 'not available yet (private or processing)',
low_quality: 'only low quality available',
timeout: 'did not finish',
processing_failed: 'processing failed',
publish_partial: 'some clips could not be scheduled',
url_ingest_disabled: 'links are disabled on this server',
};
const fmtDate = (iso) => (iso
? new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
: '');
// ApiError.detail is a string or {error, message}; never hand an object to JSX.
const errText = (e, fallback) => {
const d = e?.detail;
if (typeof d === 'string' && d) return d;
if (d && typeof d.message === 'string') return d.message;
return fallback;
};
const browserTimezone = () => {
try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch { return 'UTC'; }
};
function Switch({ checked, onChange, disabled, label }) {
return (
<span className="relative inline-flex items-center shrink-0">
<input
type="checkbox"
role="switch"
aria-label={label}
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="sr-only peer"
/>
<span className="w-11 h-6 rounded-full bg-paper3 border border-rule2 peer-checked:bg-brass peer-disabled:opacity-40 transition-colors after:content-[''] after:absolute after:left-1 after:top-1 after:w-4 after:h-4 after:rounded-full after:bg-ink after:transition-transform peer-checked:after:translate-x-5" />
</span>
);
}
function StatusBadge({ run }) {
if (!run) return <span className="readout">not clipped</span>;
const { status } = run;
if (status === 'completed') {
return (
<span className="badge-ok inline-flex items-center gap-1">
<CheckCircle2 size={11} /> {run.clips_count || 0} clips
{run.posted_count ? ` · ${run.posted_count} scheduled` : ''}
</span>
);
}
if (status === 'processing' || status === 'queued') {
return <span className="badge-brass inline-flex items-center gap-1"><Loader2 size={11} className="animate-spin" /> clipping</span>;
}
if (status === 'skipped') return <span className="badge-warn">{REASON_TEXT[run.reason] || 'skipped'}</span>;
return <span className="badge-danger">{REASON_TEXT[run.reason] || 'failed'}</span>;
}
export default function AutopilotTab({ onOpenProject, onUpgrade, justConnected }) {
const [data, setData] = useState(null); // GET /api/autopilot
const [videos, setVideos] = useState(null); // GET /api/autopilot/videos
const [videosError, setVideosError] = useState(null);
const [loadError, setLoadError] = useState('');
const [saving, setSaving] = useState(false);
const [running, setRunning] = useState(null); // video id being submitted
const [notice, setNotice] = useState('');
// Feedback for "clip it", shown next to the list: the page-level notice sits
// at the top of the tab, off screen from the button, so a click looked dead.
const [listNotice, setListNotice] = useState('');
const [opening, setOpening] = useState(null);
const pollRef = useRef(null);
const load = useCallback(async () => {
try {
const d = await apiJson('/api/autopilot');
setData(d);
setLoadError('');
if (d.youtube) {
const v = await apiJson('/api/autopilot/videos');
setVideos(v.videos || []);
setVideosError(v.error || null);
} else {
setVideos([]);
}
} catch (e) {
setLoadError(errText(e, 'Could not load Autopilot. Please try again.'));
}
}, []);
useEffect(() => { load(); }, [load]);
// Coming back from the connect page (#app?tab=autopilot&connected=1).
useEffect(() => {
if (justConnected) {
setNotice('Accounts connected.');
track('AutopilotChannelConnected');
}
}, [justConnected]);
// Refresh while something is being clipped, so the badge flips on its own.
const busy = (data?.runs || []).some((r) => r.status === 'processing' || r.status === 'queued');
useEffect(() => {
clearInterval(pollRef.current);
if (busy) pollRef.current = setInterval(load, 20000);
return () => clearInterval(pollRef.current);
}, [busy, load]);
const save = useCallback(async (patch) => {
setSaving(true);
setNotice('');
try {
const d = await apiJson('/api/autopilot', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ timezone: browserTimezone(), ...patch }),
});
setData((prev) => ({ ...prev, settings: d.settings }));
return d.settings;
} catch (e) {
setNotice(errText(e, 'Could not save. Please try again.'));
return null;
} finally {
setSaving(false);
}
}, []);
const connect = useCallback(async () => {
track('AutopilotConnectClick');
try {
const { access_url } = await apiJson('/api/social/connect?return_to=autopilot', { method: 'POST' });
if (access_url) window.location.href = access_url;
} catch (e) {
setNotice(errText(e, 'Could not open the connection page. Please try again.'));
}
}, []);
const toggleEnabled = useCallback(async (on) => {
const s = await save(on ? { enabled: true, rights_ack: true } : { enabled: false });
if (s) {
track(on ? 'AutopilotEnabled' : 'AutopilotDisabled', { props: { autopublish: String(!!s.autopublish) } });
setNotice(on ? 'Autopilot is on. Your next video will be clipped automatically.' : 'Autopilot paused.');
}
}, [save]);
const togglePlatform = useCallback((p) => {
const cur = data?.settings?.publish_platforms || [];
const next = cur.includes(p) ? cur.filter((x) => x !== p) : [...cur, p];
save({ publish_platforms: next });
}, [data, save]);
const runNow = useCallback(async (video) => {
setRunning(video.id);
setListNotice('');
try {
const r = await apiJson('/api/autopilot/run', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ video_id: video.id }),
});
track('AutopilotManualRun', { props: { status: r.status } });
if (r.status === 'processing') setListNotice(`Clipping “${video.title || 'your video'}”. We will email you when the clips are ready.`);
else setListNotice(`Not clipped: ${REASON_TEXT[r.reason] || r.reason || r.status}.`);
} catch (e) {
if (e?.name === 'QuotaError') setListNotice('You are out of minutes for this period.');
else setListNotice(errText(e, 'Could not start the job.'));
} finally {
setRunning(null);
load();
}
}, [load]);
const openProject = useCallback(async (jobId) => {
if (!onOpenProject || opening) return;
setOpening(jobId);
try { await onOpenProject(jobId); } catch { setNotice('Could not open this project yet. Find it in History.'); }
setOpening(null);
}, [onOpenProject, opening]);
if (!data && !loadError) {
return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-brass" /></div>;
}
const s = data?.settings || {};
const yt = data?.youtube;
const accounts = data?.accounts || {};
const eligible = !!data?.eligible;
const limits = data?.limits || { max_minutes_choices: [10, 20, 30, 45, 60, 90], max_clips_to_publish: 5, platforms: ['tiktok', 'instagram', 'youtube'] };
const runs = data?.runs || [];
const errorText = s.enabled && s.last_error ? ERROR_TEXT[s.last_error] : null;
return (
<div className="max-w-4xl mx-auto animate-fade">
<p className="eyebrow mb-1.5">02 · AUTOPILOT</p>
<h1 className="font-display lowercase text-3xl text-ink mb-2">your channel, clipped on its own</h1>
<p className="text-muted text-sm mb-8 max-w-2xl">
Publish on YouTube as usual. Autopilot notices every new video, turns it into shorts
and emails you when they are ready. Switch on autopublish and the best ones go out on
TikTok, Instagram and YouTube Shorts, one a day.
</p>
{loadError && <p className="text-danger text-sm mb-4">{loadError}</p>}
{notice && (
<div className="mb-6 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm text-ink2">{notice}</div>
)}
{/* Plan gate: Autopilot spends minutes on its own, so it is a paid feature. */}
{!eligible && (
<div className="card p-6 mb-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<Lock size={16} className="text-brass" /> included in paid plans
</h3>
<p className="text-muted text-sm mb-4">
Autopilot runs on your plan&apos;s minutes, so it comes with Starter, Creator and Pro.
Every new upload turns into shorts without you opening OpenShorts.
</p>
<button onClick={() => { track('AutopilotUpgradeClick'); onUpgrade?.(); }} className="btn-primary">
<Rocket size={16} /> choose a plan
</button>
</div>
)}
{/* 1 · channel */}
<div className="card p-6 mb-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-3 min-w-0">
<div className="w-10 h-10 rounded-full bg-paper3 border border-rule flex items-center justify-center shrink-0">
<Youtube size={18} className={yt ? 'text-brass' : 'text-muted'} />
</div>
<div className="min-w-0">
<p className="eyebrow">01 · CHANNEL</p>
{yt ? (
<p className="text-ink truncate">{yt.display_name || yt.handle} <span className="readout ml-1">{yt.handle}</span></p>
) : (
<p className="text-muted text-sm">no YouTube channel connected yet</p>
)}
</div>
</div>
{(!yt || yt.reauth_required) && (
<button onClick={connect} className="btn-primary" disabled={!eligible}>
<Youtube size={16} /> {yt ? 'reconnect youtube' : 'connect youtube'}
</button>
)}
{yt && !yt.reauth_required && (
<button onClick={connect} className="btn-quiet text-xs">manage accounts</button>
)}
</div>
{yt?.reauth_required && (
<p className="text-warn text-sm mt-3 flex items-center gap-2"><AlertTriangle size={14} /> YouTube needs you to reconnect this channel.</p>
)}
</div>
{/* 2 · switch */}
<div className="card p-6 mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="eyebrow mb-1">02 · AUTOPILOT</p>
<p className="text-ink">{s.enabled ? 'on: new videos are clipped automatically' : 'off'}</p>
<p className="text-muted text-sm mt-1">
Only videos you publish from now on. Up to {limits.daily_auto || 1} video a day, the first
{' '}{s.max_minutes || 30} minutes of each. Shorts are skipped.
</p>
{s.enabled && s.last_checked_at && (
<p className="readout mt-2 flex items-center gap-1"><Clock size={11} /> last check {fmtDate(s.last_checked_at)} · every hour</p>
)}
</div>
<Switch
label="autopilot"
checked={!!s.enabled}
disabled={saving || !eligible || !yt}
onChange={toggleEnabled}
/>
</div>
{errorText && (
<p className="text-warn text-sm mt-4 flex items-center gap-2"><AlertTriangle size={14} /> {errorText}</p>
)}
<div className="grid sm:grid-cols-2 gap-4 mt-6">
<label className="block">
<span className="eyebrow block mb-2">minutes per video</span>
<select
className="input-field"
value={s.max_minutes || 30}
disabled={saving || !eligible}
onChange={(e) => save({ max_minutes: Number(e.target.value) })}
>
{limits.max_minutes_choices.map((m) => <option key={m} value={m}>first {m} min</option>)}
</select>
</label>
</div>
</div>
{/* 3 · autopublish */}
<div className="card p-6 mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="eyebrow mb-1">03 · AUTOPUBLISH</p>
<p className="text-ink">{s.autopublish ? 'the best clips are scheduled for you' : 'off: you review and post the clips yourself'}</p>
<p className="text-muted text-sm mt-1">
Picks the {s.clips_to_publish || 3} highest-scoring clips of each video and schedules
them one a day at {String(s.publish_hour ?? 17).padStart(2, '0')}:00 ({s.timezone || browserTimezone()}).
</p>
</div>
<Switch
label="autopublish"
checked={!!s.autopublish}
disabled={saving || !eligible}
onChange={(on) => { track('AutopilotAutopublish', { props: { on: String(on) } }); save({ autopublish: on }); }}
/>
</div>
{s.autopublish && (
<>
<div className="mt-5">
<span className="eyebrow block mb-2">publish to</span>
<div className="flex flex-wrap gap-2">
{limits.platforms.map((p) => {
const connected = !!accounts[p];
const on = (s.publish_platforms || []).includes(p);
return connected ? (
<button
key={p}
onClick={() => togglePlatform(p)}
disabled={saving}
aria-pressed={on}
className={`px-4 py-2 rounded-full text-sm lowercase border transition-colors ${on ? 'border-brass bg-brass/10 text-ink' : 'border-rule2 text-muted hover:text-ink2'}`}
>
{on && <CheckCircle2 size={13} className="inline mr-1.5 -mt-0.5 text-brass" />}{PLATFORM_LABELS[p]}
</button>
) : (
<button key={p} onClick={connect} className="px-4 py-2 rounded-full text-sm lowercase border border-dashed border-rule2 text-muted hover:text-ink2">
+ connect {PLATFORM_LABELS[p]}
</button>
);
})}
</div>
{(s.publish_platforms || []).length === 0 && (
<p className="text-warn text-sm mt-3">Pick at least one account, or nothing gets published.</p>
)}
{(s.publish_platforms || []).includes('tiktok') && (
<p className="text-muted text-xs mt-3">TikTok clips arrive as drafts in your TikTok inbox: open the app to post them.</p>
)}
</div>
<div className="grid sm:grid-cols-2 gap-4 mt-5">
<label className="block">
<span className="eyebrow block mb-2">clips per video</span>
<select
className="input-field"
value={s.clips_to_publish || 3}
disabled={saving}
onChange={(e) => save({ clips_to_publish: Number(e.target.value) })}
>
{Array.from({ length: limits.max_clips_to_publish || 5 }, (_, i) => i + 1).map((n) => (
<option key={n} value={n}>{n} {n === 1 ? 'clip' : 'clips'} (one a day)</option>
))}
</select>
</label>
<label className="block">
<span className="eyebrow block mb-2">time of day</span>
<select
className="input-field"
value={s.publish_hour ?? 17}
disabled={saving}
onChange={(e) => save({ publish_hour: Number(e.target.value) })}
>
{Array.from({ length: 24 }, (_, h) => h).map((h) => (
<option key={h} value={h}>{String(h).padStart(2, '0')}:00</option>
))}
</select>
</label>
</div>
</>
)}
</div>
{/* 4 · channel videos */}
{yt && (
<div className="card p-6 mb-6">
<div className="flex items-center justify-between gap-3 mb-4">
<div>
<p className="eyebrow mb-1">04 · YOUR LATEST VIDEOS</p>
<p className="text-muted text-sm">Clip any of them now, or let Autopilot handle the next one.</p>
</div>
<button onClick={load} className="btn-quiet text-xs" aria-label="refresh"><RefreshCw size={13} /> refresh</button>
</div>
{listNotice && (
<div className="mb-4 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm text-ink2" role="status">{listNotice}</div>
)}
{videosError && <p className="text-warn text-sm mb-3">{ERROR_TEXT[videosError] || 'Could not read your channel.'}</p>}
{videos === null && <div className="flex justify-center py-6"><Loader2 className="animate-spin text-brass" size={18} /></div>}
{videos && videos.length === 0 && !videosError && (
<p className="text-muted text-sm">No videos on this channel yet.</p>
)}
<div className="divide-y divide-rule">
{(videos || []).map((v) => {
const run = v.run;
// Skipped runs can be retried too: private videos used to be
// misread as Shorts, and a real Short just skips again.
const canRun = eligible && (!run || run.status === 'failed' || run.status === 'skipped');
return (
<div key={v.id} className="flex items-center gap-3 py-3">
{v.thumbnail_url ? (
<img src={v.thumbnail_url} alt="" className="w-20 sm:w-24 h-[45px] sm:h-[54px] object-cover rounded-input border border-rule shrink-0" loading="lazy" />
) : (
<div className="w-20 sm:w-24 h-[45px] sm:h-[54px] rounded-input bg-paper3 shrink-0" />
)}
<div className="min-w-0 flex-1">
<a href={v.url} target="_blank" rel="noopener noreferrer" className="text-sm text-ink2 hover:text-ink line-clamp-2">
{v.title || v.id} <ExternalLink size={11} className="inline -mt-0.5 text-muted" />
</a>
<div className="flex flex-wrap items-center gap-2 mt-1">
<span className="readout">{fmtDate(v.published_at)}</span>
<StatusBadge run={run} />
</div>
</div>
{run?.status === 'completed' && run.job_id ? (
<button onClick={() => openProject(run.job_id)} className="btn-quiet text-xs shrink-0" disabled={opening === run.job_id}>
{opening === run.job_id ? <Loader2 size={13} className="animate-spin" /> : <FolderOpen size={13} />} open
</button>
) : canRun ? (
<button onClick={() => runNow(v)} className="btn-ghost px-4 py-2 text-xs shrink-0" disabled={!!running}>
{running === v.id ? <Loader2 size={13} className="animate-spin" /> : <Scissors size={13} />} clip it
</button>
) : null}
</div>
);
})}
</div>
</div>
)}
{/* 5 · activity */}
{runs.length > 0 && (
<div className="card p-6 mb-10">
<p className="eyebrow mb-4">05 · ACTIVITY</p>
<div className="space-y-3">
{runs.map((r) => (
<div key={r.id} className="flex items-center gap-3 text-sm">
{r.status === 'completed' ? <CheckCircle2 size={15} className="text-ok shrink-0" />
: (r.status === 'processing' || r.status === 'queued') ? <Loader2 size={15} className="animate-spin text-brass shrink-0" />
: r.status === 'skipped' ? <Play size={15} className="text-muted shrink-0" />
: <AlertTriangle size={15} className="text-danger shrink-0" />}
<span className="text-ink2 truncate flex-1">{r.video_title || r.video_id}</span>
{r.posted_count ? <span className="readout hidden sm:inline-flex items-center gap-1"><Send size={11} /> {r.posted_count} scheduled</span> : null}
<span className="readout shrink-0">{r.trigger === 'manual' ? 'manual' : 'auto'} · {fmtDate(r.created_at)}</span>
</div>
))}
</div>
</div>
)}
</div>
);
}

View file

@ -1,166 +0,0 @@
import React, { useState, useRef } 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.
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 sending = useRef(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: JSON.stringify({
reason,
details: details.trim() || undefined,
rating: rating || undefined,
review: review.trim() || undefined,
review_public_ok: publicOk,
}),
});
track('SubscriptionCanceled', { props: { plan, reason, rating: rating || undefined } });
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;
return (
<Modal isOpen onClose={busy ? undefined : keep} eyebrow={`CANCEL PLAN · ${step + 1}/3`}
title={['Why are you cancelling?', 'How was OpenShorts?', '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">
<p>
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 <i>Manage billing</i> 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="btn-primary px-4 py-2 text-xs">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
@ -16,7 +15,7 @@ const MIN_SEGMENT_SECONDS = 0.5;
const SNAP_WINDOW_SECONDS = 0.35;
// Hiding the source is a working preference, not a per-clip one, so it sticks.
const HIDE_SOURCE_KEY = 'openshorts_editor_hide_source';
const HIDE_SOURCE_KEY = 'clipwright_editor_hide_source';
// Words per memoised transcript slice. See TranscriptChunk for why this exists.
const CHUNK_WORDS = 50;
@ -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');
}
} finally {
setRendering(false);
}

View file

@ -16,7 +16,7 @@ const TOUR = [
{
target: '[data-tutorial="drop-zone"]',
title: 'Your video',
body: 'Click the box or paste the link here. Keep files under 500MB.',
body: 'Click the box or paste the link here. File size is limited only by your server and proxy.',
},
{
target: '[data-tutorial="output-format"]',

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,148 +0,0 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Loader2 } from 'lucide-react';
import { getApiUrl } from '../config';
import GalleryCard from './GalleryCard';
const CLIPS_PER_PAGE = 20;
export default function Gallery() {
const [clips, setClips] = useState([]);
const [loading, setLoading] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [error, setError] = useState(null);
const [hasMore, setHasMore] = useState(true);
const [offset, setOffset] = useState(0);
const loaderRef = useRef(null);
const fetchClips = useCallback(async (currentOffset = 0, append = false) => {
try {
if (currentOffset === 0) setLoading(true);
else setLoadingMore(true);
const res = await fetch(
getApiUrl(`/api/gallery/clips?limit=${CLIPS_PER_PAGE}&offset=${currentOffset}`)
);
if (!res.ok) throw new Error('Failed to fetch clips');
const data = await res.json();
const newClips = data.clips || [];
if (append) {
setClips(prev => [...prev, ...newClips]);
} else {
setClips(newClips);
}
setHasMore(data.has_more ?? newClips.length === CLIPS_PER_PAGE);
setOffset(currentOffset + newClips.length);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
setLoadingMore(false);
}
}, []);
// Initial load
useEffect(() => {
fetchClips(0, false);
}, [fetchClips]);
// Infinite scroll observer
useEffect(() => {
if (!hasMore || loadingMore || loading) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting && hasMore && !loadingMore) {
fetchClips(offset, true);
}
},
{ rootMargin: '200px', threshold: 0.1 }
);
const node = loaderRef.current;
if (node) {
observer.observe(node);
}
return () => {
if (node) {
observer.unobserve(node);
}
};
}, [hasMore, loadingMore, loading, offset, fetchClips]);
if (loading) {
return (
<div className="h-full flex flex-col items-center justify-center text-muted animate-fade">
<Loader2 size={32} className="animate-spin mb-4 text-brass" />
<p className="lowercase">Loading your viral history...</p>
</div>
);
}
if (error) {
return (
<div className="h-full flex flex-col items-center justify-center text-danger p-6">
<AlertCircle size={32} className="mb-4" />
<p>Error loading gallery: {error}</p>
<button
onClick={() => {
setError(null);
setOffset(0);
fetchClips(0, false);
}}
className="btn-quiet mt-4"
>
Retry
</button>
</div>
);
}
return (
<div className="h-full overflow-y-auto p-6 md:p-8 animate-fade">
<div className="flex items-end justify-between mb-8">
<div>
<p className="eyebrow mb-1.5">Library</p>
<h1 className="font-display lowercase text-2xl text-ink">Clip Gallery</h1>
</div>
<span className="readout">
{clips.length} {clips.length === 1 ? 'Clip' : 'Clips'}{hasMore ? '+' : ''}
</span>
</div>
{clips.length === 0 ? (
<div className="text-center py-20 text-muted">
<p className="text-lg mb-2 lowercase">No clips found yet.</p>
<p className="text-sm lowercase">Process some videos to populate your gallery!</p>
</div>
) : (
<>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-6 pb-10">
{clips.map((clip) => (
<GalleryCard key={`${clip.job_id}-${clip.index}`} clip={clip} />
))}
</div>
{/* Infinite scroll loader trigger */}
{hasMore && (
<div
ref={loaderRef}
className="flex justify-center py-8"
>
{loadingMore && (
<div className="flex items-center gap-2 text-muted">
<Loader2 size={20} className="animate-spin" />
<span className="text-sm lowercase">Loading more clips...</span>
</div>
)}
</div>
)}
</>
)}
</div>
);
}

View file

@ -1,151 +0,0 @@
import React, { useRef, useState, useEffect } from 'react';
import { Download, Copy, Check, Play } from 'lucide-react';
export default function GalleryCard({ clip }) {
const [copied, setCopied] = useState(null);
const [isVisible, setIsVisible] = useState(false);
const [_hasLoaded, setHasLoaded] = useState(false);
const cardRef = useRef(null);
const videoRef = useRef(null);
// Lazy loading with IntersectionObserver
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
// Once loaded, we don't need to observe anymore
observer.unobserve(entry.target);
}
});
},
{
rootMargin: '200px', // Start loading 200px before entering viewport
threshold: 0.1
}
);
const node = cardRef.current;
if (node) {
observer.observe(node);
}
return () => {
if (node) {
observer.unobserve(node);
}
};
}, []);
const handleCopy = (text, field) => {
navigator.clipboard.writeText(text);
setCopied(field);
setTimeout(() => setCopied(null), 2000);
};
const handleDownload = async (e) => {
e.preventDefault();
try {
const response = await fetch(clip.url);
if (!response.ok) throw new Error('Download failed');
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `clip_${clip.job_id}_${clip.index + 1}.mp4`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err) {
console.error('Download error:', err);
window.open(clip.url, '_blank');
}
};
return (
<div
ref={cardRef}
className="card card-hover overflow-hidden flex flex-col group animate-fade"
>
{/* Video Player - Lazy loaded */}
<div className="aspect-[9/16] bg-black relative group/video">
{isVisible ? (
<video
ref={videoRef}
src={clip.url}
controls
className="w-full h-full object-cover"
playsInline
preload="metadata"
onLoadedData={() => setHasLoaded(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center bg-paper">
<div className="w-12 h-12 rounded-full bg-paper3 flex items-center justify-center">
<Play size={24} className="text-muted ml-1" />
</div>
</div>
)}
<div className="absolute top-2 left-2">
<span className="readout bg-black/70 px-2 py-1 rounded-full">
{new Date(clip.created_at).toLocaleDateString()}
</span>
</div>
</div>
{/* Content & Details */}
<div className="flex-1 p-4 flex flex-col min-w-0">
<div className="mb-3">
<h3 className="text-sm font-semibold text-ink leading-tight line-clamp-2 mb-2 break-words" title={clip.title}>
{clip.title}
</h3>
<div className="flex flex-wrap gap-2">
<span className="readout bg-paper3 px-1.5 py-0.5 rounded-full">{clip.duration.toFixed(1)}s</span>
<span className="readout bg-paper3 px-1.5 py-0.5 rounded-full truncate max-w-[150px]" title={clip.job_id}>ID: {clip.job_id.substring(0, 8)}</span>
</div>
</div>
<div className="space-y-2 flex-1 overflow-y-auto custom-scrollbar max-h-[150px] pr-1 mb-3">
{/* YouTube Title */}
<div className="bg-paper rounded-input p-2 relative group/item">
<p className="eyebrow mb-1">YouTube Title</p>
<p className="text-xs text-ink2 select-all line-clamp-2 hover:line-clamp-none transition-all">{clip.title}</p>
<button
onClick={() => handleCopy(clip.title, 'yt')}
className="absolute top-2 right-2 p-1 text-muted hover:text-brass transition-colors opacity-0 group-hover/item:opacity-100"
title="Copy Title"
>
{copied === 'yt' ? <Check size={12} className="text-ok" /> : <Copy size={12} />}
</button>
</div>
{/* TikTok / IG Caption */}
<div className="bg-paper rounded-input p-2 relative group/item">
<p className="eyebrow mb-1">TikTok · IG Caption</p>
<p className="text-xs text-ink2 select-all line-clamp-3 hover:line-clamp-none transition-all cursor-pointer">
{clip.tiktok_desc || clip.insta_desc}
</p>
<button
onClick={() => handleCopy(clip.tiktok_desc || clip.insta_desc, 'caption')}
className="absolute top-2 right-2 p-1 text-muted hover:text-brass transition-colors opacity-0 group-hover/item:opacity-100"
title="Copy Caption"
>
{copied === 'caption' ? <Check size={12} className="text-ok" /> : <Copy size={12} />}
</button>
</div>
</div>
{/* Footer Action */}
<button
onClick={handleDownload}
className="btn-quiet w-full"
>
<Download size={14} className="shrink-0" /> Download Clip
</button>
</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">07 · 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

@ -51,7 +51,7 @@ const SIZE_OPTIONS = [
// Last-used hook settings, restored on the next open (style always reset to
// classic otherwise, which users read as the picker being broken).
function loadHookPrefs() {
try { return JSON.parse(localStorage.getItem('os_hook_prefs')) || {}; } catch { return {}; }
try { return JSON.parse(localStorage.getItem('cw_hook_prefs')) || {}; } catch { return {}; }
}
export default function HookModal({ isOpen, onClose, onGenerate, onRemove, isProcessing, videoUrl, initialText, durationInSeconds, existingSubtitles, hasCaptions, serverRender, burnedHook }) {
@ -297,7 +297,7 @@ export default function HookModal({ isOpen, onClose, onGenerate, onRemove, isPro
<button
onClick={() => {
try {
localStorage.setItem('os_hook_prefs', JSON.stringify({
localStorage.setItem('cw_hook_prefs', JSON.stringify({
style, font, position, size, entranceAnimation,
}));
} catch { /* ignore */ }

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,140 +0,0 @@
import React, { useState, useCallback } from 'react';
import { Plug, Copy, Check } from 'lucide-react';
import { getApiUrl } from '../config';
// "Connect an agent": the one place that tells a person how to drive
// OpenShorts from Claude, ChatGPT, Cursor or n8n. Cloud accounts connect by
// URL (claude.ai and ChatGPT run the OAuth flow themselves; CLI clients take
// an API key); a self-hosted install has no auth, so every snippet is the
// local URL and nothing else.
const CLOUD_MCP_URL = 'https://mcp.openshorts.app/mcp';
// The self-hosted dashboard proxies /api and /videos to the backend but not
// /mcp (neither the Vite dev proxy nor nginx.conf), so an MCP client must
// talk to the API container itself: VITE_API_URL when it is set, otherwise
// the backend's default port on the same host.
function localMcpUrl() {
const u = getApiUrl('/mcp');
if (u.startsWith('http')) return u;
try { return `${window.location.protocol}//${window.location.hostname}:8000/mcp`; } catch { return 'http://localhost:8000/mcp'; }
}
function buildClients({ cloud, url }) {
const key = cloud ? 'osk_YOUR_KEY' : null;
const header = key ? ` \\\n --header "Authorization: Bearer ${key}"` : '';
const desktopArgs = key
? `["-y", "mcp-remote", "${url}", "--header", "Authorization: Bearer ${key}"]`
: `["-y", "mcp-remote", "${url}"]`;
const cursorHeaders = key ? `,\n "headers": { "Authorization": "Bearer ${key}" }` : '';
return [
cloud && {
id: 'claude-ai', label: 'Claude (claude.ai)', kind: 'steps',
steps: [
'Open claude.ai → Settings → Connectors → Add custom connector.',
`Paste this URL and save: ${url}`,
'Click Connect: you will land on OpenShorts to approve the access, then the 8 tools appear in every chat.',
],
snippet: url,
},
cloud && {
id: 'chatgpt', label: 'ChatGPT', kind: 'steps',
steps: [
'Open ChatGPT → Settings → Connectors → Create (developer mode).',
`Name it OpenShorts, paste this MCP server URL, choose OAuth: ${url}`,
'Approve the access on OpenShorts when asked. Done: ask ChatGPT to clip a video.',
],
snippet: url,
},
{
id: 'claude-code', label: 'Claude Code', kind: 'code', lang: 'bash',
snippet: `claude mcp add --transport http openshorts ${url}${header}`,
note: cloud ? 'Create a key below and paste it in place of osk_YOUR_KEY.' : 'No key needed on a self-hosted install.',
},
{
id: 'claude-desktop', label: 'Claude Desktop', kind: 'code', lang: 'json',
snippet: `{\n "mcpServers": {\n "openshorts": {\n "command": "npx",\n "args": ${desktopArgs}\n }\n }\n}`,
note: 'Settings → Developer → Edit config (claude_desktop_config.json), then restart Claude.',
},
{
id: 'cursor', label: 'Cursor', kind: 'code', lang: 'json',
snippet: `{\n "mcpServers": {\n "openshorts": {\n "url": "${url}"${cursorHeaders}\n }\n }\n}`,
note: 'Settings → MCP → Add new global MCP server (.cursor/mcp.json).',
},
{
id: 'n8n', label: 'n8n', kind: 'steps',
steps: [
'Add an "MCP Client Tool" node to your AI Agent.',
`Endpoint: ${url} · Transport: HTTP Streamable.`,
cloud ? 'Authentication: Bearer, with a key from below.' : 'Authentication: none.',
],
snippet: url,
},
{
id: 'curl', label: 'curl', kind: 'code', lang: 'bash',
snippet: `curl -X POST ${url} \\\n -H "Content-Type: application/json"${key ? ` \\\n -H "Authorization: Bearer ${key}"` : ''} \\\n -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`,
note: 'Plain JSON-RPC over HTTP: the same endpoint every client above talks to.',
},
].filter(Boolean);
}
export default function McpConnectCard({ cloud = true, compact = false }) {
const url = cloud ? CLOUD_MCP_URL : localMcpUrl();
const clients = buildClients({ cloud, url });
const [active, setActive] = useState(clients[0].id);
const [copied, setCopied] = useState(false);
const current = clients.find((c) => c.id === active) || clients[0];
const copy = useCallback(() => {
navigator.clipboard?.writeText(current.snippet).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1600);
}).catch(() => {});
}, [current]);
return (
<div className="card p-6" id="connect-agent">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<Plug size={16} className="text-brass" /> Connect an agent
</h3>
<p className="text-muted text-sm mb-4">
Let Claude, ChatGPT, Cursor or n8n clip and publish for you through the built-in MCP server:
8 tools (process a video or upload one, check a job, list clips, add subtitles, recut, publish, quota).
{cloud
? ' claude.ai and ChatGPT connect with one URL and a sign-in; CLI clients use an API key.'
: ' This install runs without accounts, so no key is needed.'}
</p>
<div className="flex flex-wrap gap-1.5 mb-4" role="tablist" aria-label="client">
{clients.map((c) => (
<button
key={c.id}
role="tab"
aria-selected={c.id === active}
onClick={() => { setActive(c.id); setCopied(false); }}
className={`px-3 py-1.5 rounded-input text-xs border transition-colors ${
c.id === active ? 'border-brass text-ink bg-brass/10' : 'border-rule text-muted hover:text-ink'}`}
>
{c.label}
</button>
))}
</div>
{current.kind === 'steps' && (
<ol className="list-decimal pl-5 space-y-1.5 text-sm text-ink2 mb-3">
{current.steps.map((s) => <li key={s}>{s}</li>)}
</ol>
)}
<div className="relative">
<pre className={`font-mono text-ink2 whitespace-pre-wrap break-all rounded-card border border-rule bg-paper p-3 pr-20 text-xs ${compact ? '' : 'leading-relaxed'}`}>
{current.snippet}
</pre>
<button onClick={copy} className="btn-ghost absolute top-2 right-2 px-2.5 py-1 text-xs" aria-label="copy">
{copied ? <Check size={13} /> : <Copy size={13} />} {copied ? 'Copied' : 'Copy'}
</button>
</div>
{current.note && <p className="text-muted text-xs mt-2">{current.note}</p>}
</div>
);
}

View file

@ -49,17 +49,17 @@ export default function MediaInput({ onProcess, isProcessing }) {
// Auto-hook: burn the AI hook text into every clip. On by default; the
// choice persists so turning it off sticks across sessions.
const [autoHook, setAutoHook] = useState(() => {
try { return localStorage.getItem('os_auto_hook') !== '0'; } catch { return true; }
try { return localStorage.getItem('cw_auto_hook') !== '0'; } catch { return true; }
});
const [autoHookStyle, setAutoHookStyle] = useState(() => {
// v2 key: the default became 'pill'; an old saved 'classic' was just the old default.
try { return localStorage.getItem('os_auto_hook_style_v2') || 'pill'; } catch { return 'pill'; }
try { return localStorage.getItem('cw_auto_hook_style_v2') || 'pill'; } catch { return 'pill'; }
});
// Layout: 'auto' lets the AI pick per video (server default); the others
// force one on so a podcast host who knows what they uploaded doesn't
// depend on the detector, and 'none' keeps the plain single crop.
const [layout, setLayout] = useState(() => {
try { return localStorage.getItem('os_layout') || 'auto'; } catch { return 'auto'; }
try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; }
});
const infoRef = useRef(null);
@ -105,8 +105,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
useEffect(() => {
let pending = null;
try {
pending = localStorage.getItem('os_pending_url');
if (pending) localStorage.removeItem('os_pending_url');
pending = localStorage.getItem('cw_pending_url');
if (pending) localStorage.removeItem('cw_pending_url');
} catch { /* ignore */ }
if (pending) {
setMode('url');
@ -126,9 +126,9 @@ export default function MediaInput({ onProcess, isProcessing }) {
layout,
};
try {
localStorage.setItem('os_auto_hook', autoHook ? '1' : '0');
localStorage.setItem('os_auto_hook_style_v2', autoHookStyle);
localStorage.setItem('os_layout', layout);
localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0');
localStorage.setItem('cw_auto_hook_style_v2', autoHookStyle);
localStorage.setItem('cw_layout', layout);
} catch { /* ignore */ }
if (mode === 'url' && url) {
onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced });
@ -248,7 +248,8 @@ export default function MediaInput({ onProcess, isProcessing }) {
/>
<Upload className="mx-auto mb-3 text-muted" size={18} />
<p className="text-ink2 lowercase">Click to upload or drag and drop</p>
<p className="readout mt-2">MP4, MOV up to 500MB · at least {MIN_SOURCE_SECONDS}s long</p>
<p className="readout mt-2">MP4, MOV · at least {MIN_SOURCE_SECONDS}s long</p>
<p className="text-muted text-xs mt-1 lowercase">file size is limited only by your server and proxy</p>
</label>
)}
</div>

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', 'AI avatar / UGC videos'],
['autopilot_posting', 'Auto-posting 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,323 +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 and fal.ai for dubbing and AI Shorts.',
},
{
icon: Send,
label: 'Auto-posting',
hosted: 'TikTok, Instagram Reels and YouTube Shorts connect straight from your account.',
self: 'You register your own Upload-Post account and wire up the credentials.',
},
{
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 and fal.ai for AI Shorts if you want those. (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, auto-posting to TikTok, Instagram and YouTube is already wired up, 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: "How much does it cost to generate an AI UGC video?",
answer: "OpenShorts itself is free, but the AI Shorts feature uses external APIs (fal.ai for video generation, ElevenLabs for voiceover) that charge per use. Low Cost mode costs approximately $0.65 per video (Flux image $0.05 + ElevenLabs voice $0.10 + Hailuo img2video $0.19 + VEED Lipsync $0.20 + b-roll $0.10). Premium mode costs approximately $2.00 per video using Kling Avatar v2 for higher quality. Both modes are significantly cheaper than hiring UGC creators ($50-500 per video) or using platforms like HeyGen ($24-180/month)."
},
{
question: "Does API and MCP access cost extra?",
answer: "No. Every plan, including the free one, can create API keys in the account page and use the REST API and the MCP server at mcp.openshorts.app/mcp. Calls draw from the same monthly minutes as the dashboard, so automating with Claude, ChatGPT or n8n does not change the price of anything. The value of the hosted endpoint is that it is always on: an agent or a scheduled pipeline can clip and publish while your own machine is off, which is the one thing the self-hosted edition cannot do for you. Full guide at openshorts.app/mcp."
},
{
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, Bot } 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 + auto-posting included</span></li>
<li className="flex items-start gap-2"><Bot size={16} className="text-ok shrink-0 mt-0.5" /> <span><b>MCP + API access</b> for AI agents &amp; 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>Auto-posting is already wired up</b> for TikTok, Instagram Reels and YouTube Shorts.</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"><Bot size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>MCP server &amp; API for agents.</b> Connect Claude, ChatGPT or n8n to an always-on endpoint and automate clipping end to end. API calls use the same minutes, nothing extra to buy. <a href="/mcp" 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">AI Shorts</b> (AI-actor UGC videos) and <b className="text-ink2">voice dubbing</b> use premium generation from
<b className="text-ink2"> fal.ai</b> and <b className="text-ink2">ElevenLabs</b>. Connect your own keys for those — you're billed by those
providers directly (typically ~$0.65-2 per video). Your plan still covers the script &amp; orchestration.
</p>
<p className="text-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,9 +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 TikTokDraftNotice from './TikTokDraftNotice';
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';
@ -36,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, uploadPostKey, uploadUserId, geminiApiKey, elevenLabsKey, isManaged, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, elevenLabsKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, 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
@ -54,8 +51,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
}, [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
@ -68,28 +63,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
};
const originalVideoUrl = getApiUrl((clip.video_url || '').replace(/[^/]+$/, stripBurns((clip.video_url || '').split('/').pop())));
const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url));
// Where the <video> element pulls its bytes from. The clips are archived to
// R2 anyway, and R2 egress is free and edge-served, while /videos is served
// by the same single-worker API process that is running the renders. So play
// from R2 when possible.
//
// ONLY when R2 holds exactly the file the server considers current for this
// clip (durable.filename === serverVideoFile). Every server-side edit sends
// input_filename: serverVideoFile and rewrites clip.video_url, but the R2
// re-archive behind it is fire-and-forget, so for a few seconds the durable
// copy is the PRE-edit clip. Preferring it blindly would silently show the
// clip without the subtitles/hook the user just burned.
//
// This is display-only: currentVideoUrl remains the source of truth for the
// download button and for every server operation, so no edit can be routed
// to the wrong file by this.
const [durableSrc, setDurableSrc] = useState(null);
const [durableFailed, setDurableFailed] = useState(false);
// Switching src reloads the element and restarts playback, so the durable copy
// is only ever adopted before the user has touched this player. After an edit
// the chase in App.jsx can land while they are watching the result, and losing
// their position to save a few seconds of buffering is a bad trade.
const [hasPlayed, setHasPlayed] = useState(false);
// A delivered clip is tens of MB, and on a slow link the old silent
// fetch-then-save took minutes with nothing on screen, which reads as a dead
@ -139,34 +112,9 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
// Latest file that exists ON THE SERVER (blob: previews don't count).
// All server-side operations must chain from this, so burned-in edits
// (subtitles, hooks, effects) never get silently dropped.
// A reopened project seeds it from the persisted project state.
const [serverVideoFile, setServerVideoFile] = useState(initialState?.server_file || (clip.video_url || '').split('/').pop());
const [videoErrored, setVideoErrored] = useState(false);
const [serverVideoFile, setServerVideoFile] = useState((clip.video_url || '').split('/').pop());
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.
useEffect(() => {
if (durable?.url && durable.filename && durable.filename === serverVideoFile && !hasPlayed) {
setDurableSrc((prev) => prev || durable.url);
} else {
setDurableSrc(null);
}
}, [durable?.url, durable?.filename, serverVideoFile, hasPlayed]);
// If the local video failed and a durable R2 URL is (now) available, use it.
// Handles the race where the video errors before the durable URL has loaded.
// Deliberately NOT version-gated: reaching here means the local file is gone
// (retention sweep after a reload), so an older durable copy still beats a
// broken player.
useEffect(() => {
if (videoErrored && durable?.url && currentVideoUrl !== durable.url) {
setCurrentVideoUrl(durable.url);
setVideoErrored(false);
}
}, [videoErrored, durable, currentVideoUrl]);
// When an external refresh changes this clip's server file (e.g. bulk
// subtitles applied from another card), adopt it so the card shows the
// freshly subtitled video instead of a stale one.
@ -176,8 +124,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
if (serverName && serverName !== serverVideoFile) {
setServerVideoFile(serverName);
setCurrentVideoUrl(serverUrl);
setDurableFailed(false);
setHasPlayed(false);
if (videoRef.current) videoRef.current.load();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -220,19 +166,9 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
return Number.isFinite(secs) ? secs : 30;
});
// Accumulate Remotion layers across operations. A reopened project restores
// the layers persisted in its project state, so the next edit composes over
// them instead of silently dropping previous browser-side work.
const [activeLayers, setActiveLayers] = useState(initialState?.active_layers || { subtitles: null, hook: null, effects: null });
// Report edit state upward (debounced sync to the project record). Skip the
// mount run: only user-driven changes are worth persisting.
const stateReported = React.useRef(false);
useEffect(() => {
if (!stateReported.current) { stateReported.current = true; return; }
onStateChange?.(index, { activeLayers, serverVideoFile });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeLayers, serverVideoFile]);
// Accumulate Remotion layers across operations so an edit composes over the
// previous browser-side work instead of silently dropping it.
const [activeLayers, setActiveLayers] = useState({ subtitles: null, hook: null, effects: null });
// True when the current server file already carries burned-in content.
// Browser (Remotion) renders compose over the ORIGINAL clip, so using them
@ -257,16 +193,21 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
// Which platforms the selected profile actually has linked. `null` means
// unknown (profile list not loaded) — in that case nothing is gated.
// Identifiers are normalized to lowercase: Postiz can report them as
// "YouTube", while ChannelIcon and the backend compare lowercase.
const knownConnections = Array.isArray(connectedPlatforms);
const noAccountsConnected = knownConnections && connectedPlatforms.length === 0;
const normalizedConnections = knownConnections
? connectedPlatforms.map((p) => String(p).toLowerCase())
: [];
const noAccountsConnected = knownConnections && normalizedConnections.length === 0;
const platformOptions = knownConnections
? PLATFORM_OPTIONS.map((o) => (connectedPlatforms.includes(o.value) ? o : { ...o, disabled: true, hint: 'not connected' }))
? PLATFORM_OPTIONS.map((o) => (normalizedConnections.includes(o.value) ? o : { ...o, disabled: true, hint: 'not connected' }))
: PLATFORM_OPTIONS;
const handleConnectAccounts = () => {
setShowModal(false);
if (onConnectSocials) onConnectSocials();
else window.open('https://app.upload-post.com', '_blank', 'noopener');
else if (postizUrl) window.open(postizUrl, '_blank', 'noopener');
};
// Initialize/Reset form when modal opens
@ -280,9 +221,9 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
// Only preselect platforms the profile can actually publish to.
if (knownConnections) {
setPlatforms({
tiktok: connectedPlatforms.includes('tiktok'),
instagram: connectedPlatforms.includes('instagram'),
youtube: connectedPlatforms.includes('youtube'),
tiktok: normalizedConnections.includes('tiktok'),
instagram: normalizedConnections.includes('instagram'),
youtube: normalizedConnections.includes('youtube'),
});
}
}
@ -299,7 +240,7 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
// 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 } : {};
@ -464,6 +405,10 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
effect: options.effect || 'none',
base_opacity: options.baseOpacity ?? 1.0,
uppercase: options.uppercase || false,
reveal: options.reveal || false,
shadow: options.shadow || 0,
max_chars: options.maxChars ?? null,
max_duration: options.maxDuration ?? null,
input_filename: serverVideoFile,
// Edited caption text (clip-relative ms); null = server
// regenerates from the transcript as before.
@ -659,12 +604,12 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
}
};
// Managed (cloud plan/trial) users post with the server-side key — no BYOK needed
const canPost = isManaged || (uploadPostKey && uploadUserId);
// Publishing needs both the Postiz base URL and API key; clipping does not.
const canPost = !!postizKey && !!postizUrl;
const handlePost = async () => {
if (!canPost) {
setPostResult({ success: false, msg: "Missing API Key or User ID." });
setPostResult({ success: false, msg: "Postiz is not configured. Add your base URL and API key in Settings." });
return;
}
@ -691,8 +636,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
const payload = {
job_id: jobId,
clip_index: index,
api_key: uploadPostKey,
user_id: uploadUserId,
platforms: selectedPlatforms,
title: postTitle,
description: postDescription
@ -701,13 +644,16 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
if (isScheduling && scheduleDate) {
// Convert to ISO-8601
payload.scheduled_date = new Date(scheduleDate).toISOString();
// Optional: pass timezone if needed, backend defaults to UTC or we can send user's timezone
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
}
const res = await apiFetch('/api/social/post', {
const headers = { 'Content-Type': 'application/json' };
if (postizKey) headers['X-Postiz-Key'] = postizKey;
if (postizUrl) headers['X-Postiz-Url'] = postizUrl.replace(/\/$/, '');
const res = await apiFetch('/api/postiz/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers,
body: JSON.stringify(payload)
});
@ -734,12 +680,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
}
};
// Browser-rendered previews (Remotion) live in a blob: URL that exists only
// in this tab, so they always win over the durable copy.
const playbackUrl = (durableSrc && !durableFailed && !String(currentVideoUrl || '').startsWith('blob:'))
? durableSrc
: currentVideoUrl;
const durationReadout = formatDuration(clip);
return (
@ -752,29 +692,14 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
<div className="w-full max-w-[calc(64vh*0.5625)] md:max-w-none mx-auto md:mx-0 md:w-[236px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto group/video">
<video
ref={videoRef}
src={playbackUrl}
src={currentVideoUrl}
controls
className="w-full h-full object-contain"
playsInline
onLoadedMetadata={(e) => {
if (e.target.videoWidth) setResolution(`${e.target.videoWidth}×${e.target.videoHeight}`);
}}
onError={() => {
// The durable copy is unreachable (signature expired after an
// hour on an idle tab, object purged) → serve from the API for
// the rest of this card's life.
if (playbackUrl === durableSrc) {
setDurableFailed(true);
return;
}
// Local /videos/ file gone (e.g. cleaned up after a reload) →
// fall back to the durable R2 copy for managed users. If the
// durable URL hasn't loaded yet, the effect above retries.
if (durable?.url && currentVideoUrl !== durable.url) setCurrentVideoUrl(durable.url);
else setVideoErrored(true);
}}
onPlay={() => {
setHasPlayed(true);
const currentTime = videoRef.current ? videoRef.current.currentTime : 0;
onPlay && onPlay(clip.start + currentTime);
}}
@ -799,7 +724,7 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
{Number.isFinite(clip.predicted_score) && (
<span
className="bg-black/70 font-mono text-micro uppercase px-2 py-1 rounded-full flex items-center gap-1"
title="openshorts' prediction of how well this clip will perform, from 0 to 100"
title="clipwright' prediction of how well this clip will perform, from 0 to 100"
>
<TrendingUp size={11} className="shrink-0 text-muted" />
<span className="text-muted">viral</span>
@ -843,7 +768,7 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
ref={whyRef}
className={`text-xs text-muted leading-snug line-clamp-2 break-words ${whyClamped ? 'cursor-pointer' : ''}`}
onClick={() => whyClamped && setWhyOpen(v => !v)}
aria-label="why openshorts picked this moment"
aria-label="why clipwright picked this moment"
>
{clip.why}
</p>
@ -976,16 +901,7 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
<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()) {
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" />
@ -1063,22 +979,17 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
{!canPost && (
<div className="mb-4 px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<div className="lowercase">configure api key in settings first.</div>
<div className="lowercase">configure Postiz in settings first.</div>
</div>
)}
{noAccountsConnected && (
<div className="mb-4 px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<div className="lowercase">no social accounts connected yet — link tiktok, instagram or youtube to publish this clip.</div>
<div className="lowercase">no social accounts connected yet — link tiktok, instagram or youtube in Postiz to publish this clip.</div>
</div>
)}
{/* Both the title/description fields below and the schedule
button are downstream of this: on a tiktok draft neither
travels. See TikTokDraftNotice. */}
{platforms.tiktok && <TikTokDraftNotice />}
<div className="space-y-4">
{/* Title & Description */}
<div>
@ -1197,13 +1108,6 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey,
hasApiKey={!!elevenLabsKey}
/>
{showWatermarkModal && (
<WatermarkModal
onClose={() => setShowWatermarkModal(false)}
onContinue={downloadClip}
/>
)}
</div>
);
}

File diff suppressed because it is too large Load diff

View file

@ -1,371 +0,0 @@
import React, { useState, useMemo } from 'react';
import { Loader2, Calendar, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Circle, ExternalLink } from 'lucide-react';
import { apiFetch } from '../lib/api';
import Modal from './ui/Modal';
import SegmentedControl from './ui/SegmentedControl';
import TikTokDraftNotice from './TikTokDraftNotice';
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const TIMEZONES = [
{ value: 'Pacific/Midway', label: '(GMT-11:00) Midway' },
{ value: 'Pacific/Honolulu', label: '(GMT-10:00) Honolulu' },
{ value: 'America/Anchorage', label: '(GMT-09:00) Alaska' },
{ value: 'America/Los_Angeles', label: '(GMT-08:00) Los Angeles' },
{ value: 'America/Denver', label: '(GMT-07:00) Denver' },
{ value: 'America/Mexico_City', label: '(GMT-06:00) Mexico City' },
{ value: 'America/Chicago', label: '(GMT-06:00) Chicago' },
{ value: 'America/New_York', label: '(GMT-05:00) New York' },
{ value: 'America/Bogota', label: '(GMT-05:00) Bogota' },
{ value: 'America/Caracas', label: '(GMT-04:00) Caracas' },
{ value: 'America/Santiago', label: '(GMT-04:00) Santiago' },
{ value: 'America/Argentina/Buenos_Aires', label: '(GMT-03:00) Buenos Aires' },
{ value: 'America/Sao_Paulo', label: '(GMT-03:00) Sao Paulo' },
{ value: 'Atlantic/Azores', label: '(GMT-01:00) Azores' },
{ value: 'UTC', label: '(GMT+00:00) UTC' },
{ value: 'Europe/London', label: '(GMT+00:00) London' },
{ value: 'Europe/Madrid', label: '(GMT+01:00) Madrid' },
{ value: 'Europe/Paris', label: '(GMT+01:00) Paris' },
{ value: 'Europe/Berlin', label: '(GMT+01:00) Berlin' },
{ value: 'Europe/Rome', label: '(GMT+01:00) Rome' },
{ value: 'Africa/Lagos', label: '(GMT+01:00) Lagos' },
{ value: 'Europe/Istanbul', label: '(GMT+03:00) Istanbul' },
{ value: 'Asia/Dubai', label: '(GMT+04:00) Dubai' },
{ value: 'Asia/Kolkata', label: '(GMT+05:30) India' },
{ value: 'Asia/Bangkok', label: '(GMT+07:00) Bangkok' },
{ value: 'Asia/Shanghai', label: '(GMT+08:00) Shanghai' },
{ value: 'Asia/Tokyo', label: '(GMT+09:00) Tokyo' },
{ value: 'Australia/Sydney', label: '(GMT+10:00) Sydney' },
{ value: 'Pacific/Auckland', label: '(GMT+12:00) Auckland' },
];
const PLATFORM_OPTIONS = [
{ value: 'tiktok', label: 'TikTok', icon: <Video size={16} /> },
{ value: 'instagram', label: 'Instagram', icon: <Instagram size={16} /> },
{ value: 'youtube', label: 'YouTube', icon: <Youtube size={16} /> },
];
function getDayLabel(date) {
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const target = new Date(date);
target.setHours(0, 0, 0, 0);
if (target.getTime() === today.getTime()) return 'Today';
if (target.getTime() === tomorrow.getTime()) return 'Tomorrow';
return DAYS[target.getDay()];
}
function formatDate(date) {
return `${MONTHS[date.getMonth()]} ${date.getDate()}`;
}
function detectTimezone() {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
if (TIMEZONES.find(t => t.value === tz)) return tz;
return 'UTC';
} catch {
return 'UTC';
}
}
export default function ScheduleWeekModal({ isOpen, onClose, clips, jobId, uploadPostKey, uploadUserId, isManaged }) {
const [time, setTime] = useState('12:00');
const [timezone, setTimezone] = useState(detectTimezone);
const [platforms, setPlatforms] = useState({
tiktok: true,
instagram: true,
youtube: true
});
const [startOffset, setStartOffset] = useState(1);
const schedule = useMemo(() => {
if (!clips) return [];
return clips.map((clip, i) => {
const date = new Date();
date.setDate(date.getDate() + startOffset + i);
date.setHours(0, 0, 0, 0);
return { clip, index: i, date };
});
}, [clips, startOffset]);
const [scheduling, setScheduling] = useState(false);
const [progress, setProgress] = useState({ current: 0, total: 0, results: [] });
const [done, setDone] = useState(false);
// Reset state when modal reopens
const prevOpen = React.useRef(false);
React.useEffect(() => {
if (isOpen && !prevOpen.current) {
setScheduling(false);
setDone(false);
setProgress({ current: 0, total: 0, results: [] });
}
prevOpen.current = isOpen;
}, [isOpen]);
if (!isOpen) return null;
const selectedPlatforms = Object.keys(platforms).filter(k => platforms[k]);
// Managed (cloud plan/trial) users post with the server-side key — no BYOK needed
const canPost = isManaged || (uploadPostKey && uploadUserId);
const handleScheduleAll = async () => {
if (!canPost) return;
if (selectedPlatforms.length === 0) return;
setScheduling(true);
setDone(false);
const total = schedule.length;
setProgress({ current: 0, total, results: [] });
const results = [];
for (let i = 0; i < schedule.length; i++) {
const { clip, index, date } = schedule[i];
// Build local datetime string: "2026-04-06T12:00:00"
// Upload-Post accepts this + timezone IANA parameter
const pad = (n) => String(n).padStart(2, '0');
const scheduledDate = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${time}:00`;
const payload = {
job_id: jobId,
clip_index: index,
api_key: uploadPostKey,
user_id: uploadUserId,
platforms: selectedPlatforms,
title: clip.video_title_for_youtube_short || 'Viral Short',
description: clip.video_description_for_instagram || clip.video_description_for_tiktok || '',
scheduled_date: scheduledDate,
timezone
};
try {
const res = await apiFetch('/api/social/post', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) {
const errText = await res.text();
throw new Error(errText);
}
results.push({ index: i, success: true });
} catch (e) {
results.push({ index: i, success: false, error: e.message });
}
setProgress({ current: i + 1, total, results: [...results] });
}
setDone(true);
setScheduling(false);
};
const successCount = progress.results.filter(r => r.success).length;
const failCount = progress.results.filter(r => !r.success).length;
const footer = (
<div className="flex flex-col sm:flex-row gap-3">
<button
onClick={onClose}
disabled={scheduling}
className="btn-ghost flex-1"
>
{done ? 'close' : 'cancel'}
</button>
{!done ? (
<button
onClick={handleScheduleAll}
disabled={scheduling || !canPost || selectedPlatforms.length === 0}
className="btn-primary flex-1"
>
{scheduling ? (
<>
<Loader2 size={16} className="animate-spin" />
scheduling...
</>
) : (
<>
<Calendar size={16} />
schedule {clips?.length || 0} clips
</>
)}
</button>
) : (
<a
href="https://app.upload-post.com/calendar"
target="_blank"
rel="noopener noreferrer"
className="btn-primary flex-1 no-underline"
>
<ExternalLink size={16} />
view calendar
</a>
)}
</div>
);
return (
<Modal
isOpen={isOpen}
onClose={scheduling ? undefined : onClose}
eyebrow="PUBLISH · WEEK"
title="schedule week"
size="md"
footer={footer}
>
<p className="readout mb-4">{clips?.length || 0} CLIPS · 1/DAY</p>
{!canPost && (
<div className="mb-4 p-3 bg-warn/10 text-warn text-xs rounded-input flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<div>Set your Upload-Post API key in Settings first.</div>
</div>
)}
{/* Time + Timezone */}
<div className="mb-5 grid grid-cols-2 gap-3">
<div>
<label className="eyebrow block mb-2">time</label>
<input
type="time"
value={time}
onChange={(e) => setTime(e.target.value)}
disabled={scheduling}
className="input-field [color-scheme:dark]"
/>
</div>
<div>
<label className="eyebrow block mb-2">timezone</label>
<select
value={timezone}
onChange={(e) => setTimezone(e.target.value)}
disabled={scheduling}
className="input-field appearance-none cursor-pointer"
>
{TIMEZONES.map(tz => (
<option key={tz.value} value={tz.value}>{tz.label}</option>
))}
</select>
</div>
</div>
{/* Start day offset */}
<div className="mb-5 flex flex-wrap items-center justify-between gap-2">
<span className="eyebrow">start from</span>
<div className="flex items-center gap-2">
<button
onClick={() => setStartOffset(Math.max(1, startOffset - 1))}
disabled={startOffset <= 1 || scheduling}
className="btn-quiet px-2 py-2 disabled:opacity-40 disabled:cursor-not-allowed"
>
<ChevronLeft size={16} />
</button>
<span className="readout text-ink2 min-w-[110px] text-center">
{(() => {
const d = new Date();
d.setDate(d.getDate() + startOffset);
return `${getDayLabel(d)} · ${formatDate(d)}`;
})()}
</span>
<button
onClick={() => setStartOffset(startOffset + 1)}
disabled={scheduling}
className="btn-quiet px-2 py-2 disabled:opacity-40 disabled:cursor-not-allowed"
>
<ChevronRight size={16} />
</button>
</div>
</div>
{/* Calendar list */}
<div className="mb-5 border-y border-rule divide-y divide-rule">
{schedule.map(({ clip, index, date }) => (
<div key={index} className="flex items-center gap-3 py-2.5">
<div className="w-24 shrink-0">
<span className="readout">{getDayLabel(date)} · {formatDate(date)}</span>
</div>
<div className="flex-1 min-w-0">
<div className="text-xs text-ink truncate">
{clip.video_title_for_youtube_short || 'Viral Short'}
</div>
<div className="readout mt-0.5 truncate">
{time} · {TIMEZONES.find(t => t.value === timezone)?.label || timezone}
</div>
</div>
<div className="shrink-0">
{progress.results[index]?.success === true && (
<CheckCircle size={16} className="text-ok" />
)}
{progress.results[index]?.success === false && (
<AlertCircle size={16} className="text-danger" />
)}
{scheduling && progress.current === index && (
<Loader2 size={16} className="text-brass animate-spin" />
)}
{!scheduling && progress.results[index] === undefined && (
<Circle size={16} className="text-muted" />
)}
</div>
</div>
))}
</div>
{/* Platforms */}
<div className="mb-5">
<label className="eyebrow block mb-2">platforms</label>
<SegmentedControl
multi
options={PLATFORM_OPTIONS.map(opt => ({ ...opt, disabled: scheduling }))}
value={selectedPlatforms}
onChange={(arr) => setPlatforms({
tiktok: arr.includes('tiktok'),
instagram: arr.includes('instagram'),
youtube: arr.includes('youtube')
})}
/>
</div>
{/* A whole week of tiktok posts is a whole week of silent drafts:
this modal writes no captions of its own either (it sends the
clip's generated title/description), and tiktok keeps none of
them on a draft. Say it before the button, not after. */}
{platforms.tiktok && !scheduling && !done && <TikTokDraftNotice />}
{/* Progress bar */}
{(scheduling || done) && (
<div className="mb-1">
<div className="flex items-center justify-between mb-2">
<span className="text-xs text-muted lowercase">{scheduling ? 'scheduling...' : 'complete'}</span>
<span className="readout">{progress.current}/{progress.total}</span>
</div>
<div className="w-full h-1.5 bg-paper3 rounded-full overflow-hidden">
<div
className={`h-full rounded-full transition-all duration-500 ${done && failCount === 0 ? 'bg-ok' : done && failCount > 0 ? 'bg-danger' : 'bg-brass'}`}
style={{ width: `${(progress.current / progress.total) * 100}%` }}
/>
</div>
{done && (
<div className="mt-3 text-xs text-center lowercase">
{failCount === 0 ? (
<span className="text-ok">all clips scheduled</span>
) : (
<span className="text-danger">{successCount} scheduled, {failCount} failed</span>
)}
</div>
)}
</div>
)}
</Modal>
);
}

View file

@ -1,104 +0,0 @@
import React, { useEffect, useState } from 'react';
import { BarChart3, ExternalLink } from 'lucide-react';
import { apiJson } from '../lib/api';
const fmtNum = (n) => new Intl.NumberFormat('en-US', {
notation: (n || 0) >= 10000 ? 'compact' : 'standard',
maximumFractionDigits: 1,
}).format(n || 0);
// Upload-Post metric shapes vary per platform; read the first count that exists.
const postViews = (p) => {
const m = p.post_metrics || p.metrics || p;
return Number(m.views || m.impressions || m.plays || 0) || 0;
};
const postTitle = (p) => p.title || p.caption || p.youtube_title || p.tiktok_title || 'untitled post';
const postUrl = (p) => p.post_url || p.url || p.share_url || null;
// Post-publication analytics: what the clips actually did out there.
// Paid-only by nature (social posting itself is paid in cloud): a 402 or any
// other failure simply hides the card — the account page works without it.
export default function SocialAnalyticsCard() {
const [data, setData] = useState(null);
useEffect(() => {
let alive = true;
(async () => {
try {
const [imp, postsResp] = await Promise.all([
apiJson('/api/social/analytics/impressions?period=last_month&breakdown=true'),
apiJson('/api/social/analytics/posts?limit=50'),
]);
if (!alive) return;
const posts = (postsResp.posts || postsResp.data || postsResp.items || [])
.slice()
.sort((a, b) => postViews(b) - postViews(a));
setData({ imp, posts });
} catch (_) { /* free plan, nothing connected, or vendor hiccup — stay hidden */ }
})();
return () => { alive = false; };
}, []);
if (!data) return null;
const total = data.imp?.total_impressions
|| data.posts.reduce((s, p) => s + postViews(p), 0);
const perPlatform = Object.entries(data.imp?.per_platform || {})
.filter(([, v]) => Number(v) > 0)
.sort((a, b) => Number(b[1]) - Number(a[1]));
const top = data.posts.slice(0, 3);
return (
<div className="card p-6">
<div className="flex items-baseline justify-between gap-4 mb-1">
<h3 className="font-display lowercase text-lg text-ink flex items-center gap-2">
<BarChart3 size={16} className="text-brass" /> Your posts
</h3>
<span className="text-muted text-xs lowercase">last 30 days</span>
</div>
{data.posts.length === 0 && !total ? (
<p className="text-muted text-sm lowercase">
Nothing published yet. Post a clip from your results and its views show up here.
</p>
) : (
<>
<div className="flex items-end gap-3 mb-3">
<span className="readout text-2xl text-ink">{fmtNum(total)}</span>
<span className="text-muted text-sm lowercase mb-0.5">impressions</span>
</div>
{perPlatform.length > 0 && (
<div className="flex flex-wrap gap-x-4 gap-y-1 mb-4 text-sm">
{perPlatform.map(([platform, v]) => (
<span key={platform} className="text-ink2 lowercase">
{platform} <span className="text-brass">{fmtNum(Number(v))}</span>
</span>
))}
</div>
)}
{top.length > 0 && (
<div className="space-y-2 border-t border-rule pt-3">
{top.map((p, i) => (
<div key={p.request_id || p.platform_post_id || i}
className="flex items-center justify-between gap-3 text-sm">
<span className="text-ink2 truncate">
{postTitle(p)}
{postUrl(p) && (
<a href={postUrl(p)} target="_blank" rel="noreferrer"
className="inline-flex align-middle ml-1.5 text-muted hover:text-ink">
<ExternalLink size={12} />
</a>
)}
</span>
<span className="text-ink shrink-0">{fmtNum(postViews(p))} views</span>
</div>
))}
</div>
)}
</>
)}
</div>
);
}

View file

@ -1,13 +1,13 @@
import { Github } from 'lucide-react';
export const REPO_URL = 'https://github.com/mutonby/openshorts';
export const REPO_URL = 'https://git.pbento.pt/pedro-bento/clipwright';
// Small "star us" ask, once per job, while the clips render: that wait is the
// only dead time in the flow. Asking again on the finished clips made it two
// asks for the same job, and the old "free while it renders" wording put the
// word free next to the product name for anyone who missed the pun — the one
// thing our copy must never do. No incentive attached.
export default function StarBanner({ message = 'Enjoying OpenShorts?' }) {
export default function StarBanner({ message = 'Enjoying Clipwright?' }) {
return (
<a
href={REPO_URL}

View file

@ -6,6 +6,8 @@ import Modal from './ui/Modal';
import SegmentedControl from './ui/SegmentedControl';
const FONT_OPTIONS = [
{ value: 'Anton', label: 'Anton' },
{ value: 'Montserrat ExtraBold', label: 'Montserrat' },
{ value: 'Verdana', label: 'Verdana' },
{ value: 'Arial', label: 'Arial' },
{ value: 'Impact', label: 'Impact' },
@ -24,7 +26,10 @@ const COLOR_PRESETS = [
];
const HIGHLIGHT_PRESETS = [
{ color: '#FFE500', label: 'Yellow' },
{ color: '#FFDD00', label: 'Gold' },
{ color: '#A3FF12', label: 'Lime' },
{ color: '#7C3AED', label: 'Purple' },
{ color: '#FF4444', label: 'Red' },
{ color: '#00FF88', label: 'Green' },
{ color: '#00BBFF', label: 'Blue' },
@ -34,10 +39,37 @@ const HIGHLIGHT_PRESETS = [
const ANIMATION_OPTIONS = [
{ value: 'pop', label: 'Pop' },
{ value: 'word-highlight', label: 'Glow' },
{ value: 'karaoke', label: 'Karaoke' },
{ value: 'karaoke', label: 'Box' },
{ value: 'none', label: 'None' },
];
// Preview animation -> the effect burned server-side, so what the modal
// plays is what the clip gets. 'karaoke' in the preview is a box behind the
// active word, which is the 'highlight' effect.
const ANIMATION_TO_EFFECT = { pop: 'pop', 'word-highlight': 'glow', karaoke: 'highlight', none: 'none' };
const EFFECT_TO_ANIMATION = { pop: 'pop', glow: 'word-highlight', highlight: 'karaoke', box: 'karaoke', none: 'none' };
// Font size in the units /api/subtitle takes. M is what every clip ships
// with (subtitles.AUTO_CAPTION_STYLE font_size 44), so opening the modal and
// applying never shrinks the captions.
const SIZE_OPTIONS = [
{ value: 34, label: 'S' },
{ value: 44, label: 'M' },
{ value: 56, label: 'L' },
{ value: 70, label: 'XL' },
];
// Characters per line at size M, per font: Anton is condensed, Montserrat
// wide. Bigger text gets proportionally fewer, so a line still fits the 9:16
// frame instead of wrapping into a wall of text.
const LINE_CHARS = { Anton: 16, 'Montserrat ExtraBold': 9, Impact: 16 };
const lineBudget = (fontName, fontSize, oneWord) =>
oneWord ? 1 : Math.max(6, Math.round((LINE_CHARS[fontName] || 14) * 44 / fontSize));
// libass sizes text against PlayResY 288 (subtitles.generate_ass): one unit
// there is ~3.85 CSS px in the 1080x1920 preview, measured on burned frames.
const PREVIEW_PX_PER_UNIT = 3.85;
const POSITION_OPTIONS = [
{ value: 'top', label: 'top' },
{ value: 'middle', label: 'middle' },
@ -47,6 +79,15 @@ const POSITION_OPTIONS = [
// Ready-made caption looks burned server-side as karaoke ASS (word highlight):
// dimmed base text + strong active word, optional glow/pop/box effect.
const CAPTION_PRESETS = [
// What every clip ships with (subtitles.AUTO_CAPTION_STYLE).
{ id: 'default', label: 'Default', style: 'karaoke', effect: 'pop', highlightColor: '#FFE500', baseOpacity: 1.0, uppercase: true, fontName: 'Anton', borderWidth: 4, fontSize: 44 },
// Trending short-form looks (2026): word-by-word build-up, a box behind
// the active word, one big word at a time, and the clean shadow-only look.
{ id: 'hormozi', label: 'Hormozi', style: 'karaoke', effect: 'pop', highlightColor: '#FFE500', baseOpacity: 1.0, uppercase: true, fontName: 'Montserrat ExtraBold', borderWidth: 4, shadow: 2, reveal: true, fontSize: 44 },
{ id: 'pill', label: 'Pill', style: 'karaoke', effect: 'highlight', highlightColor: '#7C3AED', baseOpacity: 1.0, uppercase: true, fontName: 'Montserrat ExtraBold', borderWidth: 3, fontSize: 44 },
{ id: 'oneword', label: 'One word', style: 'karaoke', effect: 'pop', highlightColor: '#FFFFFF', baseOpacity: 1.0, uppercase: true, fontName: 'Anton', borderWidth: 5, oneWord: true, fontSize: 70 },
{ id: 'clean', label: 'Clean', style: 'karaoke', effect: 'none', highlightColor: '#FFFFFF', baseOpacity: 0.7, uppercase: false, fontName: 'Montserrat ExtraBold', borderWidth: 0, shadow: 2, fontSize: 34 },
{ id: 'lime', label: 'Lime box', style: 'karaoke', effect: 'highlight', highlightColor: '#A3FF12', baseOpacity: 1.0, uppercase: true, fontName: 'Montserrat ExtraBold', borderWidth: 3, fontSize: 44 },
{ id: 'tiktok', label: 'TikTok', style: 'karaoke', effect: 'none', highlightColor: '#FE2C55', baseOpacity: 0.75, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
{ id: 'reels', label: 'Reels', style: 'karaoke', effect: 'none', highlightColor: '#E1306C', baseOpacity: 0.7, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
{ id: 'shorts', label: 'Shorts Pop', style: 'karaoke', effect: 'pop', highlightColor: '#FF0000', baseOpacity: 0.7, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
@ -60,30 +101,48 @@ const CAPTION_PRESETS = [
{ id: 'classic', label: 'Classic', style: 'classic', effect: 'none', highlightColor: '#FFD700', baseOpacity: 1.0, uppercase: false, fontName: 'Verdana', borderWidth: 2 },
];
// Mirrors subtitles._luminance (Rec. 601).
const luminance = (hex) => {
const m = /^#?([0-9a-fA-F]{6})$/.exec(hex || '');
if (!m) return 1;
const [r, g, b] = [0, 2, 4].map((i) => parseInt(m[1].slice(i, i + 2), 16));
return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
};
const swatchClass = (selected) =>
`w-6 h-6 rounded-full transition-all ${selected
? 'ring-2 ring-[color:var(--color-accent)] ring-offset-2 ring-offset-[color:var(--color-paper-2)]'
: 'ring-1 ring-[color:var(--color-rule-2)] hover:ring-[color:var(--color-accent)]'}`;
export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll, onRemove, isProcessing, videoUrl, jobId, clipIndex, existingHook, bulkCount = 0, bulkProgress }) {
// Opens on the look the clip already has (the Default preset), so
// "apply" without touching anything changes nothing.
const [position, setPosition] = useState('bottom');
const [fontSize] = useState(24);
const [fontName, setFontName] = useState('Verdana');
const [fontSize, setFontSize] = useState(44);
const [fontName, setFontName] = useState('Anton');
const [fontColor, setFontColor] = useState('#FFFFFF');
const [highlightColor, setHighlightColor] = useState('#FFDD00');
const [highlightColor, setHighlightColor] = useState('#FFE500');
const [borderColor, setBorderColor] = useState('#000000');
const [borderWidth, setBorderWidth] = useState(2);
const [borderWidth, setBorderWidth] = useState(4);
const [bgColor, setBgColor] = useState('#000000');
const [bgOpacity, setBgOpacity] = useState(0.0);
const [animation, setAnimation] = useState('pop');
const [animation, setAnimationState] = useState('pop');
const [showTextEditor, setShowTextEditor] = useState(false);
// Karaoke (server-side ASS burn) state
const [style, setStyle] = useState('classic'); // classic | karaoke
const [effect, setEffect] = useState('none'); // none | glow | pop | box
const [style, setStyle] = useState('karaoke'); // classic | karaoke
const [effect, setEffect] = useState('pop'); // none | glow | pop | box | highlight
const [baseOpacity, setBaseOpacity] = useState(1.0);
const [uppercase, setUppercase] = useState(false);
const [activePreset, setActivePreset] = useState(null);
const [uppercase, setUppercase] = useState(true);
const [reveal, setReveal] = useState(false);
const [shadow, setShadow] = useState(0);
const [oneWord, setOneWord] = useState(false);
const [activePreset, setActivePreset] = useState('default');
const setAnimation = (value) => {
setAnimationState(value);
if (style === 'karaoke') setEffect(ANIMATION_TO_EFFECT[value] || 'none');
};
const applyPreset = (p) => {
setActivePreset(p.id);
@ -96,10 +155,17 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll,
setBorderWidth(p.borderWidth);
setFontColor('#FFFFFF');
setBgOpacity(0);
// Keep the Remotion preview roughly in sync with the burned look
setAnimation(p.style === 'karaoke' ? (p.effect === 'pop' ? 'pop' : p.effect === 'glow' ? 'word-highlight' : 'karaoke') : 'none');
setReveal(!!p.reveal);
setShadow(p.shadow || 0);
setOneWord(!!p.oneWord);
if (p.fontSize) setFontSize(p.fontSize);
setAnimationState(p.style === 'karaoke' ? (EFFECT_TO_ANIMATION[p.effect] || 'none') : 'none');
};
const maxChars = lineBudget(fontName, fontSize, oneWord);
// Same block duration as the auto captions (AUTO_CAPTION_STYLE).
const maxDuration = 1.4;
// Remotion preview state
const [captions, setCaptions] = useState([]);
const [originalCaptions, setOriginalCaptions] = useState([]);
@ -158,9 +224,11 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll,
const subtitleConfig = {
captions,
position,
maxChars,
maxDurationMs: maxDuration * 1000,
style: {
fontFamily: fontName,
fontSize: fontSize * 2.2, // Scale up for 1080p (modal fontSize is for small preview)
fontSize: Math.round(fontSize * 0.85 * PREVIEW_PX_PER_UNIT),
fontColor,
highlightColor,
borderColor,
@ -171,6 +239,10 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll,
// Karaoke look reflected live in the playable preview.
baseOpacity: style === 'karaoke' ? baseOpacity : 1,
uppercase: style === 'karaoke' ? uppercase : false,
reveal: style === 'karaoke' && reveal,
shadow: style === 'karaoke' ? shadow : 0,
// Text on the active-word box: black on a light box, as burned.
highlightTextColor: luminance(highlightColor) > 0.6 ? '#000000' : fontColor,
},
};
@ -296,6 +368,38 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll,
/>
</div>
{/* Size */}
<div>
<p className="eyebrow mb-2">Size</p>
<SegmentedControl
options={SIZE_OPTIONS}
value={fontSize}
onChange={setFontSize}
size="sm"
/>
</div>
{style === 'karaoke' && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="readout">One word at a time</span>
<label className="relative inline-flex items-center cursor-pointer">
<input type="checkbox" checked={oneWord} onChange={(e) => setOneWord(e.target.checked)} className="sr-only peer" />
<div className="w-8 h-4 rounded-full bg-paper3 peer-checked:bg-brass transition-colors after:content-[''] after:absolute after:top-0 after:left-0 after:h-4 after:w-4 after:rounded-full after:bg-ink after:transition-all peer-checked:after:translate-x-full"></div>
</label>
</div>
{!oneWord && (
<div className="flex items-center justify-between">
<span className="readout">Reveal word by word</span>
<label className="relative inline-flex items-center cursor-pointer">
<input type="checkbox" checked={reveal} onChange={(e) => setReveal(e.target.checked)} className="sr-only peer" />
<div className="w-8 h-4 rounded-full bg-paper3 peer-checked:bg-brass transition-colors after:content-[''] after:absolute after:top-0 after:left-0 after:h-4 after:w-4 after:rounded-full after:bg-ink after:transition-all peer-checked:after:translate-x-full"></div>
</label>
</div>
)}
</div>
)}
{/* Animation Style (new) */}
<div>
<p className="eyebrow mb-2">Animation</p>
@ -453,6 +557,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, onApplyAll,
position, fontSize, fontName, fontColor, borderColor, borderWidth, bgColor, bgOpacity,
// Karaoke burn (server-side ASS render)
style, effect, baseOpacity, uppercase, highlightColor,
reveal: !oneWord && reveal, shadow, maxChars, maxDuration,
// Remotion data
remotion: useRemotionPreview ? subtitleConfig : null,
captions: textEdited ? captions : null,

View file

@ -70,11 +70,10 @@ function DragDropZone({ label, accept, onFile, file, onClear, icon }) {
);
}
export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, 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, uploadPostKey, uploadUse
// --- Publish to YouTube ---
const handlePublish = async () => {
if (!managed && (!uploadPostKey || !uploadUserId)) return alert('Please configure your Upload-Post API key and user in Settings first.');
if (!postizUrl || !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.');
@ -390,12 +389,15 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
formData.append('title', finalTitle);
formData.append('description', description);
formData.append('thumbnail_url', selectedThumbnail);
formData.append('api_key', uploadPostKey);
formData.append('user_id', uploadUserId);
const headers = {};
if (postizKey) headers['X-Postiz-Key'] = postizKey;
if (postizUrl) headers['X-Postiz-Url'] = postizUrl.replace(/\/$/, '');
// Submit the publish job — returns immediately with a publish_id
const res = await apiFetch('/api/thumbnail/publish', {
method: 'POST',
headers,
body: formData
});
@ -471,7 +473,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* Header */}
<div className="flex items-end justify-between mb-2">
<div>
<p className="eyebrow mb-2">06 · YOUTUBE STUDIO</p>
<p className="eyebrow mb-2">02 · YOUTUBE STUDIO</p>
<h1 className="font-display lowercase text-2xl text-ink flex items-center gap-3">
<span className="w-10 h-10 rounded-card bg-paper3 flex items-center justify-center">
<Image size={18} className="text-brass" />
@ -491,7 +493,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
<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" />
@ -1136,14 +1138,14 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
</div>
{/* Publish Button */}
{(!managed && (!uploadPostKey || !uploadUserId)) ? (
{!postizKey || !postizUrl ? (
<div className="glass-panel p-6 space-y-3">
<div className="flex items-center gap-2 text-warn">
<AlertCircle size={16} />
<span className="text-sm font-medium lowercase">Upload-Post Not Configured</span>
<span className="text-sm font-medium lowercase">Postiz Not Configured</span>
</div>
<p className="text-xs text-muted">
To publish directly to YouTube, configure your Upload-Post API key and connect a profile in Settings.
To publish directly to YouTube, configure your Postiz base URL and API key in Settings.
</p>
<button
onClick={() => { }}

View file

@ -1,35 +0,0 @@
import React from 'react';
import { AlertCircle } from 'lucide-react';
/**
* Shown wherever tiktok is among the selected platforms, before the button
* that posts or schedules.
*
* Two different people need it. Someone who publishes one clip expects a live
* post and finds nothing on their profile, and reads that as a failure. Someone
* who schedules a week gets a silent drawer of drafts and a profile that stays
* empty for seven days.
*
* The title/description line is not a detail: TikTok's upload-to-inbox endpoint
* takes only source_info (the bytes), with no post_info anywhere in the request,
* so the caption we send is dropped on the floor for a video draft — whether the
* user typed it or the AI wrote it. Saying only "it arrives as a draft" leaves
* them to discover that in the app.
*
* Lead with the upside: finishing the post inside TikTok is what the algorithm
* rewards, so this is a better default, not a limitation we are apologising for.
*/
export default function TikTokDraftNotice() {
return (
<div className="mb-4 px-3 py-2 rounded-input text-xs text-ink2 bg-paper3 flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0 text-brass" />
<div className="lowercase">
tiktok arrives as a <b className="text-ink">draft</b>, not a live post — you'll
get a notification in the app. its api won't carry the title or description
onto a draft, so you write those there too, along with trending sounds,
effects and hashtags — which reaches more people than posting straight
from an api.
</div>
</div>
);
}

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