diff --git a/.env.cloud.example b/.env.cloud.example index ae5c54c..93fc84d 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -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://.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 diff --git a/app.py b/app.py index 3a62e1d..a42207e 100644 --- a/app.py +++ b/app.py @@ -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 diff --git a/cloud/__init__.py b/cloud/__init__.py index 13b8227..f424d9d 100644 --- a/cloud/__init__.py +++ b/cloud/__init__.py @@ -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).") diff --git a/cloud/billing.py b/cloud/billing.py index 1c81aed..3c87403 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -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: diff --git a/cloud/config.py b/cloud/config.py index 23e6112..38d8edc 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -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() diff --git a/cloud/models.py b/cloud/models.py index d265243..620d048 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -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 diff --git a/cloud/storage.py b/cloud/storage.py new file mode 100644 index 0000000..9f9536c --- /dev/null +++ b/cloud/storage.py @@ -0,0 +1,66 @@ +"""Cloudflare R2 (S3-compatible) storage for the users' durable video library. + +Layout: users///. 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 diff --git a/cloud/videos.py b/cloud/videos.py new file mode 100644 index 0000000..45e81fd --- /dev/null +++ b/cloud/videos.py @@ -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()) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index d992ffc..c736243 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -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() { YouTube Studio + {billingEnabled && isSignedIn && ( + + )} + {/*