diff --git a/app.py b/app.py index 39a08e4..f9588ae 100644 --- a/app.py +++ b/app.py @@ -1240,6 +1240,10 @@ app.add_middleware( allow_credentials=True, allow_methods=["*"], allow_headers=["*"], + # Without this the browser hides them from fetch(), so the clip download had + # no total to measure against and could not show progress. Safelisted or not, + # they only become readable to JS once they are named here. + expose_headers=["Content-Length", "Content-Range", "Accept-Ranges"], ) # Mount static files for serving videos diff --git a/cloud/config.py b/cloud/config.py index 5d65c54..99ffbd3 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -249,6 +249,25 @@ class Settings: def r2_secret_access_key(self) -> str: return os.environ.get("R2_SECRET_ACCESS_KEY", "") + @property + def r2_public_base(self) -> str: + """Base URL of a custom domain bound to the R2 bucket, e.g. + https://cdn.openshorts.app — unset means keep signing S3 URLs. + + The S3 endpoint (*.r2.cloudflarestorage.com) is not a browser-facing + endpoint: measured 22-ago-2026, a presigned GET from Chrome on a Spanish + residential line returns 503 on every attempt while the same URL with the + same headers returns 206 at 11 MB/s from a datacenter. A custom domain + serves the same objects through the normal Cloudflare edge, which both + fixes that and puts the bytes on Cloudflare's network instead of a single + long path out of Hetzner (measured to the same client: 90 KB/s). + + Objects under it are public. That matches the capability model already in + production for /videos/{job_id}/... (unauthenticated, the UUID is the + capability); anything stricter needs a Worker checking a signed token. + """ + return os.environ.get("R2_PUBLIC_BASE", "").strip().rstrip("/") + @property def r2_configured(self) -> bool: return bool(self.r2_endpoint and self.r2_bucket and self.r2_access_key_id diff --git a/cloud/storage.py b/cloud/storage.py index fb01c52..63b3dff 100644 --- a/cloud/storage.py +++ b/cloud/storage.py @@ -4,6 +4,8 @@ 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. """ +from urllib.parse import quote + import boto3 from botocore.config import Config @@ -65,6 +67,18 @@ def list_keys(prefix) -> list: 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}"' diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 1b78899..2757351 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -76,11 +76,35 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, // their position to save a few seconds of buffering is a bad trade. const [hasPlayed, setHasPlayed] = useState(false); + // A delivered clip is tens of MB, and on a slow link the old silent + // fetch-then-save took minutes with nothing on screen, which reads as a dead + // button. Stream it instead and report progress. + const [downloadPct, setDownloadPct] = useState(null); + const downloadClip = async () => { try { + setDownloadPct(0); const response = await fetch(currentVideoUrl); if (!response.ok) throw new Error('Download failed'); - const blob = await response.blob(); + const total = Number(response.headers.get('content-length')) || 0; + let blob; + // No body reader (old browser) or no length to measure against: fall + // back to the plain path rather than lose the download. + if (!response.body || !total) { + blob = await response.blob(); + } else { + const reader = response.body.getReader(); + const chunks = []; + let received = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + received += value.length; + setDownloadPct(Math.min(99, Math.round((received / total) * 100))); + } + blob = new Blob(chunks, { type: 'video/mp4' }); + } const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; @@ -93,6 +117,8 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, } catch (err) { console.error('Download error:', err); window.open(currentVideoUrl, '_blank'); + } finally { + setDownloadPct(null); } }; // Latest file that exists ON THE SERVER (blob: previews don't count). @@ -890,7 +916,8 @@ export default function ResultCard({ clip, index, jobId, durable, uploadPostKey, }} className={`${QUIET_BTN}${onEditClip ? ' col-span-2' : ''}`} > - download + + {downloadPct === null ? 'download' : `downloading ${downloadPct}%`}