From edcfeaf9d56ff4f652c7cef04e3c766cb143fe2c Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Sun, 4 Oct 2026 17:02:55 +0100 Subject: [PATCH] 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 --- .env.example | 29 +- CLAUDE.md | 39 +- Dockerfile | 6 +- alembic.ini | 41 - alembic/env.py | 60 - alembic/script.py.mako | 22 - app.py | 1385 +---------------- cli/README.md | 50 +- cli/openshorts_cli.py | 50 +- cli/pyproject.toml | 4 +- cloud/LICENSE | 66 - cloud/__init__.py | 65 - cloud/account.py | 376 ----- cloud/alerts.py | 438 ------ cloud/analytics.py | 123 -- cloud/api_keys.py | 147 -- cloud/auth.py | 398 ----- cloud/autopilot.py | 873 ----------- cloud/billing.py | 774 --------- cloud/cancellation.py | 300 ---- cloud/config.py | 374 ----- cloud/database.py | 72 - cloud/digest.py | 138 -- cloud/disposable_domains.txt | 166 -- cloud/disposable_mx.txt | 26 - cloud/email_policy.py | 176 --- cloud/emails.py | 326 ---- cloud/lifecycle.py | 232 --- cloud/managed_keys.py | 25 - cloud/marketing.py | 107 -- cloud/mcp_oauth.py | 357 ----- cloud/metering.py | 727 --------- cloud/models.py | 467 ------ cloud/oauth.py | 111 -- cloud/onboarding.py | 113 -- cloud/proxy_ledger.py | 236 --- cloud/social_profiles.py | 112 -- cloud/storage.py | 116 -- cloud/videos.py | 650 -------- dashboard/index.html | 78 +- dashboard/seo/data.js | 38 +- dashboard/seo/landing-fallback.js | 13 +- dashboard/seo/legal.js | 714 +++------ dashboard/seo/pages.js | 274 ++-- dashboard/seo/render.js | 9 +- dashboard/seo/tools.js | 7 +- dashboard/src/App.jsx | 674 +------- dashboard/src/Landing.jsx | 106 +- dashboard/src/components/AccountPage.jsx | 247 --- dashboard/src/components/ApiKeysCard.jsx | 116 -- dashboard/src/components/CancelPlanModal.jsx | 238 --- dashboard/src/components/ClipEditor.jsx | 12 +- .../src/components/DeleteAccountCard.jsx | 150 -- dashboard/src/components/HistoryTab.jsx | 126 -- dashboard/src/components/InvoicesCard.jsx | 92 -- dashboard/src/components/LoginModal.jsx | 104 -- dashboard/src/components/OAuthConsent.jsx | 111 -- dashboard/src/components/OnboardingSurvey.jsx | 131 -- dashboard/src/components/PlanChoiceModal.jsx | 96 -- dashboard/src/components/PricingPage.jsx | 319 ---- dashboard/src/components/PricingSection.jsx | 189 --- dashboard/src/components/ProfileMenu.jsx | 62 - dashboard/src/components/ResultCard.jsx | 39 +- dashboard/src/components/ThumbnailStudio.jsx | 13 +- dashboard/src/components/TopUpModal.jsx | 226 --- dashboard/src/components/TrialGate.jsx | 26 - .../src/components/TrialUpgradeModal.jsx | 90 -- dashboard/src/components/UsageMeter.jsx | 28 - dashboard/src/components/WatermarkModal.jsx | 97 -- dashboard/src/contexts/AuthContext.jsx | 157 +- dashboard/src/lib/analytics.js | 72 +- dashboard/src/lib/api.js | 43 +- dashboard/src/lib/attribution.js | 82 - dashboard/src/main.jsx | 79 +- dashboard/vite-plugin-seo.js | 15 +- docker-compose.cloud.yml | 53 - docs/compliance/retencion.md | 72 +- docs/compliance/subprocessors.md | 98 +- free_tools.py | 7 - log_view.py | 120 -- main.py | 9 +- media_auth.py | 3 +- requirements-billing.txt | 12 - skills/openshorts/.claude-plugin/plugin.json | 2 +- skills/openshorts/SKILL.md | 6 +- tests/conftest.py | 6 - tests/test_account_erasure.py | 200 --- tests/test_account_local_purge.py | 143 -- tests/test_agent_uploads.py | 171 -- tests/test_alert_classify.py | 80 - tests/test_api_keys.py | 42 - tests/test_audit_hardening.py | 86 +- tests/test_auto_retry.py | 17 +- tests/test_autopilot.py | 144 -- tests/test_billing_states.py | 93 -- tests/test_cancellation.py | 228 --- tests/test_caption_presets.py | 40 +- tests/test_cleanup_live_jobs.py | 25 +- tests/test_email_policy.py | 155 -- tests/test_free_plan_denied.py | 164 -- tests/test_job_error_text.py | 64 - tests/test_lifecycle_emails.py | 187 --- tests/test_log_view.py | 92 -- tests/test_mcp_endpoint.py | 149 -- tests/test_mcp_oauth.py | 84 - tests/test_mcp_protocol.py | 83 - tests/test_mcp_stdio.py | 54 - tests/test_mcp_ui.py | 102 -- tests/test_metering_free_plan.py | 55 - tests/test_no_blocking_http_in_async.py | 12 +- tests/test_onboarding_survey.py | 52 - tests/test_openpanel_revenue.py | 76 - tests/test_partial_processing.py | 262 ---- tests/test_probe_anonymous_fallback.py | 111 -- tests/test_probe_noplaylist.py | 123 -- tests/test_probe_plan.py | 123 -- tests/test_process_handover.py | 2 +- tests/test_proxy_ledger.py | 355 ----- tests/test_proxy_watch.py | 196 --- tests/test_proxy_watch_alerts.py | 56 - tests/test_reframe_endpoint.py | 8 +- tests/test_rerender_endpoint.py | 19 +- tests/test_social_tenant_isolation.py | 88 -- tests/test_source_access.py | 88 +- tests/test_static_probe_cookies.py | 116 -- tests/test_subtitle_metering.py | 32 - tests/test_transcript_checkpoint.py | 2 +- tests/test_watermark_delivery.py | 147 +- tests/test_youtube_non_video_urls.py | 39 +- tests/test_yt_clients.py | 24 - watermarked.py | 23 +- 131 files changed, 831 insertions(+), 18619 deletions(-) delete mode 100644 alembic.ini delete mode 100644 alembic/env.py delete mode 100644 alembic/script.py.mako delete mode 100644 cloud/LICENSE delete mode 100644 cloud/__init__.py delete mode 100644 cloud/account.py delete mode 100644 cloud/alerts.py delete mode 100644 cloud/analytics.py delete mode 100644 cloud/api_keys.py delete mode 100644 cloud/auth.py delete mode 100644 cloud/autopilot.py delete mode 100644 cloud/billing.py delete mode 100644 cloud/cancellation.py delete mode 100644 cloud/config.py delete mode 100644 cloud/database.py delete mode 100644 cloud/digest.py delete mode 100644 cloud/disposable_domains.txt delete mode 100644 cloud/disposable_mx.txt delete mode 100644 cloud/email_policy.py delete mode 100644 cloud/emails.py delete mode 100644 cloud/lifecycle.py delete mode 100644 cloud/managed_keys.py delete mode 100644 cloud/marketing.py delete mode 100644 cloud/mcp_oauth.py delete mode 100644 cloud/metering.py delete mode 100644 cloud/models.py delete mode 100644 cloud/oauth.py delete mode 100644 cloud/onboarding.py delete mode 100644 cloud/proxy_ledger.py delete mode 100644 cloud/social_profiles.py delete mode 100644 cloud/storage.py delete mode 100644 cloud/videos.py delete mode 100644 dashboard/src/components/AccountPage.jsx delete mode 100644 dashboard/src/components/ApiKeysCard.jsx delete mode 100644 dashboard/src/components/CancelPlanModal.jsx delete mode 100644 dashboard/src/components/DeleteAccountCard.jsx delete mode 100644 dashboard/src/components/HistoryTab.jsx delete mode 100644 dashboard/src/components/InvoicesCard.jsx delete mode 100644 dashboard/src/components/LoginModal.jsx delete mode 100644 dashboard/src/components/OAuthConsent.jsx delete mode 100644 dashboard/src/components/OnboardingSurvey.jsx delete mode 100644 dashboard/src/components/PlanChoiceModal.jsx delete mode 100644 dashboard/src/components/PricingPage.jsx delete mode 100644 dashboard/src/components/PricingSection.jsx delete mode 100644 dashboard/src/components/ProfileMenu.jsx delete mode 100644 dashboard/src/components/TopUpModal.jsx delete mode 100644 dashboard/src/components/TrialGate.jsx delete mode 100644 dashboard/src/components/TrialUpgradeModal.jsx delete mode 100644 dashboard/src/components/UsageMeter.jsx delete mode 100644 dashboard/src/components/WatermarkModal.jsx delete mode 100644 dashboard/src/lib/attribution.js delete mode 100644 docker-compose.cloud.yml delete mode 100644 log_view.py delete mode 100644 requirements-billing.txt delete mode 100644 tests/test_account_erasure.py delete mode 100644 tests/test_account_local_purge.py delete mode 100644 tests/test_agent_uploads.py delete mode 100644 tests/test_alert_classify.py delete mode 100644 tests/test_api_keys.py delete mode 100644 tests/test_autopilot.py delete mode 100644 tests/test_billing_states.py delete mode 100644 tests/test_cancellation.py delete mode 100644 tests/test_email_policy.py delete mode 100644 tests/test_free_plan_denied.py delete mode 100644 tests/test_job_error_text.py delete mode 100644 tests/test_lifecycle_emails.py delete mode 100644 tests/test_log_view.py delete mode 100644 tests/test_mcp_endpoint.py delete mode 100644 tests/test_mcp_oauth.py delete mode 100644 tests/test_mcp_protocol.py delete mode 100644 tests/test_mcp_stdio.py delete mode 100644 tests/test_mcp_ui.py delete mode 100644 tests/test_metering_free_plan.py delete mode 100644 tests/test_onboarding_survey.py delete mode 100644 tests/test_openpanel_revenue.py delete mode 100644 tests/test_partial_processing.py delete mode 100644 tests/test_probe_anonymous_fallback.py delete mode 100644 tests/test_probe_noplaylist.py delete mode 100644 tests/test_probe_plan.py delete mode 100644 tests/test_proxy_ledger.py delete mode 100644 tests/test_proxy_watch.py delete mode 100644 tests/test_proxy_watch_alerts.py delete mode 100644 tests/test_social_tenant_isolation.py delete mode 100644 tests/test_static_probe_cookies.py delete mode 100644 tests/test_subtitle_metering.py diff --git a/.env.example b/.env.example index 2c0dbab..8bcc541 100644 --- a/.env.example +++ b/.env.example @@ -3,19 +3,11 @@ AWS_ACCESS_KEY_ID=your_aws_access_key_here AWS_SECRET_ACCESS_KEY=your_aws_secret_key_here AWS_REGION=eu-west-3 AWS_S3_BUCKET=your-bucket-name -AWS_S3_PUBLIC_BUCKET=your-public-bucket-name # YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection) # YOUTUBE_COOKIES=... -# Google OAuth (cloud/billing mode only). When logging in through a proxy whose -# Host header doesn't match a Google-registered URI (e.g. local dev via the Vite -# proxy), pin the callback explicitly: -# OAUTH_REDIRECT_URI=http://localhost:8000/api/auth/google/callback -# FRONTEND_URL=http://localhost:5175 - -# Local dev: show the full pipeline logs (yt-dlp/ffmpeg/debug) in the UI even -# when running in paid mode (BILLING_ENABLED). Cloud/prod leaves this unset. +# Local dev: show the full pipeline logs (yt-dlp/ffmpeg/debug) in the UI. # DEBUG_LOGS=true # Pre-flight quality gate: warn before processing a YouTube source below this @@ -75,11 +67,9 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image # Privacy, retention and access control (GDPR remediation, 4-sep-2026) # --------------------------------------------------------------------------- -# Absolute base URL of the API as the internet reaches it. Already used for the -# absolute clip URLs in webhook payloads; now also required to build the -# unsubscribe link that goes in the out-of-minutes email. Without it that email -# falls back to "reply to unsubscribe". -# PUBLIC_API_URL=https://api.openshorts.app +# Absolute base URL of the API as the internet reaches it, used for the +# absolute clip URLs in webhook payloads. +# PUBLIC_API_URL=https://your-host # /videos and /thumbnails are authenticated endpoints, not static mounts. # MEDIA_TOKEN_TTL_SECONDS: life of the per-user token the dashboard appends to @@ -131,19 +121,10 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image # HSTS_HEADER=max-age=31536000; includeSubDomains # Encrypted PostgreSQL backups (ops/pg_backup.sh — installed and scheduled on -# the database host, not by the app). The privacy policy promises a deletion is -# gone from every copy within 30 days, which is only true while this runs. +# the database host, not by the app). # DATABASE_URL=postgres://user:pass@host:5432/openshorts # BACKUP_AGE_RECIPIENT=age1... # BACKUP_DEST=s3://openshorts-backups/pg # BACKUP_S3_ENDPOINT=https://.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 diff --git a/CLAUDE.md b/CLAUDE.md index fa85a92..5887b1c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -79,10 +79,9 @@ homepage as zero characters of text. `vite-plugin-seo.js` fixes that at build ti - Generates `sitemap.xml` and `llms.txt` from the same page list, so they cannot drift. Do not add a static `public/sitemap.xml` back. -When editing pricing anywhere, edit `seo/data.js` too. Nothing on the site should -say "OpenShorts is free" without naming the Cloud price in the same breath: both -are true of different editions and quoting only the first one is what makes AI -answers describe the paid product as free. +When editing pricing anywhere, edit `seo/data.js` too. OpenShorts has a single +self-hosted edition: free and open source under MIT. Do not reintroduce a hosted +or paid tier into the copy. ### Free tools (/tools) and SEO attribution @@ -163,17 +162,6 @@ LLM it logs one line and keeps the transcript hook. `HOOK_GROUNDING=0` disables it. The detail prompt itself now carries the rule "about this moment, not the video", which is the cheap half of the same fix. -### Sign-up survey (`cloud/onboarding.py`, `OnboardingSurvey.jsx`) - -`signup_attribution` says which page a user came from, not why. Accounts -younger than 7 days get one skippable screen before the clip tutorial (never -over a running job): what they want to make (multi-select: clip long videos -into shorts, publish to my socials, thumbnails...), how they heard of us, and who they are. -Closed lists mirrored in the JSX (a test checks), stored in -`onboarding_surveys` (user-owned; a skip is a row too, so it is asked once), -and tracked as `SignupSurveyAnswered` with one `goal_` prop per goal so -OpenPanel can break conversion down by what people came for. - ### How many clips a job returns (`clip_selection.py`) The count is not a setting, it is derived, and every stage of the derivation @@ -381,7 +369,7 @@ vars. Because the clip file lives on the app server, the backend reads it and uploads the bytes to Postiz (`POST /upload`, multipart), then references the returned `{id, path}` in `POST /posts`. Provider settings (`tiktok`, `instagram`, `youtube`) are built server-side from the clip title and caption. -Auth is the raw key, no `Bearer`. The old Upload-Post integration is gone. +Auth is the raw key, no `Bearer`. ### Webhooks @@ -428,9 +416,6 @@ checked by eye, audio identical): - **Silero VAD on one CPU thread** (`vad_load_kwargs`): on CUDA it ran one 32 ms chunk per launch and was most of the transcription's wall time. - **Blur at quarter size** (`ffmpeg_utils.blurred_backdrop`). -- **Watermark as a served copy** (`main.mark_delivery`, see the section - on the free plan's watermark): one NVENC pass per free clip, after - captions. It used to ride the reframe encode, which made it permanent. - **hooked_ + subtitled_ from one ffmpeg** (`hooks.add_hook_to_video(also=)`): the editor still needs both files (re-caption walks back to hooked_, hook replace to the canonical), so nothing is skipped, only one decode. @@ -475,14 +460,13 @@ Failures the user should never see (`app.run_job_wrapper`): the child is killed and the manifest + reservation are kept, so the next instance resumes it. A manifest next to a metadata file means "stopped mid-render" and is resumed, not recovered as completed. -- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued; - the dashboard shows it with a "paid plans skip the line" upsell (paid plans - do dispatch first: `PLAN_PRIORITY`). +- `/api/status` returns `queue: {position, ahead, eta_seconds}` while queued, + which the dashboard shows as a queue position and ETA. -### Paid proxy accounting (`cloud/proxy_ledger.py`) +### Download proxy routing and accounting (`yt_clients.py`, `metering.py`) Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB), -and the duration probe (`cloud/metering.probe_url_minutes`) follows the same +and the duration probe (`metering.probe_url_minutes`) follows the same order, with one extra free step before any per-GB attempt: the fallback clients through a static (`fallback-static`). **The client list is explicit and shared** (`yt_clients.py`: `default,mweb` + the bgutil PO token @@ -523,11 +507,8 @@ IP problem and escalated to the per-GB proxy, which carries the same cookies and fails identically, while the download recovered for free on the same static. `main.py` prints `PROXY_ROUTE=` 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 diff --git a/Dockerfile b/Dockerfile index 80b05b1..a9c9a89 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/alembic.ini b/alembic.ini deleted file mode 100644 index 6b8c0ee..0000000 --- a/alembic.ini +++ /dev/null @@ -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 diff --git a/alembic/env.py b/alembic/env.py deleted file mode 100644 index d41af74..0000000 --- a/alembic/env.py +++ /dev/null @@ -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()) diff --git a/alembic/script.py.mako b/alembic/script.py.mako deleted file mode 100644 index 9dab8a1..0000000 --- a/alembic/script.py.mako +++ /dev/null @@ -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"} diff --git a/app.py b/app.py index 1c079f3..f06f479 100644 --- a/app.py +++ b/app.py @@ -8,11 +8,8 @@ import threading import json import shutil import glob -import hashlib -import hmac import time import zipfile -import math import itertools import functools import asyncio @@ -69,10 +66,10 @@ QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), # Server credentials the pipeline subprocesses (main.py, quality_probe.py) never # read: main.py and everything it imports use GEMINI_API_KEY / LLM_* / the -# proxies / YOUTUBE_COOKIES and nothing from cloud/. A child that runs yt-dlp -# and ffmpeg on user-supplied URLs and files has no business holding the -# Stripe key, the JWT signing secret or the database password; one exploit -# in that stack would otherwise hand over all of them. +# proxies / YOUTUBE_COOKIES. A child that runs yt-dlp and ffmpeg on +# user-supplied URLs and files has no business holding the Stripe key, the JWT +# signing secret or the database password; one exploit in that stack would +# otherwise hand over all of them. CHILD_ENV_DENYLIST = frozenset({ "DATABASE_URL", "POSTGRES_PASSWORD", "JWT_SECRET", "STRIPE_SECRET_KEY", "STRIPE_WEBHOOK_SECRET", @@ -114,18 +111,11 @@ for _stream in (sys.stdout, sys.stderr): except Exception: pass -# ---- Cloud billing (paid / managed-keys) integration -------------------------- -# All paid-mode code lives in the optional `cloud/` package and is imported ONLY -# when BILLING_ENABLED is set. With the flag off, the app behaves exactly as the -# self-hosted BYOK app does today (no extra dependencies required). -BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", "yes") - # Job/file retention (issue #46). Self-host defaults to 24h: the 1h sweep kept # deleting finished projects under users who never touched their env, and the -# OUTPUT_MAX_GB / UPLOADS_MAX_GB caps below already bound the disk. Cloud keeps -# the tight default because clips are archived to R2 as soon as a job finishes. +# OUTPUT_MAX_GB / UPLOADS_MAX_GB caps below already bound the disk. JOB_RETENTION_SECONDS = int( - os.environ.get("JOB_RETENTION_SECONDS", "3600" if BILLING_ENABLED else "86400") + os.environ.get("JOB_RETENTION_SECONDS", "86400") ) # The retained download of a URL job (--keep-original) is the one artifact that # is a full copy of someone else's video rather than something we made, so it @@ -138,43 +128,16 @@ JOB_RETENTION_SECONDS = int( SOURCE_RETENTION_SECONDS = int( os.environ.get("SOURCE_RETENTION_SECONDS", str(JOB_RETENTION_SECONDS)) ) -# Force full pipeline logs to the client even under billing (local debugging). -DEBUG_LOGS = os.environ.get("DEBUG_LOGS", "").lower() in ("1", "true", "yes") - -if BILLING_ENABLED: - import cloud - from cloud import managed_keys, metering as _metering, config as _cloud_config, alerts as _alerts - from cloud.auth import get_current_user_optional -else: - cloud = None - managed_keys = None - _metering = None - _cloud_config = None - _alerts = None - - async def get_current_user_optional(request: Request): - # No-op dependency in self-host mode: every request is anonymous / BYOK. - return None async def _user_from_request(request: Request): - """Load the authenticated cloud user (or None). Cheap indexed lookup.""" - return await get_current_user_optional(request) + """Self-host: every request is anonymous / BYOK. There is no user account.""" + return None async def resolve_gemini(request: Request) -> Optional[str]: - """Resolve the Gemini API key for a request. - - Cloud (hosted) is PAID-ONLY: there is no BYOK for the core pipeline, so the - ``X-Gemini-Key`` header is ignored — an entitled user (active plan or trial) - gets the managed server key, everyone else gets ``None`` (→ 402, start trial). - Self-host keeps BYOK: header wins, else the env fallback. - """ - if BILLING_ENABLED: - user = await _user_from_request(request) - if managed_keys.has_active_entitlement(user): - return managed_keys.gemini_key() - return None + """Resolve the Gemini API key for a request: the ``X-Gemini-Key`` header + wins, else the env fallback. This fork is BYOK / self-host only.""" header = request.headers.get("X-Gemini-Key") if header: return header @@ -200,327 +163,36 @@ def postiz_http_error(exc: postiz.PostizError) -> HTTPException: def gemini_missing_error(): - """The right 4xx when no Gemini key could be resolved. - - 402 for a signed-in-but-not-entitled cloud user (needs a plan); 400 otherwise - (BYOK header simply missing). - """ - if BILLING_ENABLED: - return HTTPException(status_code=402, detail={ - "error": "no_plan", - "message": "This action needs an active plan. Choose a plan or add your own API key.", - }) + """The 4xx when no Gemini key could be resolved: the BYOK header is missing.""" return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") -# Probe rate limiter. In-memory, resets on restart by design — the hard monthly -# quota lives in the metering ledger; this only stops someone hammering the -# proxy with metadata probes. -_probe_times: dict = {} # user_id -> [monotonic timestamps] -PROBES_PER_HOUR = 15 +async def reserve_process_minutes(*a, **k): + """Self-host shim: BYOK requests don't consume managed minutes. -# Out-of-minutes upsell email: at most one per user per day (a client may -# retry the same 402 many times). -_last_quota_email: dict = {} -_QUOTA_EMAIL_COOLDOWN = 24 * 3600 + Returns the same tuple the metering path did: (user_id, priority, + reservation_id, plan, partial).""" + return None, 2, None, None, None -def _maybe_send_quota_email(user): - if user is None or user.plan != "free" or not user.email: - return - now = time.monotonic() - last = _last_quota_email.get(str(user.id)) - if last is not None and now - last < _QUOTA_EMAIL_COOLDOWN: - return - _last_quota_email[str(user.id)] = now - from cloud.emails import send_out_of_minutes_email - upgrade_url = f"{_cloud_config.settings.frontend_url}/#/pricing" - asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url, user.id)) +async def reserve_managed_action(*a, **k): + """Self-host shim: nothing is metered.""" + return None -def _check_probe_rate(user_id): - now = time.monotonic() - times = _probe_times.setdefault(str(user_id), []) - times[:] = [t for t in times if now - t < 3600] - if len(times) >= PROBES_PER_HOUR: - raise HTTPException(status_code=429, - detail="Too many requests this hour. Please slow down.") - times.append(now) - - -def partial_offer(minutes_required: float, minutes_remaining: float) -> int: - """Minutes of the source we can offer to clip instead of a 402, or 0. - - The offer is the caller's whole remaining balance, floored to full minutes - (the reservation is in whole minutes), and only when it is both worth - clipping (``PARTIAL_MIN_MINUTES``) and actually shorter than the source. - """ - from cloud import config as _cfg # plain constants; importable with billing off - offer = int(math.floor(max(0.0, float(minutes_remaining or 0)))) - if offer < _cfg.PARTIAL_MIN_MINUTES or offer >= minutes_required: - return 0 - return offer - - -def plan_partial_minutes(minutes_required: int, minutes_remaining: float, max_minutes): - """How many minutes to reserve for a source of ``minutes_required``. - - Returns ``(reserve, partial)``: ``partial`` is None for a normal whole-video - job, or ``{"processed_minutes", "total_minutes"}`` when the caller asked - (``max_minutes``) to clip only the first part. The slice is capped by the - balance as well as by the request, so a client cannot name a bigger cut - than it can pay for; when the slice would be too small the request falls - through to the ordinary quota check (and its 402). - """ - if max_minutes is None: - return minutes_required, None - try: - asked = float(max_minutes) - except (TypeError, ValueError): - return minutes_required, None - from cloud import config as _cfg - cap = int(math.floor(min(asked, max(0.0, float(minutes_remaining or 0))))) - if minutes_required <= cap or cap < _cfg.PARTIAL_MIN_MINUTES: - return minutes_required, None - return cap, {"processed_minutes": cap, "total_minutes": minutes_required} - - -def free_overflow(plan, minutes_required, minutes_remaining, max_minutes, processed_before): - """What a free account gets for a source longer than its balance. - - Returns ``(grant, max_minutes)``: - - * ``grant`` is the whole (floored) balance when this is the account's first - video and it fits ``FIRST_VIDEO_MAX_MINUTES``: the video is clipped whole - and only the balance is charged, so it lands at zero. - * otherwise ``max_minutes`` becomes the balance, so the job clips the first - N minutes (``plan_partial_minutes``) instead of answering with the wall. - - Anything else (a paid plan, a source that fits, a client that already named - its own cut) passes through untouched. - """ - from cloud import config as _cfg - remaining = max(0.0, float(minutes_remaining or 0)) - if plan != "free" or max_minutes is not None or minutes_required <= remaining: - return None, max_minutes - if (not processed_before and remaining >= 1 - and minutes_required <= _cfg.FIRST_VIDEO_MAX_MINUTES): - return int(math.floor(remaining)), None - return None, remaining - - -async def reserve_process_minutes(request, url, input_path, job_id, max_minutes=None): - """Meter a managed /api/process request. - - Returns (user_id, priority, reservation_id, plan, partial). - - ``partial`` is None unless the caller asked (``max_minutes``) to clip only - the first part of a source its balance cannot cover whole; then it is the - ``plan_partial_minutes`` dict and only that many minutes are reserved. - - BYOK / self-host requests don't consume minutes (priority 2, no reservation). - For a managed (entitled, no BYOK header) request this probes the input - duration, enforces the per-user concurrent-job limit, and reserves minutes — - raising 402 (quota) or 429 (too many jobs) as needed. - - NOTE: in cloud mode ``resolve_gemini`` ignores ``X-Gemini-Key`` (paid-only, - no BYOK), so we must NOT skip metering just because that header is present — - otherwise a client could send a dummy header and run unlimited managed jobs - on the operator's key for free. Only skip metering when billing is off. - """ - if not BILLING_ENABLED: - return None, 2, None, None, None - user = await _user_from_request(request) - if not managed_keys.has_active_entitlement(user): - return None, 2, None, None, None # shouldn't happen (resolve_gemini would have 402'd) - - priority = _cloud_config.PLAN_PRIORITY.get(user.plan, 1) - - # Per-user simultaneous job cap. - limit = _cloud_config.PLAN_JOB_LIMIT.get(user.plan, 2) - active = sum(1 for j in jobs.values() - if j.get('user_id') == user.id and j.get('status') in ('queued', 'processing')) - if active >= limit: - raise HTTPException(status_code=429, - detail="You already have the maximum number of jobs running. Please wait.") - - # Out of minutes -> 402 before probing. The probe is a real yt-dlp metadata - # fetch through the download proxies, and every job costs at least one - # minute, so a user at zero can be turned away without spending bandwidth on - # a duration we are about to reject anyway (4 of 12 submissions in the - # 21-aug-2026 sample were quota 402s that had already paid for their probe). - balance = await _metering.get_balance(user.id) - if balance["remaining"] < 1: - _maybe_send_quota_email(user) - raise HTTPException(status_code=402, detail={ - "error": "quota_exceeded", - "minutes_required": 1, - "minutes_remaining": balance["remaining"], - "partial_minutes": 0, - }) - - # Probe rate limit: probing costs a (cheap) proxied metadata call. The - # 20-minute monthly quota is the real bound on free usage; there is no daily - # job cap. - _check_probe_rate(user.id) - - # Probe input duration (blocking → run in a thread). When today's paid - # traffic is over budget, the probe (and below, the job itself) runs - # without the per-GB proxy: statics or nothing. - paid_allowed = True - try: - from cloud import proxy_ledger as _pl - paid_allowed = not await _pl.budget_exceeded() - except Exception: - pass - loop = asyncio.get_event_loop() - try: - if url: - minutes = await loop.run_in_executor( - None, functools.partial(_metering.probe_url_minutes, url, - allow_paid=paid_allowed)) - else: - minutes = await loop.run_in_executor(None, _metering.probe_file_minutes, input_path) - except Exception as e: - from yt_clients import NotASingleVideo - if isinstance(e, NotASingleVideo): - raise HTTPException(status_code=400, detail=( - f"{e} Paste the link of one video (youtube.com/watch?v=... " - "or youtu.be/...).")) - raise HTTPException(status_code=400, - detail="Could not determine the video duration. Try a different source.") - finally: - # A probe that had to reach the paid proxy leaves an event behind; - # record it (DB row + Telegram) whether or not the probe succeeded. - try: - from cloud import proxy_ledger as _pl - await _pl.drain_probe_events() - except Exception: - pass - minutes = max(1, math.ceil(minutes)) - # The probe already learned whether this video is bot-checked on every - # static IP; the download skips those attempts then (DOWNLOAD_SKIP_STATICS). - request.state.skip_statics = bool(url) and _metering.pop_statics_bot_checked(url) - - # Free account past its balance: the first video (up to - # FIRST_VIDEO_MAX_MINUTES) is clipped whole for the balance; any other is - # clipped to the first N minutes. Neither sees the wall. - grant = None - ip_hash = "" - if balance.get("plan") == "free" and minutes > balance["remaining"] and max_minutes is None: - processed_before = await _metering.has_processed_before(user.id) - if not processed_before: - # One whole first video per network (FIRST_VIDEO_IP_WINDOW_DAYS), - # so a stack of Google accounts from one IP gets one, not many. - ip_hash = _metering.ip_fingerprint(request.client.host if request.client else "") - if await _metering.ip_had_first_video(ip_hash): - processed_before = True - grant, max_minutes = free_overflow("free", minutes, balance["remaining"], - max_minutes, processed_before) - - # A source longer than the balance can be clipped in part instead of - # refused: the wall offers "the first N minutes" (``partial_minutes`` in - # the 402 below) and the client resubmits with ``max_minutes``. - if grant is not None: - reserve, partial = grant, None - else: - reserve, partial = plan_partial_minutes(minutes, balance["remaining"], max_minutes) - try: - reservation_id = await _metering.reserve_minutes(user.id, reserve, job_id) - # Read by process_endpoint for the download's safety cut - # (SOURCE_CAP_MINUTES); kept off the return tuple on purpose. A granted - # first video is processed whole, so its cap is the probed length. - request.state.reserved_minutes = minutes if grant is not None else reserve - request.state.first_video = grant is not None - if grant is not None: - try: - await _metering.record_first_video(ip_hash, job_id) - except Exception as e: # the grant stands; only the IP memory is lost - print(f"⚠️ Could not record first-video grant: {e}") - except _metering.QuotaExceeded as e: - _maybe_send_quota_email(user) - raise HTTPException(status_code=402, detail={ - "error": "quota_exceeded", - "minutes_required": e.required, - "minutes_remaining": e.remaining, - "partial_minutes": partial_offer(e.required, e.remaining), - }) - - return user.id, priority, reservation_id, user.plan, partial - - -async def reserve_managed_action(request, minutes, job_id, job_type): - """Reserve quota for a synchronous managed action (e.g. thumbnail image gen). - - Returns a reservation_id to commit/release around the work, or None for - BYOK / self-host. Raises 402 when the user is out of minutes. - """ - if not BILLING_ENABLED: - return None - if minutes <= 0: - # Free action (e.g. burning captions). Skip the ledger entirely rather - # than writing a 0-minute row on every call — the endpoint's own - # entitlement gate is what bounds it. - return None - user = await _user_from_request(request) - if not managed_keys.has_active_entitlement(user): - return None # BYOK header path (self-host) — not metered - try: - return await _metering.reserve_minutes(user.id, minutes, job_id, job_type) - except _metering.QuotaExceeded as e: - _maybe_send_quota_email(user) - raise HTTPException(status_code=402, detail={ - "error": "quota_exceeded", - "minutes_required": e.required, - "minutes_remaining": e.remaining, - }) - - -async def require_managed_entitlement(request): - """Gate a managed compute endpoint that doesn't resolve a Gemini key itself. - - Some endpoints (subtitle/hook FFmpeg re-encodes, render proxy, the thumbnail - upload that kicks off a YouTube download + Whisper) do expensive server work - without ever calling ``resolve_gemini``, so nothing was stopping an anonymous - or non-entitled caller from driving unbounded compute in cloud mode. In cloud - mode this rejects them with 402; it's a no-op for self-host (BILLING off). - """ - if not BILLING_ENABLED: - return None - user = await _user_from_request(request) - if not managed_keys.has_active_entitlement(user): - raise gemini_missing_error() - return user +async def require_managed_entitlement(request, *a, **k): + """Self-host shim: every request is allowed.""" + return None async def _owner_id(request): - """The authenticated cloud user's id to stamp on a new job/session, or None - for self-host / BYOK / anonymous (BILLING off → nothing to scope).""" - if not BILLING_ENABLED: - return None - user = await _user_from_request(request) - return user.id if user else None + """Self-host shim: there is no account to scope a job to.""" + return None async def _assert_job_owner(request, record): - """Cloud multi-tenant guard: reject unless the caller owns this in-memory - job/session record. - - No-op for self-host (BILLING off) and for records with no owner stamped - (BYOK / self-host jobs never set ``user_id``). Returns 404 rather than 403 so - a non-owner can't even confirm the id exists. UUID ids already make these - stores hard to enumerate; this closes the gap for a shared/leaked id. - """ - if not BILLING_ENABLED: - return - owner = record.get("user_id") if isinstance(record, dict) else None - if owner is None: - return - user = await _user_from_request(request) - # Compare as strings: live jobs store a uuid.UUID, but jobs recovered from - # the .owner sidecar store its string form — UUID != str is always True. - if user is None or str(user.id) != str(owner): - raise HTTPException(status_code=404, detail="Not found") + """Self-host shim: single-user app, every job belongs to the caller.""" + return # Application State # PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first: @@ -757,34 +429,12 @@ def _strip_burned_hook(output_dir, filename): async def _deliver(request, job_id, filename): - """The name to serve for a freshly derived clip file: the file itself, or - on the free plan its ``wm_`` copy (``main.mark_delivery``). - - Decided from the caller's plan right now, not from the job's flag: the - flag is lost on a restart/restore, and a user who upgraded mid-session - must get clean files from their next edit on. Self-host never marks.""" - if not BILLING_ENABLED: - return filename - user = await _user_from_request(request) - if user is None or user.plan != "free": - return filename - output_dir = os.path.join(OUTPUT_DIR, job_id) - # Only jobs the pipeline rendered under this scheme (marker file). A job - # from before it has the mark burned into its canonical, so every - # derivative already carries one and a copy would stack a second. - if not watermarked.job_is_marked(output_dir): - return filename - import main as _main - marked = await asyncio.get_event_loop().run_in_executor( - None, _main.mark_delivery, os.path.join(output_dir, filename)) - return os.path.basename(marked) + """Self-host shim: clips are always served clean (no watermark).""" + return filename def _media_guard(path: str) -> bool: - """``/videos`` allowlist: deliverable types only (media_auth), and on a - job rendered for the free plan never the clean twin of a served clip. - The twins exist so an upgrade can re-point at them, not for stripping - ``wm_`` off a URL.""" + """``/videos`` allowlist: deliverable types only (media_auth).""" if not media_auth.is_servable(path): return False job_id, _, filename = path.replace("\\", "/").strip("/").partition("/") @@ -793,43 +443,6 @@ def _media_guard(path: str) -> bool: return not watermarked.job_is_marked(os.path.join(OUTPUT_DIR, job_id)) -def _unmark_local_job(job_id, clip_index, clean_filename): - """After an upgrade: point the working copy of a clip at its clean twin. - - Called by cloud/videos.unmark_user_library for every clip it re-pointed - in R2, so a dashboard still open on the job polls clean URLs from the - in-memory result and a later restore/recovery reads them from the - metadata. The marked file and the marker go, so the /videos guard opens - the twins again.""" - job_dir = os.path.join(OUTPUT_DIR, job_id) - url = f"/videos/{job_id}/{clean_filename}" - job = jobs.get(job_id) - mem_clips = ((job or {}).get('result') or {}).get('clips') or [] - if clip_index < len(mem_clips): - mem_clips[clip_index]['video_url'] = url - ready = (job or {}).get('ready_files') - if isinstance(ready, dict) and clip_index in ready: - ready[clip_index] = clean_filename - for meta_path in glob.glob(os.path.join(job_dir, "*_metadata.json")): - try: - with open(meta_path, 'r') as f: - data = json.load(f) - shorts = data.get('shorts', []) - if clip_index < len(shorts): - shorts[clip_index]['video_url'] = url - with open(meta_path, 'w') as f: - json.dump(data, f, indent=4) - except Exception as e: - print(f"⚠️ Could not unmark metadata of {job_id}: {e}") - watermarked.unmark_job(job_dir) - marked_path = os.path.join(job_dir, watermarked.marked_name(clean_filename)) - if os.path.exists(marked_path): - try: - os.remove(marked_path) - except OSError: - pass - - def _reapply_captions(job_id, clip_index, video_path): """Re-burn the default captions onto a freshly derived file. @@ -1210,7 +823,7 @@ def _install_drain_signal_handler(): print(f"⚠️ Drain-on-SIGTERM unavailable ({e}); jobs will resume on restart instead.") -def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, watermark, +def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, webhook_url=None, webhook_secret=None, base_url=None, partial=None, source_cap_minutes=None, skip_statics=False): try: @@ -1220,7 +833,7 @@ def _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, water "cmd": cmd, "priority": priority, "user_id": None if user_id is None else str(user_id), "reservation_id": reservation_id, - "watermark": bool(watermark), "attempts": 0, + "attempts": 0, # The caller's webhook must survive a redeploy: a pipeline that # relies on the callback would otherwise hang forever on a job # that resumed fine. The secret is the caller's own HMAC value, @@ -1308,24 +921,9 @@ def _resume_interrupted_jobs() -> set: keep_reservations.discard(str(reservation_id)) # let the sweep refund it continue - # Rebuild env from scratch — the manifest holds no secrets. Managed - # (cloud) jobs get the server key; self-host falls back to its env key. + # Rebuild env from scratch — the manifest holds no secrets. Self-host + # uses its own env GEMINI_API_KEY (already present via child_env). env = child_env() - try: - from cloud import proxy_ledger as _pl - if BILLING_ENABLED and _pl.budget_exceeded_sync(): - env.pop("PROXY_URL", None) # daily paid-proxy budget hit - except Exception: - pass - if BILLING_ENABLED and user_id is not None: - try: - env["GEMINI_API_KEY"] = managed_keys.gemini_key() - except Exception: - pass - if m.get("watermark"): - env["WATERMARK"] = "1" - else: - env.pop("WATERMARK", None) partial = m.get("partial") if partial and partial.get("processed_minutes"): env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"]) @@ -1355,7 +953,6 @@ def _resume_interrupted_jobs() -> set: 'output_dir': job_path, 'user_id': None if user_id is None else user_id, 'reservation_id': reservation_id, - 'watermark': bool(m.get("watermark")), 'partial': partial or None, 'webhook_url': m.get("webhook_url"), 'webhook_secret': m.get("webhook_secret"), @@ -1614,53 +1211,6 @@ async def process_queue(): print(f"❌ Queue dispatch error: {e}") await asyncio.sleep(1) -# Monthly proxy bandwidth counter (in-memory; an alert threshold, not a bill — -# losing it on a deploy just means the alert re-arms from 0 mid-month). -_proxy_month = {"month": None, "bytes": 0, "alerted": False} -PROXY_ALERT_GB = 100 - - -def _job_source_url(job) -> Optional[str]: - """The ``-u`` argument of the job's main.py command, if it was a URL job.""" - cmd = list((job or {}).get('cmd') or []) - # The command is ``python -u main.py -u ``: skip past the script - # name first or the interpreter's own ``-u`` flag is what gets matched. - start = next((i + 1 for i, a in enumerate(cmd) if str(a).endswith('main.py')), 0) - for i in range(start, len(cmd) - 1): - if cmd[i] in ('-u', '--url'): - return cmd[i + 1] - return None - - -async def _track_proxy_usage(job_id): - job = jobs.get(job_id) or {} - # Durable trail + Telegram page whenever the per-GB proxy carried bytes - # (cloud mode only: self-host has no DB and pays nobody per GB). - if BILLING_ENABLED and job.get('proxy_route'): - try: - from cloud import proxy_ledger as _pl - await _pl.record_download(job_id, job.get('proxy_route'), _job_source_url(job)) - except Exception as e: - print(f"⚠️ proxy ledger failed for {job_id}: {e}") - nbytes = job.get('proxy_bytes') or 0 - if not nbytes: - return - month = datetime.now(timezone.utc).strftime("%Y-%m") - if _proxy_month["month"] != month: - _proxy_month.update(month=month, bytes=0, alerted=False) - _proxy_month["bytes"] += nbytes - gb = _proxy_month["bytes"] / 1e9 - if gb >= PROXY_ALERT_GB and not _proxy_month["alerted"] and _alerts: - _proxy_month["alerted"] = True - try: - await _alerts.send_admin_alert( - "Proxy bandwidth threshold", - f"Managed downloads have used {gb:.1f} GB of proxy bandwidth in {month} " - f"(threshold {PROXY_ALERT_GB} GB). Review free-plan usage.", - ) - except Exception as e: - print(f"⚠️ Proxy alert failed: {e}") - async def run_job_wrapper(job_id): """Wrapper to run job and release semaphore""" @@ -1703,21 +1253,8 @@ async def run_job_wrapper(job_id): # state, so drop the resume manifest. It only survives if the container # was killed mid-run, which is exactly when we want to resume. _clear_resume_manifest(job_id) - # Settle the minute reservation (managed jobs only): commit on success, - # release otherwise so the minutes go back to the user. - await _settle_reservation(job_id, job) - # Archive the completed clips to the user's durable R2 library (history). - await _archive_managed_job(job_id) - # Fire the caller's webhook (after archive, so durable links exist). + # Fire the caller's webhook (self-host has no R2 archive step). await _notify_job_webhook(job_id) - # Operational alerting for managed jobs (proxy out of credits / failures). - await _record_job_alert(job_id) - # Accumulate proxy bandwidth for the monthly cost alert. - await _track_proxy_usage(job_id) - # Tell the owner their clips are ready (managed jobs, once per job). - await _notify_clips_ready(job_id) - # Telegram pulse for high-signal activity (first clip / paid user). - await _notify_clip_activity(job_id) # Always release semaphore and mark queue task done _running_jobs.discard(job_id) concurrency_semaphore.release() @@ -1798,104 +1335,6 @@ def _schedule_auto_retry(job_id, job): asyncio.create_task(_later()) -async def _archive_managed_job(job_id): - if not BILLING_ENABLED: - return - job = jobs.get(job_id) or {} - if not job.get('user_id') or job.get('status') != 'completed': - return - clips = (job.get('result') or {}).get('clips') or [] - if not clips: - return - try: - await cloud.videos.archive_job(job['user_id'], job_id, clips, job['output_dir']) - except Exception as e: - print(f"⚠️ R2 archive error for {job_id}: {e}") - - -def _archive_clip_edit_bg(job_id: str, clip_index: int, filename: str): - """Fire-and-forget R2 re-archive of an edited clip (managed jobs only). - - Keeps the user's durable library (history/projects) pointing at the current - version of each clip without blocking the edit response.""" - if not BILLING_ENABLED: - return - user_id = (jobs.get(job_id) or {}).get('user_id') - if not user_id: - return - output_dir = os.path.join(OUTPUT_DIR, job_id) - - async def _run(): - try: - await cloud.videos.archive_clip_edit(user_id, job_id, clip_index, output_dir, filename) - except Exception as e: - print(f"⚠️ R2 edit archive error for {job_id}: {e}") - - asyncio.create_task(_run()) - - -async def _notify_clips_ready(job_id): - """Email the owner when their clips finish — processing takes minutes, so - this lets them close the tab. Once per job (email_sent flag).""" - if not BILLING_ENABLED: - return - job = jobs.get(job_id) or {} - if not job.get('user_id') or job.get('status') != 'completed' or job.get('email_sent'): - return - clips = (job.get('result') or {}).get('clips') or [] - if not clips: - return - job['email_sent'] = True - try: - from cloud.database import session as cloud_session - from cloud.models import User - from cloud.emails import send_clips_ready_email - async with cloud_session() as s: - user = await s.get(User, job['user_id']) - if not user or not user.email: - return - title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "Your video" - # #app opens the app itself. The bare frontend URL showed the marketing - # landing to anyone whose browser had not already set the skip flag, - # which is the wrong page for someone clicking "View my clips". - await send_clips_ready_email(user.email, title, len(clips), - f"{_cloud_config.settings.frontend_url}/#app") - except Exception as e: - print(f"⚠️ Clips-ready email error for {job_id}: {e}") - - -async def _notify_clip_activity(job_id): - """Telegram pulse when a PAID user's clips are created. Free-tier activity - (including first clips) is deliberately silent: at current signup volume it - drowned the ops channel without being actionable. - Telegram-only (best effort, no email).""" - if not BILLING_ENABLED: - return - job = jobs.get(job_id) or {} - if not job.get('user_id') or job.get('status') != 'completed': - return - clips = (job.get('result') or {}).get('clips') or [] - if not clips: - return - try: - from cloud.database import session as cloud_session - from cloud.models import User - from cloud import metering - async with cloud_session() as s: - user = await s.get(User, job['user_id']) - if not user: - return - sub = await metering._active_subscription(s, user.id) - if sub is None: - return - title = clips[0].get('video_title_for_youtube_short') or clips[0].get('title') or "video" - n = len(clips) - await _alerts.send_telegram( - f"🎬 Clips created\n{user.email} ({sub.plan}) — “{title}” ({n} clip{'s' if n != 1 else ''})") - except Exception as e: - print(f"⚠️ Clip-activity notify error for {job_id}: {e}") - - # Markers that identify a line as an actual error rather than progress noise. # "Error:" (capital E) catches raised exception lines — RuntimeError:, # DownloadError:, GeminiBlockedError: — which "ERROR:" alone missed, leaving @@ -1935,60 +1374,6 @@ def _job_error_text(logs) -> str: return " ".join(hits[-6:]) -async def _record_job_alert(job_id): - if not BILLING_ENABLED: - return - job = jobs.get(job_id) or {} - if not job.get('user_id'): - return # only track managed jobs - ok = job.get('status') == 'completed' - err = "" if ok else _job_error_text(job.get('logs', [])) - try: - await _alerts.record_job_outcome(ok, err) - except Exception as e: - print(f"⚠️ Alert recording error for {job_id}: {e}") - await _track_job_outcome(job, ok, err) - - -async def _track_job_outcome(job, ok, err): - """Report the job to OpenPanel, with the user's job index. - - The index is what makes the retention question answerable: on 26-jul-2026, - 491 of 564 users who ever processed a video did it exactly once. Counting - distinct users at index 1 versus index >= 2 measures whether the clip - quality work moved that, which nothing in the stack could do before. - - Client-side analytics cannot cover this: a render finishes minutes later, - often after the tab is closed, and ad-blockers eat a share of the rest. - """ - try: - from cloud import analytics as _an - from sqlalchemy import text as _sa_text - from cloud import database as _db - user_id = job.get('user_id') - job_index = None - try: - async with _db.session() as s: - job_index = (await s.execute(_sa_text( - "select count(*) from usage_ledger " - "where user_id = :uid and job_type = 'process'"), - {"uid": user_id})).scalar() - except Exception: - pass # an index we cannot read is not worth failing a job over - clips = len(((job.get('result') or {}).get('clips')) or []) - _an.track( - "ClipsDelivered" if ok else "JobFailed", - user_id=user_id, - job_index=job_index, - clips=clips if ok else None, - plan=job.get('user_plan'), - source="url" if _job_source_url(job) else "upload", - reason=(_alerts._classify_failure(err) if not ok and err else None), - ) - except Exception as e: - print(f"⚠️ Analytics error: {e}") - - # --- Job completion webhooks -------------------------------------------------- # Agents and pipelines (n8n, cron, scripts) need push, not poll: a caller # passes webhook_url on /api/process and gets one POST when the job reaches a @@ -2005,9 +1390,7 @@ def _sign_webhook(body: bytes, secret: str) -> str: async def _webhook_clip_entries(job_id, job): - """The payload's clip list: absolute URLs, plus durable R2 links when the - job was archived (a webhook consumer usually fetches later, after the - 1-hour local retention would have expired the /videos path).""" + """The payload's clip list as absolute URLs.""" base = (job.get('base_url') or os.environ.get("PUBLIC_API_URL", "")).rstrip("/") clips = (job.get('result') or {}).get('clips') or [] entries = [] @@ -2018,22 +1401,6 @@ async def _webhook_clip_entries(job_id, job): "title": clip.get('title') or clip.get('video_title_for_youtube_short'), "video_url": f"{base}{rel}" if rel.startswith("/") and base else rel, }) - if BILLING_ENABLED and job.get('user_id'): - try: - from sqlalchemy import select as _select - from cloud.database import session as cloud_session - from cloud.models import UserVideo - from cloud import storage as _storage - async with cloud_session() as s: - vids = list((await s.execute( - _select(UserVideo).where(UserVideo.job_id == job_id) - )).scalars()) - for v in vids: - if v.clip_index is not None and v.clip_index < len(entries): - entries[v.clip_index]["download_url"] = _storage.presigned_get( - v.r2_key, expires=24 * 3600) - except Exception as e: - print(f"⚠️ Webhook R2 links failed for {job_id}: {e}") return entries @@ -2086,112 +1453,12 @@ async def _notify_job_webhook(job_id): asyncio.create_task(_deliver_webhook(url, body, job.get('webhook_secret'))) -async def _settle_reservation(job_id, job=None): - if not BILLING_ENABLED: - return - job = job if job is not None else (jobs.get(job_id) or {}) - reservation_id = job.get('reservation_id') - if not reservation_id: - return - try: - if job.get('status') == 'completed': - await cloud.metering.commit_reservation(reservation_id) - else: - await cloud.metering.release_reservation(reservation_id) - except Exception as e: - print(f"⚠️ Reservation settle error for {job_id}: {e}") - -def _owned_by(record, uid: str) -> bool: - owner = record.get('user_id') if isinstance(record, dict) else None - return owner is not None and str(owner) == uid - - -def _rm_under(base_dir: str, relative: str): - """Remove a file or directory, refusing anything that escapes ``base_dir``.""" - target = _safe_under(base_dir, relative) - if not target or target == os.path.realpath(base_dir): - return - if os.path.isdir(target): - shutil.rmtree(target, ignore_errors=True) - else: - try: - os.remove(target) - except OSError: - pass - - -def _purge_local_jobs_for_user(user_id) -> int: - """Delete this user's working files and in-memory records from local disk. - - Called by cloud/account.py when an account is erased. The durable copies - live on R2 and are deleted there; these are the working files on the API's - own disk, which would otherwise sit around until the one-hour cleanup sweep - — and thumbnails not even then, because that sweep skips their directory. - - Three stores, because each records ownership differently: - - clip jobs: the ``.owner`` file every managed job writes, so jobs - recovered from disk after a restart (no in-memory record) count too; - - thumbnail sessions (``output/thumbnails/`` plus the source video in - ``uploads/``): in-memory only. - - Blocking: rmtree over gigabytes of video. Callers must run it in a thread. - """ - uid = str(user_id) - removed = 0 - - job_ids = {jid for jid, job in list(jobs.items()) if _owned_by(job, uid)} - thumbs_dir_name = os.path.basename(THUMBNAILS_DIR) - try: - entries = os.listdir(OUTPUT_DIR) - except OSError: - entries = [] - for job_id in entries: - # Never a job, and it backs a StaticFiles mount: deleting the directory - # itself 500s every /thumbnails request until the process restarts. - if job_id == thumbs_dir_name: - continue - try: - with open(os.path.join(OUTPUT_DIR, job_id, ".owner")) as f: - if f.read().strip() == uid: - job_ids.add(job_id) - except OSError: - continue - - for job_id in job_ids: - _rm_under(OUTPUT_DIR, job_id) - jobs.pop(job_id, None) - # Source uploads are named "_" (see /api/process). - for path in glob.glob(os.path.join(UPLOAD_DIR, f"{glob.escape(job_id)}_*")): - try: - os.remove(path) - except OSError: - pass - removed += 1 - - for sid, sess in list(thumbnail_sessions.items()): - if not _owned_by(sess, uid): - continue - # Generated thumbnails are served publicly at /thumbnails//... and - # nothing else ever deletes them. - _rm_under(THUMBNAILS_DIR, sid) - video_path = sess.get('video_path') - if video_path: - _rm_under(UPLOAD_DIR, os.path.basename(video_path)) - thumbnail_sessions.pop(sid, None) - removed += 1 - - if removed: - print(f"🗑️ Purged {removed} local work item(s) for erased user {uid}.") - return removed - - @asynccontextmanager async def lifespan(app: FastAPI): # Rehydrate finished jobs from disk before serving (survives restarts). _recover_jobs_from_disk() - # Re-enqueue jobs that were mid-processing when we stopped (redeploy). Their - # reservations must survive the orphan sweep so the resumed run can settle them. - _resumed_reservation_ids = _resume_interrupted_jobs() + # Re-enqueue jobs that were mid-processing when we stopped (redeploy). + _resume_interrupted_jobs() # Deploy handover: claim the marker (any older instance sees it and drains), # keep watching it in case a newer one appears, keep looking for manifests # left behind, and drain instead of dying on docker stop. @@ -2202,40 +1469,20 @@ async def lifespan(app: FastAPI): # Start worker and cleanup worker_task = asyncio.create_task(process_queue()) cleanup_task = asyncio.create_task(cleanup_jobs()) - if BILLING_ENABLED: - await cloud.setup_async(app, keep_reservation_ids=_resumed_reservation_ids) - # Account erasure lives in cloud/, which can't import app.py; hand it the - # one thing only this module can do — wipe the local working files. - cloud.account.register_local_purge(_purge_local_jobs_for_user) - # Same arrangement for the watermark: when a user upgrades, cloud/videos - # re-points their clips at the clean twins in R2 and hands us each - # one so the working copy (and an open dashboard) follows. - cloud.videos.register_local_unmark(_unmark_local_job) - # Welcome / first-clip / win-back emails (cloud/lifecycle.py). - cloud.lifecycle.start(is_active=lambda: not _draining) - # Nag on Telegram while the residential proxy is down/out of credits — - # a single job-failure alert is easy to miss and ingest stays broken - # until someone tops the balance up. - asyncio.create_task(_alerts.proxy_watch_loop()) yield # Cleanup (optional: cancel worker) app = FastAPI(lifespan=lifespan) -# Cloud mode: attach middleware + routers at import time (before the app serves). -if BILLING_ENABLED: - cloud.setup_sync(app) - # Free public tools behind the /tools SEO pages: YouTube transcript (existing # captions only, never the GPU) and the title/description/tag generator. import free_tools as _free_tools app.include_router(_free_tools.router) -# Enable CORS for frontend. Cloud mode locks this down to the configured origins; -# self-host keeps the permissive wildcard it has always used. +# Enable CORS for frontend. Self-host allows any origin (permissive wildcard). app.add_middleware( CORSMiddleware, - allow_origins=cloud.settings.allowed_origins if BILLING_ENABLED else ["*"], + allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], @@ -2245,16 +1492,12 @@ app.add_middleware( expose_headers=["Content-Length", "Content-Range", "Accept-Ranges"], ) -# Mount static files for serving videos. A miss under /videos// first -# tries to bring the job back from R2 (see restoring_static.py): the players -# of a reopened project used to 404 while the transcript requests were still -# restoring it. Late-bound lambda: the restorer is defined further down. +# Mount static files for serving videos. ``guard`` refuses non-deliverables +# (``*_metadata.json``, ``.owner``, ``.resume.json``) so they are never served. from restoring_static import RestoringStaticFiles -import media_auth app.mount("/videos", RestoringStaticFiles( directory=OUTPUT_DIR, - guard=_media_guard, - restorer=lambda job_id: _restore_for_public_path(job_id)), name="videos") + guard=_media_guard), name="videos") # Mount static files for serving thumbnails THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails") @@ -2288,21 +1531,6 @@ def _scrub_secrets(line: str) -> str: return _CREDENTIAL_URL_RE.sub(r'\1***:***@', line) -# Cloud users don't need (and shouldn't see) implementation details: the ingest -# plumbing (proxy / downloader / cookies) OR which AI model powers it, token -# usage and cost. These are dropped from the client view even when the line is -# emoji-prefixed. Never applied under DEBUG_LOGS (local dev sees everything). -_SENSITIVE_LOG_RE = re.compile( - # Ingest plumbing - r'proxy|yt[-_ ]?dlp|youtube-?dl|cookie|residential|po[_ ]?token' - r'|player_client|extractor|\bdownload|descarg' - # AI model / provider / cost / pipeline internals - r'|gemini|openai|anthropic|\bflash\b|\bmodel\b|token|thinking' - r'|\bcost\b|\$\s*[0-9]|scoring window|shortlist', - re.IGNORECASE, -) - - class _TimedLog(list): """A job's log lines plus the time each one arrived (``.times``). @@ -2325,33 +1553,12 @@ class _TimedLog(list): def _visible_logs_timed(logs): - """(lines, times) to surface to the client; see _visible_logs.""" + """(lines, times) to surface to the client. Self-host shows the full + pipeline output so people running their own instance can debug.""" times = getattr(logs, "times", None) if times is not None and len(times) != len(logs): times = None - if not BILLING_ENABLED or DEBUG_LOGS: - return list(logs), list(times) if times is not None else None - from log_view import friendly_logs_timed - pairs = friendly_logs_timed(logs, times) - return [p[0] for p in pairs], ([p[1] for p in pairs] if times is not None else None) - - -def _visible_logs(logs): - """Logs to surface to the client. - - Self-host (BILLING off) shows the full pipeline output so people running - their own instance can debug. Cloud shows a curated whitelist view - (log_view.friendly_logs): plain progress for normal users — transcription - percentage, clip counters — with no file paths, model names or pipeline - internals. - - DEBUG_LOGS=true forces the full output even under billing — for local dev - where you run in paid mode but still want the raw logs. - """ - if not BILLING_ENABLED or DEBUG_LOGS: - return logs - from log_view import friendly_logs - return friendly_logs(logs) + return list(logs), list(times) if times is not None else None def enqueue_output(out, job_id): @@ -2373,22 +1580,10 @@ def enqueue_output(out, job_id): pass continue if decoded_line.startswith("PROXY_BYTES="): - try: - if job_id in jobs: - jobs[job_id]['proxy_bytes'] = int(decoded_line.split("=", 1)[1]) - except ValueError: - pass + # Internal downloader marker: never shown to the user. continue if decoded_line.startswith("PROXY_ROUTE="): - # Which download attempt won and why the free ones failed; - # persisted at job end (cloud/proxy_ledger). Not shown to clients. - try: - from cloud import proxy_ledger as _pl - route = _pl.parse_route_line(decoded_line) - if route is not None and job_id in jobs: - jobs[job_id]['proxy_route'] = route - except Exception: - pass + # Internal downloader marker (proxy route): never shown. continue print(f"📝 [Job Output] {decoded_line}") if job_id in jobs: @@ -2488,11 +1683,9 @@ async def run_job(job_id, job_data): jobs[job_id]['status'] = 'completed' jobs[job_id]['logs'].append("Process finished successfully.") - # Self-host: silent AWS S3 backup. Cloud mode stores to R2 instead - # (see _archive_managed_job), so skip the redundant/paid AWS upload. - if not BILLING_ENABLED: - loop = asyncio.get_event_loop() - loop.run_in_executor(None, upload_job_artifacts, output_dir, job_id) + # Silent AWS S3 backup (optional; a no-op when S3 is unconfigured). + loop = asyncio.get_event_loop() + loop.run_in_executor(None, upload_job_artifacts, output_dir, job_id) # Find result JSON json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) @@ -2513,8 +1706,7 @@ async def run_job(job_id, job_data): rendered, missing = _clips_actually_rendered( job_id, output_dir, base_name, clips) if not rendered: - # Nothing to hand over: fail the job so _settle_reservation - # releases the minutes instead of committing them. + # Nothing to hand over: fail the job. jobs[job_id]['status'] = 'failed' jobs[job_id]['logs'].append( "No clips could be rendered from this video.") @@ -2559,12 +1751,12 @@ async def health_ready(): async def get_config(): return { "youtubeUrlEnabled": not DISABLE_YOUTUBE_URL, - "billingEnabled": BILLING_ENABLED, - "googleAuthEnabled": bool(BILLING_ENABLED and cloud.settings.google_auth_enabled), + # Kept for a stale dashboard build; the self-host app has no billing. + "billingEnabled": False, "jobRetentionSeconds": JOB_RETENTION_SECONDS, - # Self-host only: tells the dashboard the Gemini key is optional + # Self-host: tells the dashboard the Gemini key is optional # because the moment picker runs on an OpenAI-compatible server. - "localLlm": None if BILLING_ENABLED else llm_backend.describe(), + "localLlm": llm_backend.describe(), } async def _probe_youtube_quality(url: str) -> dict: @@ -2628,12 +1820,7 @@ async def _quality_gate(url: str, force_low: bool): async def _drop_unstarted_job(reservation_id, job_output_dir): - """Undo a submission refused after its minutes were reserved.""" - if reservation_id: - try: - await _metering.release_reservation(reservation_id) - except Exception as e: - print(f"⚠️ Could not release reservation {reservation_id}: {e}") + """Undo a submission refused after its working dir was created.""" shutil.rmtree(job_output_dir, ignore_errors=True) @@ -2705,8 +1892,6 @@ def _upload_url_base(request): async def create_upload(request: Request): """Reserve an upload slot. Body (JSON, optional): {"filename": "..."}.""" user_id = await _owner_id(request) - if BILLING_ENABLED and user_id is None: - raise HTTPException(status_code=401, detail="Sign in or use an API key to upload") try: body = await request.json() except Exception: @@ -2767,9 +1952,9 @@ async def put_upload(upload_id: str, request: Request): @app.delete("/api/uploads/{upload_id}") async def delete_upload(upload_id: str, request: Request): - """Drop a slot and its file before it expires (owner only in cloud mode).""" + """Drop a slot and its file before it expires (owner only).""" slot = pending_uploads.get(upload_id) - if not slot or (BILLING_ENABLED and slot.get("user_id") != await _owner_id(request)): + if not slot or slot.get("user_id") != await _owner_id(request): raise HTTPException(status_code=404, detail="Unknown or expired upload_id") pending_uploads.pop(upload_id, None) try: @@ -2798,7 +1983,7 @@ def _sweep_pending_uploads(now=None): def _take_pending_upload(upload_id, user_id): """The completed upload for this caller, or an HTTPException.""" slot = pending_uploads.get(upload_id) - if not slot or (BILLING_ENABLED and slot.get("user_id") != user_id): + if not slot or slot.get("user_id") != user_id: raise HTTPException(status_code=404, detail="Unknown or expired upload_id") if not slot.get("complete") or not os.path.exists(slot["path"]): raise HTTPException(status_code=409, detail="Upload not received yet: PUT the video to upload_url first") @@ -2856,7 +2041,7 @@ async def process_endpoint( max_minutes: Optional[str] = Form(None), ): api_key = await resolve_gemini(request) - if not api_key and not (llm_backend.active() and not BILLING_ENABLED): + if not api_key and not llm_backend.active(): # Self-host with an OpenAI-compatible server configured needs no # Google key for the core pipeline: the moment picker runs there and # the frame-based stages degrade on their own (layout_picker returns @@ -2864,9 +2049,6 @@ async def process_endpoint( raise gemini_missing_error() ack_flag = str(acknowledged).lower() in ("1", "true", "yes") - # May be lowered by the paid-proxy budget check in the metering block - # below; self-host never runs that block, so it must default here. - paid_allowed = True force_low = str(force_low_quality).lower() in ("1", "true", "yes") # Handle JSON body manually for URL payload @@ -2969,9 +2151,6 @@ async def process_endpoint( # probe above already gets this right. cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered env = child_env() - if not paid_allowed: - # Daily paid-proxy budget hit: this job runs on the free routes only. - env.pop("PROXY_URL", None) if api_key: env["GEMINI_API_KEY"] = api_key # Override with key from request else: @@ -2983,8 +2162,7 @@ async def process_endpoint( env.setdefault("PYTHONIOENCODING", "utf-8") # Optional layouts are per job. The renderer reads these at import time in - # the subprocess, so they must be set before Popen — same path WATERMARK - # already takes. + # the subprocess, so they must be set before Popen. chosen = layout_env(layouts) env.update(chosen) if chosen: @@ -3157,10 +2335,6 @@ async def process_endpoint( # main.py cuts the source down to this many minutes before anything # reads it, so the whole pipeline (and the editor) sees a short video. env["MAX_SOURCE_MINUTES"] = str(partial["processed_minutes"]) - if user_plan == "free": - # Free-plan clips carry a burned-in watermark (applied by the main.py - # subprocess after each clip renders). - env["WATERMARK"] = "1" # Absolute-URL base for the webhook payload: explicit env wins (the API may # sit behind a proxy whose forwarded headers we can't trust), else what the @@ -3177,29 +2351,16 @@ async def process_endpoint( 'attestation': attestation, 'user_id': user_id, 'reservation_id': reservation_id, - 'watermark': env.get("WATERMARK") == "1", 'partial': partial, 'webhook_url': webhook_url, 'webhook_secret': webhook_secret, 'base_url': api_base, - # Read by the ClipsDelivered/JobFailed analytics event (plan). 'user_plan': user_plan, } - # Persist the owner so recovered jobs keep their multi-tenant guard after a - # restart (see _recover_jobs_from_disk). - if user_id is not None: - try: - os.makedirs(job_output_dir, exist_ok=True) - with open(os.path.join(job_output_dir, ".owner"), "w") as f: - f.write(str(user_id)) - except Exception as e: - print(f"⚠️ Could not persist job owner for {job_id}: {e}") - # Resume manifest: enough to re-run this job if the container dies mid-flight # (a redeploy). No secrets — the env is rebuilt from os.environ on resume. _write_resume_manifest(job_id, cmd, priority, user_id, reservation_id, - watermark=jobs[job_id]['watermark'], webhook_url=webhook_url, webhook_secret=webhook_secret, base_url=api_base, partial=partial, source_cap_minutes=source_cap, skip_statics=skip_statics) @@ -3297,90 +2458,26 @@ def _locate_source(job_id: str): return None -# How long a signed source URL stays valid. Long enough to survive an editing -# session and a page reload, short enough that a link leaked through a log, a -# referer or a shared screenshot is dead by the time anyone tries it. -SOURCE_URL_TTL_SECONDS = int(os.environ.get("SOURCE_URL_TTL_SECONDS", "21600")) - - -def _source_signature(job_id: str, exp: int) -> str: - """HMAC tying a job id to an expiry, keyed on the app's JWT secret.""" - secret = (_cloud_config.settings.jwt_secret if BILLING_ENABLED else "") or "" - msg = f"{job_id}:{exp}".encode() - return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()[:32] - - def _job_record(job_id: str): """The in-memory job record, or what the shared disk says about it.""" return jobs.get(job_id) or _job_view_from_disk(job_id) -def _signed_source_url(job_id: str) -> str: - """The URL to hand a `