feat: durable video library on Cloudflare R2 (history + retention)

- cloud/storage.py: R2 (S3-compatible) client — upload, presigned view/download
  URLs, delete-by-prefix.
- cloud/videos.py: archive a completed managed job's clips to R2 under
  users/<uid>/<job>/, GET /api/history (private signed links), and a retention
  sweeper that deletes a user's videos 7 days after their subscription ends.
- models.py: user_videos table (created via create_all).
- app.py: archive clips to R2 on managed-job completion.
- billing.py: email the admin the moment a subscriber hits cancel.
- Frontend: History tab (library grid with per-video view + download).

R2 bucket 'openshorts-videos' + scoped API token created; end-to-end verified:
archive -> presigned GET (200) -> purge after grace -> object 404.
This commit is contained in:
juancarlos.cavero 2026-07-14 14:56:40 +02:00
parent 12d423d739
commit 0ba4fac47b
10 changed files with 346 additions and 4 deletions

View file

@ -43,6 +43,13 @@ OPENSHORTS_LOGO_URL=https://openshorts.app/logo.png
# to 720p when this is set, to control bandwidth cost. Empty = direct download.
PROXY_URL=
# Cloudflare R2 (S3-compatible) — durable storage for users' generated videos.
# Create an R2 bucket + an "Object Read & Write" API token scoped to it.
R2_ENDPOINT=https://<account_id>.r2.cloudflarestorage.com
R2_BUCKET=openshorts-videos
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
# PO-token provider for 720p/1080p YouTube (bgutil sidecar in docker-compose.cloud.yml).
# Defaults to the sidecar; only override if you run bgutil elsewhere.
BGUTIL_BASE_URL=http://bgutil:4416

17
app.py
View file

@ -314,6 +314,8 @@ async def run_job_wrapper(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)
# Archive the completed clips to the user's durable R2 library (history).
await _archive_managed_job(job_id)
# Operational alerting for managed jobs (proxy out of credits / failures).
await _record_job_alert(job_id)
# Always release semaphore and mark queue task done
@ -322,6 +324,21 @@ async def run_job_wrapper(job_id):
print(f"✅ Released slot for job: {job_id}")
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}")
async def _record_job_alert(job_id):
if not BILLING_ENABLED:
return

View file

@ -26,13 +26,14 @@ def setup_sync(app):
from starlette.middleware.sessions import SessionMiddleware
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
from . import auth, oauth, billing, social_profiles
from . import auth, oauth, billing, social_profiles, videos
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
app.include_router(oauth.router)
app.include_router(billing.router)
app.include_router(social_profiles.router)
app.include_router(videos.router)
async def setup_async(app):
@ -40,8 +41,9 @@ async def setup_async(app):
DB engine, orphaned-reservation cleanup and the metering sweeper live here.
"""
from . import database, metering
from . import database, metering, videos
await database.init_engine()
await metering.release_orphaned_reservations()
metering.start_sweeper()
videos.start_sweeper()
print("☁️ Cloud billing mode ENABLED (DB ready, metering active).")

View file

@ -289,14 +289,19 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime):
if row and row.last_event_at and event_created < row.last_event_at:
return
start, end = _sub_period(sub_obj)
now_canceling = bool(sub_obj.get("cancel_at_period_end"))
# Detect the moment the user hits "cancel" (False -> True).
was_canceling = bool(row.cancel_at_period_end) if row else False
just_canceled = now_canceling and not was_canceling
end_dt = _ts(end)
values = dict(
stripe_subscription_id=sub_obj["id"],
stripe_price_id=price_id,
plan=plan, interval=interval, status=sub_obj["status"],
minutes_per_period=minutes,
current_period_start=_ts(start),
current_period_end=_ts(end),
cancel_at_period_end=bool(sub_obj.get("cancel_at_period_end")),
current_period_end=end_dt,
cancel_at_period_end=now_canceling,
last_event_at=event_created,
)
if row is None:
@ -305,6 +310,17 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime):
for k, v in values.items():
setattr(row, k, v)
# Churn alert to the admin the moment a subscription is set to cancel.
if just_canceled:
from .alerts import send_admin_alert
from .config import VIDEO_RETENTION_GRACE_DAYS
await send_admin_alert(
"🔻 Subscription canceled",
f"A {plan} subscriber just canceled.\n"
f"Access continues until {end_dt:%Y-%m-%d}; their videos are then kept "
f"{VIDEO_RETENTION_GRACE_DAYS} more days before deletion.",
)
async def _set_subscription_status(sub_obj: dict, status: str, event_created: datetime):
async with database.session() as s:

View file

@ -149,6 +149,32 @@ class Settings:
def openshorts_logo_url(self) -> str:
return os.environ.get("OPENSHORTS_LOGO_URL", "https://openshorts.app/logo.png")
# Cloudflare R2 (S3-compatible) — durable video library storage
@property
def r2_endpoint(self) -> str:
return os.environ.get("R2_ENDPOINT", "")
@property
def r2_bucket(self) -> str:
return os.environ.get("R2_BUCKET", "")
@property
def r2_access_key_id(self) -> str:
return os.environ.get("R2_ACCESS_KEY_ID", "")
@property
def r2_secret_access_key(self) -> str:
return os.environ.get("R2_SECRET_ACCESS_KEY", "")
@property
def r2_configured(self) -> bool:
return bool(self.r2_endpoint and self.r2_bucket and self.r2_access_key_id
and self.r2_secret_access_key)
# Days a user's videos survive after their subscription ends (grace period).
VIDEO_RETENTION_GRACE_DAYS = 7
settings = Settings()

View file

@ -97,6 +97,19 @@ class UploadPostProfile(Base):
created_at = Column(DateTime(timezone=True), server_default=func.now())
class UserVideo(Base):
__tablename__ = "user_videos"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
job_id = Column(Text, nullable=False)
clip_index = Column(Integer, nullable=True)
r2_key = Column(Text, nullable=False)
title = Column(Text, nullable=True)
size_bytes = Column(Integer, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
class StripeEvent(Base):
__tablename__ = "stripe_events"
id = Column(Text, primary_key=True) # Stripe event.id — dedupe key

66
cloud/storage.py Normal file
View file

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

121
cloud/videos.py Normal file
View file

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

View file

@ -14,6 +14,7 @@ import TopUpModal from './components/TopUpModal';
import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate';
import AdvancedBanner from './components/AdvancedBanner';
import HistoryTab from './components/HistoryTab';
import { useAuth } from './contexts/AuthContext';
import { apiFetch, apiJson, QuotaError } from './lib/api';
import { getApiUrl } from './config';
@ -464,6 +465,16 @@ function App() {
<span className="font-medium hidden lg:block">YouTube Studio</span>
</button>
{billingEnabled && isSignedIn && (
<button
onClick={() => setActiveTab('history')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'history' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
>
<History size={20} />
<span className="font-medium hidden lg:block">History</span>
</button>
)}
{/* <button
onClick={() => setActiveTab('gallery')}
className={`w-full flex items-center gap-3 px-3 py-3 rounded-xl transition-colors ${activeTab === 'gallery' ? 'bg-primary/10 text-primary' : 'text-zinc-400 hover:text-white hover:bg-white/5'}`}
@ -951,6 +962,8 @@ function App() {
)}
{/* View: Thumbnails */}
{activeTab === 'history' && <HistoryTab />}
{activeTab === 'thumbnails' && (
<ThumbnailStudio geminiApiKey={apiKey} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} managed={isManaged} />
)}

View file

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