Commit graph

11 commits

Author SHA1 Message Date
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
victorcavero14
725aebf1a3 feat(funnel): first free video clipped whole, auto-partial instead of the wall, lifecycle emails
- Free source past the balance: first video (<= 60 min) clipped whole for the
  balance, any other clipped to the first N minutes. No 402 wall for free
  accounts with >= PARTIAL_MIN_MINUTES left.
- cloud/lifecycle.py: welcome, first-clip nudge, win-back (optional
  WINBACK_PROMO_CODE from env) and abandoned-checkout recovery via
  after_expiration.recovery + checkout.session.expired.
- Commercial emails go through send_commercial_email: opt-out honoured,
  unsubscribe footer and List-Unsubscribe headers (out-of-minutes too).
2026-09-28 13:05:43 +02:00
victorcavero14
8f57560fa5 feat(autopilot): clip every new video on the connected YouTube channel
Most subscribers use OpenShorts on one day and cancel. Autopilot makes the
value recur: once switched on, every new upload on the user's YouTube channel
(listed through the existing Upload-Post connection, no scraping) is sent
through the normal /api/process pipeline, the user gets an email when the
clips are ready, and with autopublish on the best clips are scheduled on
their socials, one a day.

- cloud/autopilot.py: poller, in-process job submission as the user,
  completion hook, autopublish, and /api/autopilot{,/videos,/run}
- guard rails: only videos published after switching on, max 3 days old,
  1 automatic job per user per day, first N minutes per video, Shorts skipped,
  paid plans only, dedupe by (user, video) across the deploy handover
- dashboard: new Autopilot tab (sidebar + mobile menu, #app?tab=autopilot)
- connect page can return to the Autopilot tab
- analytics: ClipsDelivered/JobFailed now report source=url and the plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-22 21:36:19 +02:00
juancarlos.cavero
b4bf211b7b fix(cloud): close the gaps the account-deletion review turned up
Eight findings from re-reading the erasure path, each one something that would
have shown up in production rather than in a test:

- The local purge missed two stores. SaaSShorts outputs (output/saas_<id>) and
  generated thumbnails record ownership in their own in-memory dicts, not in
  the .owner file, so neither was erased. Thumbnails are the serious half: the
  hourly sweep deliberately skips their directory, so a deleted user's
  generated images stayed on disk forever, publicly served at /thumbnails/.
- The purge ran on the event loop. rmtree over gigabytes of video stalled every
  other request on the process; it goes through asyncio.to_thread now.
- Paths from those dicts are now resolved through _safe_under, so a session id
  or output_dir containing ".." deletes nothing.
- Deleting a user made a webhook path reachable that never was: _apply_topup
  takes the user id from Stripe metadata, so a top-up completing around the
  deletion inserted a row pointing at a user that no longer exists. The FK
  violation 500s the webhook, and since the event is only recorded after
  handle_event returns, Stripe retries the same doomed insert for three days.
  It confirms the row exists first.
- The "why are you leaving" box was free text stored in a record that
  deliberately outlives the account, which is how personal data ends up in one
  by accident. It is a closed list now, which also makes twenty deletions a
  month countable instead of readable.
- Two concurrent deletes wrote two erasure records and sent two goodbye emails.
  The DELETE's rowcount now decides which call is the real one; the UI holds a
  ref so a double click doesn't fire a second Stripe cancel and R2 purge.
- The delete button armed itself when the confirm box was empty, if the page
  ever rendered before /api/me resolved.
- The goodbye email claimed we keep "a one-way hash of your email and nothing
  else", which was not true of the Stripe reference beside it. Fixed in the
  email and in the privacy policy, EN and ES.

Also: skip the Upload-Post call when no managed key is configured, and say
plainly in the in-flight comment that it covers metered work only.

tests/test_account_local_purge.py covers tenant isolation across all three
stores and both traversal attempts; test_account_erasure.py gains the
confirmation gate, the API-key refusal, and the already-cancelled-at-Stripe
case that would otherwise trap a user forever.
2026-08-24 19:26:12 +02:00
juancarlos.cavero
1d9fef7445 feat(cloud): self-service account deletion (GDPR art. 17)
The privacy policy already told users that "deleting your account from the
dashboard removes your content" — there was no way to do it. This adds one:
Account -> Delete account in the dashboard, DELETE /api/account on the server.

The endpoint refuses API-key auth (a leaked osk_ must not destroy the account
it was issued from) and requires the caller to retype the account email; the UI
does the same, collapsed behind a danger zone that itemises what actually goes.
Erasure is immediate and irreversible, because after it there is nothing left
to authenticate a recovery request against.

The order of the steps is the design, each one a failure mode:

- Stripe cancel first, aborting everything if it fails, so we never erase a
  user we are still billing. An InvalidRequestError is treated as already
  cancelled: a portal cancellation whose webhook never landed leaves our row
  reading "active" forever, and the one account that could not be deleted
  would be the one Stripe already stopped charging.
- R2 before the database, because those rows are the only index of which
  objects belong to the user; dropping them first turns a failed purge into
  permanent orphans.
- The DB delete is one transaction over an explicit table list, not the
  declared ON DELETE CASCADEs: create_all never ALTERs an existing table, so a
  constraint added after a table shipped lives in the models and not in
  production. tests/test_account_erasure.py fails if a new table references
  users.id without joining that list.
- A reserved usage_ledger row blocks the delete: erasing under a running job
  would pull the output from beneath it and leave the reservation unsettled.

What survives, and why: the Stripe customer and its invoices (six years,
Spanish commercial law) and one account_deletions row holding a sha256 of the
email as proof the erasure happened, itself purged after five years by the
retention sweeper. app.py registers a callback so the working files in output/
and uploads/ go too instead of waiting for the hourly sweep.

Privacy policy sections 6 (EN + ES) now point at the button and name both
survivors; the Legal hub summary says the same in one line.
2026-08-24 19:12:05 +02:00
juancarlos.cavero
8f873296a1 fix(emails): stop duplicate expiry warnings and fix the button that 404s
Two bugs in the "your N clips will be deleted tomorrow" email.

The button pointed at {frontend_url}/dashboard, a route that has never existed:
the app is a single-page app routed entirely through the hash, and #app is what
opens it. Until today /dashboard fell through to the SPA fallback and quietly
showed the marketing landing, so the link looked like it worked. Now that
unknown paths return a real 404 it fails visibly. Both this and the clips-ready
email now link to /#app; the clips-ready one was passing the bare frontend URL,
which showed the landing page to anyone whose browser had not already set the
skip-landing flag.

The duplicate send is worse. De-duplication was `_warned_video_ids`, a set in
process memory, and the warning window is a full day while the sweep runs every
six hours. Any API restart inside that window re-armed the warning for everyone
already told. That is exactly what happened today: the 06:00 warning went out,
three deploys restarted the API (frontend and API share this repo, so the SEO
pushes redeployed both), the container came up at 12:36, and the sweeper's first
run six hours later at 18:36 mailed the same clips again.

Warnings are now recorded in clip_expiry_warnings, keyed by clip id, written
before the send. A new table rather than a column because the schema bootstrap
is create_all, which creates missing tables but never ALTERs one — same reason
SignupAttribution is its own table. The FK cascades from user_videos, so rows
disappear when purge_free_expired deletes the clip and no cleanup pass is needed.

Recording before sending is deliberate: a duplicate email is the failure being
fixed, while a warning row for a mail that then failed to send costs that user
one notice.

No backfill. Clips already warned about have no row yet, so the current cohort
gets one more warning after this deploys and none after that. Backfilling the
window would also silence the first warning for anyone who entered it since the
last sweep, and a missed deletion notice costs the user their clips, while a
duplicate only costs them an email.

Verified against a real Postgres: create_all builds the table, the primary key
rejects a second row for the same clip, the cascade removes warnings when the
clip is deleted, and warn_free_expiring sends exactly one email across two
sweeps plus a module reload standing in for a restart (which is what used to
produce the second email).
2026-07-27 22:31:04 +02:00
juancarlos.cavero
c88239921e feat(conversion): vender también en los momentos buenos, no solo en el muro
Hasta ahora el único camino al upgrade era fallar contra la cuota. Tres
momentos nuevos, todos con el mismo mensaje ya validado (watermark +
caducidad 7d + minutos):

- Resultados (pico de satisfacción): banner para usuarios free junto a
  sus clips recién generados — "Like these clips? Keep them forever →" —
  que abre la modal de upgrade en modo 'upsell' (copy adaptado: aún
  tienen minutos, se vende permanencia y limpieza, no "te quedaste sin").
- Medidor del header: para free abre la modal de upgrade en vez de ir a
  account — antes no existía ningún camino visible a los planes desde el
  dashboard sin fallar primero.
- Email "tus clips se borran mañana": warn_free_expiring() en el sweeper
  avisa el día 6 de los 7 de retención free, con descarga o upgrade como
  salidas. Aversión a la pérdida honesta: la fecha es real y hoy se
  borraba en silencio, lo que no convertía a nadie. Dedupe en memoria
  (peor caso tras restart: un duplicado).

Eventos UpsellModalSeen/UpsellModalCheckout separados de los del muro
para medir cada momento por su lado.

Verificado: lógica del aviso probada contra la DB local (clip de 6.5d
avisa, el de 8d ya purgeable no, segundo pase no duplica); 141 tests y
build del dashboard en verde.
2026-07-25 02:27:34 +02:00
juancarlos.cavero
95a9a5ff1e feat(conversion): vender el plan (no top-ups) en el momento del muro de cuota
De 76 impactos del muro 402 en 72h solo 4 llegaron a checkout y la única
compra fue un top-up: la modal antigua ofrecía packs de minutos sueltos
como opción principal, el upgrade a plan era un párrafo NO clickable y
un StarBanner empujaba a GitHub en pleno momento de compra.

Nueva modal (mismo fichero/props, cero cambios en App.jsx):
- Starter destacado + Creator al lado como ancla de precio; bullets del
  valor real de pagar: 5x/15x minutos, sin watermark, clips permanentes
  (los free caducan a 7 dias) y prioridad de cola sobre free — todo
  cierto, sin escasez inventada ni cuentas atras falsas.
- Copy goal-gradient con los datos del 402: "this video needs X min and
  you have Y left — upgrade and it starts processing right away".
- "cancel anytime" como reversion de riesgo; top-ups relegados a un link
  discreto que expande; StarBanner fuera.
- Eventos QuotaWallSeen / QuotaWallCheckout para medir la conversion del
  muro, que hasta ahora era invisible.

El email de sin-minutos replica el mismo mensaje (perdida + plan concreto
+ CTA unico) y por fin deja rastro en logs al enviarse.

Verificado end-to-end en local: usuario free con cuota agotada via DB,
402 real de /api/process, modal con datos reales y packs expandibles.
2026-07-25 02:14:58 +02:00
juancarlos.cavero
9fd1cacb0c feat(billing): free plan (20 min/mes sin tarjeta) + retirar trial + opt-in galería UGC
- Plan free resuelto en metering (sin fila Stripe): 20 min/mes para cuentas
  Google, período sintético de mes natural con reset automático
- TRIAL_DAYS=0 para nuevos checkouts; trials en curso grandfathered
- Watermark drawtext en clips free (pasada única post-render, sobrevive
  subtítulos/hooks); thumbnails IA solo de pago
- Anti-abuso: 3 jobs/día por cuenta, 5 por IP, rate-limit de probes,
  contador mensual de GB de proxy con alerta Telegram a 100 GB
- Clips free caducan a 7 días (purge_free_expired); purge_expired respeta
  a cancelados que ahora son free
- Galería UGC pública pasa a opt-in (share_to_gallery, antes publicaba
  producto+guion de todos los usuarios sin permiso)
- Emails: clips listos (con star-ask) y sin-minutos (cooldown 24h)
- Frontend: card Free en pricing, copy sin trial (landing/legal/gates),
  StarBanner en resultados y TopUpModal, upsell de watermark
2026-07-20 00:26:21 +02:00
juancarlos.cavero
12d423d739 feat: 720p->360p download fallback + SMTP email alerts
- main.py / metering.py: try the HD (bgutil/720p) strategy first, fall back to
  the conservative (360p) clients on any failure, so a YouTube/yt-dlp change
  degrades gracefully instead of failing the whole job.
- cloud/alerts.py: in-memory tracking of managed-job outcomes; emails the admin
  (ADMIN_EMAIL) when a proxy/credit error appears or when many jobs fail in a
  row, with a 1h per-alert cooldown. Wired into run_job_wrapper.
- Email switched from Resend to SMTP (cloud/emails.py) for magic link + alerts
  (Namecheap Private Email). Config via SMTP_* / EMAIL_FROM / ADMIN_EMAIL in the
  mounted .env (kept out of compose so the password's $/* aren't mangled).

SMTP send verified from host and from the backend container.
2026-07-14 14:00:02 +02:00
juancarlos.cavero
05578c5456 feat: add hosted paid mode (managed keys, Stripe trial, metering)
Adds an optional cloud/paid mode behind a BILLING_ENABLED flag. With the flag
off the app is byte-identical to today's self-hosted BYOK build (regression-zero).

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

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

Verified end-to-end against real Postgres + Stripe test mode.
2026-07-14 13:04:43 +02:00