Every file the pipeline and the clip editor write is now clean. On the free plan the served file is a wm_<final> copy with the mark burned in (main.mark_delivery, last step after captions; app._deliver for the editor endpoints, decided from the caller's plan), and both twins go to R2. An upgrade re-points the user's library at the clean twins from the Stripe webhook (cloud.videos.unmark_user_library): no render, no source video, and the dashboard chases the job result until no served URL carries wm_. Before, the mark rode the reframe encode, so every derivative inherited it and the upgrade modal's "upgrade to remove the watermark" was false for the clips already made. The first cancellation for "clip quality" (29-sep) was a user who paid 15 minutes after their first job and kept the mark on every download and restyle. - /videos guard refuses a marked job's clean deliverables (.marked dotfile), so the twin cannot be fetched by stripping the prefix off a URL; editor scratch files stay servable. Re-checked after an R2 restore. - Walk-backs treat wm_ as the outermost layer; _canonical_clip_file globs it. - Jobs from before this scheme (mark burned into the canonical) never get a second copy; a failed mark still serves under the wm_ name. - Watermark notice once per job when the clips land on a free account, and before the first download if skipped; tracked with source=results|download. Upsell/banner/win-back copy now promise the instant removal.
116 lines
3.8 KiB
Python
116 lines
3.8 KiB
Python
"""Cloudflare R2 (S3-compatible) storage for the users' durable video library.
|
|
|
|
Layout: users/<user_id>/<job_id>/<filename>. Presigned URLs give private,
|
|
time-limited view/download links. Delete-by-prefix wipes a user's whole library
|
|
when their subscription's grace period ends.
|
|
"""
|
|
from urllib.parse import quote
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
|
|
from .config import settings
|
|
|
|
_client = None
|
|
|
|
|
|
def client():
|
|
global _client
|
|
if _client is None:
|
|
_client = boto3.client(
|
|
"s3",
|
|
endpoint_url=settings.r2_endpoint,
|
|
aws_access_key_id=settings.r2_access_key_id,
|
|
aws_secret_access_key=settings.r2_secret_access_key,
|
|
region_name="auto",
|
|
config=Config(signature_version="s3v4", retries={"max_attempts": 3}),
|
|
)
|
|
return _client
|
|
|
|
|
|
def user_prefix(user_id) -> str:
|
|
return f"users/{user_id}/"
|
|
|
|
|
|
def job_key(user_id, job_id, filename) -> str:
|
|
return f"users/{user_id}/{job_id}/{filename}"
|
|
|
|
|
|
def upload_file(local_path, key, content_type="video/mp4"):
|
|
client().upload_file(local_path, settings.r2_bucket, key,
|
|
ExtraArgs={"ContentType": content_type})
|
|
|
|
|
|
def download_file(key, local_path):
|
|
client().download_file(settings.r2_bucket, key, local_path)
|
|
|
|
|
|
def object_size(key):
|
|
"""Size in bytes of one object, or None when it is not there."""
|
|
try:
|
|
return int(client().head_object(Bucket=settings.r2_bucket, Key=key)["ContentLength"])
|
|
except client().exceptions.ClientError as e:
|
|
code = str((e.response or {}).get("Error", {}).get("Code", ""))
|
|
if code in ("404", "NoSuchKey", "NotFound"):
|
|
return None
|
|
raise
|
|
|
|
|
|
def delete_key(key):
|
|
client().delete_object(Bucket=settings.r2_bucket, Key=key)
|
|
|
|
|
|
def list_keys(prefix) -> list:
|
|
"""List every object key under a prefix."""
|
|
c = client()
|
|
keys = []
|
|
token = None
|
|
while True:
|
|
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
|
|
if token:
|
|
kw["ContinuationToken"] = token
|
|
resp = c.list_objects_v2(**kw)
|
|
keys.extend(o["Key"] for o in resp.get("Contents", []))
|
|
if not resp.get("IsTruncated"):
|
|
break
|
|
token = resp.get("NextContinuationToken")
|
|
return keys
|
|
|
|
|
|
def presigned_get(key, expires=3600, download_name=None) -> str:
|
|
"""A URL a client can GET. Signed against the S3 endpoint by default; a plain
|
|
URL on the bucket's custom domain when R2_PUBLIC_BASE is set.
|
|
|
|
Switching here rather than at each call site on purpose: every caller hands
|
|
the result to a browser, and the S3 endpoint is the one variant browsers
|
|
cannot reliably fetch (see settings.r2_public_base). The custom domain has no
|
|
equivalent of ResponseContentDisposition, so a download keeps the object's
|
|
own name, which is already the clip filename.
|
|
"""
|
|
base = settings.r2_public_base
|
|
if base:
|
|
return f"{base}/{quote(key, safe='/')}"
|
|
params = {"Bucket": settings.r2_bucket, "Key": key}
|
|
if download_name:
|
|
params["ResponseContentDisposition"] = f'attachment; filename="{download_name}"'
|
|
return client().generate_presigned_url("get_object", Params=params, ExpiresIn=expires)
|
|
|
|
|
|
def delete_prefix(prefix) -> int:
|
|
"""Delete every object under a prefix. Returns the count deleted."""
|
|
c = client()
|
|
deleted = 0
|
|
token = None
|
|
while True:
|
|
kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000}
|
|
if token:
|
|
kw["ContinuationToken"] = token
|
|
resp = c.list_objects_v2(**kw)
|
|
objs = [{"Key": o["Key"]} for o in resp.get("Contents", [])]
|
|
if objs:
|
|
c.delete_objects(Bucket=settings.r2_bucket, Delete={"Objects": objs})
|
|
deleted += len(objs)
|
|
if not resp.get("IsTruncated"):
|
|
break
|
|
token = resp.get("NextContinuationToken")
|
|
return deleted
|