Skip to content

Open source CapCut alternative.

TypeScript

feat(site): download source media from asset cards, clips, and the library [rebuild]

David Le01bbd1030ff2
diff --git a/site/src/cut/components/GeneratedAssetMenu.tsx b/site/src/cut/components/GeneratedAssetMenu.tsx
index 2bb2bfec..7a89fbd9 100644
--- a/site/src/cut/components/GeneratedAssetMenu.tsx
+++ b/site/src/cut/components/GeneratedAssetMenu.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, type ReactNode } from "react";
-import { Clapperboard, Ellipsis, FolderPlus, Trash2 } from "lucide-react";
+import { Clapperboard, Download, Ellipsis, FolderPlus, Trash2 } from "lucide-react";
import {
AlertDialog,
AlertDialogAction,
@@ -20,6 +20,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { saveAssetToLibrary } from "@/cut/lib/library";
+import { downloadMedia } from "@/cut/lib/media";
import { useEditor } from "@/cut/lib/store";
import type { MediaAsset } from "@/cut/lib/types";
@@ -93,6 +94,12 @@ export function GeneratedAssetMenu({
>
<FolderPlus /> Add to Library
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => downloadMedia(projectId, asset)}
+ disabled={!!asset.upload}
+ >
+ <Download /> Download
+ </DropdownMenuItem>
{(after != null || onDelete) && <DropdownMenuSeparator />}
{after}
{onDelete && (
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 940fd865..62af4187 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -5,6 +5,8 @@ import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
Cloud,
+ Download,
+ Ellipsis,
Film,
FolderOpen,
FolderPlus,
@@ -18,6 +20,13 @@ import {
Upload,
} from "lucide-react";
import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { LiveElapsed } from "@/cut/components/Elapsed";
import {
AlertDialog,
@@ -46,6 +55,7 @@ import {
deleteFromLibrary,
deleteLibraryFolder,
deleteTemplate,
+ downloadLibraryAsset,
importUrlToLibrary,
libraryMediaUrl,
moveLibraryItem,
@@ -665,25 +675,31 @@ export function LibraryCard({
durationClassName={!!onUse && "transition-opacity group-hover:opacity-0"}
/>
)}
- {a.type === "video" && (
- <span className="absolute right-1.5 bottom-1.5 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">
- {formatTime(a.duration)}
- </span>
- )}
- {sizeBytes != null && (
+ {a.type !== "audio" && (a.type === "video" || sizeBytes != null) && (
+ // Length and size share one pill in the corner: on a card this narrow
+ // two of them collide. The length reads at rest, the size takes over
+ // on hover, where the + button is what the pointer is there for.
<span
className={cn(
- "absolute font-mono tabular-nums opacity-0 transition-opacity group-hover:opacity-100",
- a.type === "audio"
- ? // Clear of the play circle, matching the face's duration pill.
- "bottom-3 left-12 rounded-md bg-[#2b4e42] px-1.5 py-0.5 text-[10px] text-[#d6eddf]"
- : cn(
- "rounded-md bg-black/65 px-1.5 py-0.5 text-[10px] text-white",
- // The + button takes the corner on hover; sit beside it.
- onUse ? "bottom-2 left-9" : "bottom-1.5 left-1.5"
- )
+ "absolute right-1.5 bottom-1.5 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums",
+ a.type !== "video" && "opacity-0 transition-opacity group-hover:opacity-100"
)}
>
+ {a.type === "video" && (
+ <span className={cn(sizeBytes != null && "group-hover:hidden")}>
+ {formatTime(a.duration)}
+ </span>
+ )}
+ {sizeBytes != null && (
+ <span className={cn(a.type === "video" && "hidden group-hover:inline")}>
+ {formatBytes(sizeBytes)}
+ </span>
+ )}
+ </span>
+ )}
+ {a.type === "audio" && sizeBytes != null && (
+ // Clear of the play circle, matching the face's duration pill.
+ <span className="absolute bottom-3 left-12 rounded-md bg-[#2b4e42] px-1.5 py-0.5 font-mono text-[10px] text-[#d6eddf] tabular-nums opacity-0 transition-opacity group-hover:opacity-100">
{formatBytes(sizeBytes)}
</span>
)}
@@ -711,27 +727,34 @@ export function LibraryCard({
className={cn(
"absolute top-2 right-2 transition-opacity",
offline ? "text-muted-foreground" : "text-white/85",
- // The delete button takes this corner on hover.
- onDelete && "group-hover:opacity-0"
+ // The actions menu takes this corner on hover.
+ "group-hover:opacity-0"
)}
/>
)}
- <div className="absolute top-1.5 right-1.5 flex gap-1 opacity-0 group-hover:opacity-100">
- {onDelete && (
- <Button
- variant="ghost"
- size="icon-xs"
- aria-label="Remove from library"
- className="bg-black/40 text-white hover:bg-black/60 hover:text-white"
- onClick={(e) => {
- e.stopPropagation();
- onDelete();
- }}
- >
- <Trash2 />
- </Button>
- )}
- </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label="More actions"
+ title="More actions"
+ className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full bg-black/40 text-white opacity-0 transition-opacity group-hover:opacity-100 hover:bg-black/60 data-[state=open]:opacity-100"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Ellipsis className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44" onClick={(e) => e.stopPropagation()}>
+ <DropdownMenuItem onClick={() => downloadLibraryAsset(a)} disabled={offline}>
+ <Download /> Download
+ </DropdownMenuItem>
+ {onDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 /> Remove from library
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
<CopyNameLabel
name={a.name}
dark={a.type === "audio"}
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index ed3c3371..21eac99d 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -68,7 +68,7 @@ import {
import { activeResidency, availableResidencies, type Residency } from "@/cut/lib/residency";
import { isStylePresetTemplate } from "@/cut/lib/stylePresets";
import { retryUpload } from "@/cut/lib/importQueue";
-import { isMediaFile, revealMedia } from "@/cut/lib/media";
+import { downloadMedia, isMediaFile, revealMedia } from "@/cut/lib/media";
import { mediaUrl, TRANSITION_MAX } from "@/cut/lib/types";
import { Slider } from "@/components/ui/slider";
import { genPulseOverlay, isGenTab, useGenNotify, useGenPulse, useWatchGenTab } from "@/cut/lib/genNotify";
@@ -1096,6 +1096,12 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string
<DropdownMenuItem onClick={saveToLibrary} disabled={!!asset.upload}>
<FolderPlus /> Save to library
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => downloadMedia(projectId, asset)}
+ disabled={!!asset.upload}
+ >
+ <Download /> Download
+ </DropdownMenuItem>
{caps.revealInFinder && (
<DropdownMenuItem
onClick={() => void revealMedia(projectId, asset.fileName).catch(() => {})}
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 3816cc79..471d42a2 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -1,7 +1,7 @@
"use client";
import { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
-import { ArrowDown, ArrowDownToLine, ArrowLeft, ArrowLeftToLine, ArrowRight, ArrowRightToLine, ArrowUp, ArrowUpToLine, AudioLines, Blend, Check, Circle, Clapperboard, Copy, Diamond, Droplets, EllipsisVertical, Expand, Eye, EyeOff, FolderOpen, FolderPlus, FoldHorizontal, Fullscreen, Heart, Hexagon, Loader2, Minus, Moon, MoreHorizontal, MoveRight, Pause, Play, Scissors, SkipBack, Sparkles, Square, Star, Sticker, Sun, Target, Trash2, Triangle, Type, UnfoldHorizontal, Volume2, VolumeX, type LucideIcon } from "lucide-react";
+import { ArrowDown, ArrowDownToLine, ArrowLeft, ArrowLeftToLine, ArrowRight, ArrowRightToLine, ArrowUp, ArrowUpToLine, AudioLines, Blend, Check, Circle, Clapperboard, Copy, Diamond, Download, Droplets, EllipsisVertical, Expand, Eye, EyeOff, FolderOpen, FolderPlus, FoldHorizontal, Fullscreen, Heart, Hexagon, Loader2, Minus, Moon, MoreHorizontal, MoveRight, Pause, Play, Scissors, SkipBack, Sparkles, Square, Star, Sticker, Sun, Target, Trash2, Triangle, Type, UnfoldHorizontal, Volume2, VolumeX, type LucideIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -40,7 +40,7 @@ import { originalSettings, type ExportDoc } from "@/cut/lib/exportClient";
import { useExports } from "@/cut/lib/exportStore";
import { isDragActive, startDrag, subscribeDragActive } from "@/cut/lib/drag";
import { CLIP_GAP, startLaneMove, startLaneTrim, type LaneDrag } from "@/cut/lib/laneTracks";
-import { ensurePeaks, importImage, importStockMusic, importStockVideo, peekEdgeFrame, requestEdgeFrame, revealMedia } from "@/cut/lib/media";
+import { downloadMedia, ensurePeaks, importImage, importStockMusic, importStockVideo, peekEdgeFrame, requestEdgeFrame, revealMedia } from "@/cut/lib/media";
import { track0Clips, laneGapAt, sameLane, type LaneRef, clipLen, clipSpeed, footprints, getClipSpans, nextFreeStart, overlayLaneOrder, overlayLayers, projectDuration, resolveTransitions, rippleInsert, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";
@@ -3259,6 +3259,17 @@ function ClipMenu({
<DropdownMenuItem onClick={() => exportSegment(asset, clip)}>
<ArrowDownToLine /> Export segment
</DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!!asset.upload}
+ onClick={() => {
+ // The source file whole, as it was imported — the trimmed version
+ // is what "Export segment" renders.
+ const projectId = useEditor.getState().projectId;
+ if (projectId) downloadMedia(projectId, asset);
+ }}
+ >
+ <Download /> Download
+ </DropdownMenuItem>
{caps.revealInFinder && (
<DropdownMenuItem
onClick={() => {
diff --git a/site/src/cut/lib/download.ts b/site/src/cut/lib/download.ts
new file mode 100644
index 00000000..1c8d9c29
--- /dev/null
+++ b/site/src/cut/lib/download.ts
@@ -0,0 +1,20 @@
+"use client";
+
+/**
+ * Save a served media file to the user's Downloads folder.
+ *
+ * The `download=1` flag is what turns the URL into a download: both backends
+ * answer it with an attachment disposition, which is the only thing that works
+ * here. The anchor's own `download` attribute is ignored cross-origin, and
+ * every media URL this app hands out is cross-origin to the page — the engine
+ * on localhost, the cloud's 302 to the media host.
+ */
+export function downloadFromUrl(url: string, name: string) {
+ const a = document.createElement("a");
+ a.href = `${url}${url.includes("?") ? "&" : "?"}download=1`;
+ a.download = name;
+ a.rel = "noopener";
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+}
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 1bdc6cde..e2826e96 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -2,6 +2,7 @@
import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
import { quotaErrorMessage } from "./backend/cloud";
+import { downloadFromUrl } from "./download";
import { renderProjectToMp4 } from "./exportRender";
import { putSigned } from "./media";
import { clipSpeed, getClipSpans, overlayLayers, projectDuration, spanSequence, useEditor } from "./store";
@@ -139,14 +140,10 @@ export async function revealExport(
* when the backend has no Finder (the cloud route 302s to a signed R2 URL with
* attachment disposition). */
export function downloadProjectExport(projectId: string, file: string) {
- const a = document.createElement("a");
- a.href = getBackend().url(
- `/api/cut/projects/${projectId}/exports/${encodeURIComponent(file)}?download=1`
+ downloadFromUrl(
+ getBackend().url(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(file)}`),
+ file
);
- a.download = file;
- document.body.appendChild(a);
- a.click();
- a.remove();
}
/** Delete a rendered export from the project folder. Throws on failure so the
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index d510a177..5317367a 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -2,6 +2,7 @@
import { apiJson, getBackend } from "./backend";
import { readSnapshot, writeSnapshot } from "./cache";
+import { downloadFromUrl } from "./download";
import {
enrichAsset,
importRemote,
@@ -64,6 +65,12 @@ export interface LibraryData {
export const libraryMediaUrl = (fileName: string, residency: Residency) =>
backendFor(residency).url(`/api/cut/library/media/${encodeURIComponent(fileName)}`);
+/** Save a library file to the user's Downloads folder, off the shelf it sits
+ * on. */
+export function downloadLibraryAsset(a: Pick<LibraryAsset, "fileName" | "residency">) {
+ downloadFromUrl(libraryMediaUrl(a.fileName, a.residency), a.fileName);
+}
+
async function fetchLibraryFrom(r: Residency): Promise<LibraryData> {
const res = await backendFor(r).fetch("/api/cut/library");
if (!res.ok) throw new Error("Could not load the library.");
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 1c603bf0..a8b0173f 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -4,6 +4,7 @@ import { scanSilence, type PcmChunk } from "./audioScan";
import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
import { quotaErrorMessage } from "./backend/cloud";
import { encodeWav } from "./cloudTranscribe";
+import { downloadFromUrl } from "./download";
import { startUpload } from "./importQueue";
import {
audioChunks,
@@ -88,6 +89,20 @@ export async function createProjectFromFile(
return project.id;
}
+/** Save a project media file to the user's Downloads folder — the everywhere
+ * counterpart to revealing it in Finder.
+ *
+ * What lands is the source file itself: import stores the bytes it was handed
+ * and every derivative (proxy, ladder, filmstrip, export) is a separate file,
+ * so the media route is already the original. An asset whose bytes are still
+ * uploading has no server copy to serve, so it has nothing to download yet.
+ * `backend` pins the shelf the asset lives on when the ambient one may have
+ * moved on. */
+export function downloadMedia(projectId: string, asset: MediaAsset, backend?: CutBackend) {
+ if (asset.upload) return;
+ downloadFromUrl(mediaUrl(projectId, asset.fileName, backend), asset.fileName);
+}
+
/** Reveal a project media file in Finder (local engine only). */
export async function revealMedia(projectId: string, fileName: string) {
await apiFetch(
diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.ts
index 52c0aa61..fcd0aee6 100644
--- a/site/src/cut/server/cloud/library.ts
+++ b/site/src/cut/server/cloud/library.ts
@@ -400,9 +400,15 @@ export const libraryCloud = {
}
},
- async serveMedia(userId: string, file: string) {
+ async serveMedia(userId: string, file: string, download = false) {
try {
- return redirect(mediaObjectUrl(libraryKey(userId, decodeFileParam(file))));
+ const fileName = decodeFileParam(file);
+ return redirect(
+ mediaObjectUrl(
+ libraryKey(userId, fileName),
+ download ? { downloadName: fileName } : undefined
+ )
+ );
} catch (e) {
return caught(e, "Bad request.", 400);
}
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index 52d3c915..d76c8208 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -331,7 +331,7 @@ export const projectsCloud = {
// --- Media / export / preview bytes: 302 to a signed R2 GET. ---
- async serveMedia(userId: string, id: string, file: string) {
+ async serveMedia(userId: string, id: string, file: string, download = false) {
try {
const fileName = decodeFileParam(file);
const row = await prisma.cutMediaObject.findFirst({
@@ -342,6 +342,7 @@ export const projectsCloud = {
return redirect(
mediaObjectUrl(projectMediaKey(userId, id, fileName), {
version: String(row.updatedAt.getTime()),
+ ...(download ? { downloadName: fileName } : {}),
})
);
} catch (e) {
diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.ts
index 9cb4c350..4c69a825 100644
--- a/site/src/cut/server/cloud/routes.ts
+++ b/site/src/cut/server/cloud/routes.ts
@@ -17,6 +17,7 @@ import { projectsCloud } from "./projects";
import { shareCloud } from "./share";
import { transcribeCloud } from "./transcribe";
import { usageApi } from "./usage";
+import { wantsDownload } from "./util";
type CloudHandler = (
req: Request,
@@ -42,9 +43,9 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "POST", path: "/api/cut-cloud/projects/:id/duplicate", handler: (_r, u, p) => copyJobs.requestDuplicate(u, p.id) },
{ method: "GET", path: "/api/cut-cloud/copy-jobs/:jobId", handler: (_r, u, p) => copyJobs.ownerStatus(u, p.jobId) },
{ method: "GET", path: "/api/cut-cloud/projects/:id/exports", handler: (_r, u, p) => projectsCloud.listExports(u, p.id) },
- { method: "GET", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (r, u, p) => projectsCloud.serveExport(u, p.id, p.file, new URL(r.url).searchParams.has("download")) },
+ { method: "GET", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (r, u, p) => projectsCloud.serveExport(u, p.id, p.file, wantsDownload(r)) },
{ method: "DELETE", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (_r, u, p) => projectsCloud.removeExport(u, p.id, p.file) },
- { method: "GET", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.serveMedia(u, p.id, p.file) },
+ { method: "GET", path: "/api/cut-cloud/projects/:id/media/:file", handler: (r, u, p) => projectsCloud.serveMedia(u, p.id, p.file, wantsDownload(r)) },
{ method: "DELETE", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.removeMedia(u, p.id, p.file) },
{ method: "GET", path: "/api/cut-cloud/projects/:id/preview", handler: (_r, u, p) => projectsCloud.servePreview(u, p.id) },
{ method: "GET", path: "/api/cut-cloud/projects/:id/share", handler: (_r, u, p) => shareCloud.get(u, p.id) },
@@ -73,7 +74,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [
{ method: "POST", path: "/api/cut-cloud/library/folders", handler: (r, u) => libraryCloud.createFolder(u, r) },
{ method: "PUT", path: "/api/cut-cloud/library/folders/:id", handler: (r, u, p) => libraryCloud.renameFolder(u, p.id, r) },
{ method: "DELETE", path: "/api/cut-cloud/library/folders/:id", handler: (_r, u, p) => libraryCloud.deleteFolder(u, p.id) },
- { method: "GET", path: "/api/cut-cloud/library/media/:file", handler: (_r, u, p) => libraryCloud.serveMedia(u, p.file) },
+ { method: "GET", path: "/api/cut-cloud/library/media/:file", handler: (r, u, p) => libraryCloud.serveMedia(u, p.file, wantsDownload(r)) },
{ method: "DELETE", path: "/api/cut-cloud/library/:id", handler: (_r, u, p) => libraryCloud.remove(u, p.id) },
{ method: "GET", path: "/api/cut-cloud/export-jobs", handler: (_r, u) => jobsCloud.exportFeed(u) },
diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.ts
index 71453b1e..0ab2dd3d 100644
--- a/site/src/cut/server/cloud/util.ts
+++ b/site/src/cut/server/cloud/util.ts
@@ -25,6 +25,10 @@ export const caught = (e: unknown, fallback: string, status = 500) => {
export const redirect = (url: string, headers: Record<string, string> = {}) =>
new Response(null, { status: 302, headers: { Location: url, ...headers } });
+/** `?download=1` on a media URL asks for the bytes as an attachment — the
+ * engine's flag, read the same way here. */
+export const wantsDownload = (req: Request) => new URL(req.url).searchParams.has("download");
+
/** Sanitize an upload name the way the engine's saveMedia does. */
export function safeFileName(original: string): string {
const base = path
diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.ts
index 4b784d1f..cd6c368d 100644
--- a/site/src/cut/server/http/library.ts
+++ b/site/src/cut/server/http/library.ts
@@ -18,7 +18,7 @@ import {
useTemplate,
type TemplateInput,
} from "../library";
-import { serveFileRange } from "../serveFile";
+import { serveFileRange, wantsDownload } from "../serveFile";
import { importFromUrl } from "../urlImport";
const err = (message: string, status: number) => Response.json({ error: message }, { status });
@@ -189,11 +189,13 @@ export const libraryApi = {
/** Raw library media file with Range support. */
async serveMedia(req: Request, { file }: { file: string }) {
let p: string;
+ let name: string;
try {
- p = libMediaPath(decodeURIComponent(file));
+ name = decodeURIComponent(file);
+ p = libMediaPath(name);
} catch {
return new Response("Bad request.", { status: 400 });
}
- return serveFileRange(p, req);
+ return serveFileRange(p, req, wantsDownload(req) ? { downloadName: name } : {});
},
};
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 2467a182..3a5a8d3c 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -22,7 +22,7 @@ import {
sweepOrphanMedia,
writeProject,
} from "../projects";
-import { serveFileRange } from "../serveFile";
+import { serveFileRange, wantsDownload } from "../serveFile";
import { importUrlToProject } from "../urlImport";
import { createTranscribeJob, getTranscribeJob, type TranscribeSpec } from "../transcribe";
import { exists } from "../util";
@@ -239,12 +239,14 @@ export const projectsApi = {
/** Raw media file with Range support so <video>/<audio> can seek. */
async serveMedia(req: Request, { id, file }: { id: string; file: string }) {
let p: string;
+ let name: string;
try {
- p = mediaPath(id, decodeURIComponent(file));
+ name = decodeURIComponent(file);
+ p = mediaPath(id, name);
} catch {
return new Response("Bad request.", { status: 400 });
}
- return serveFileRange(p, req);
+ return serveFileRange(p, req, wantsDownload(req) ? { downloadName: name } : {});
},
/** Rendered exports for a project, newest first. */
@@ -259,12 +261,17 @@ export const projectsApi = {
/** A rendered export with Range support so the preview player can seek. */
async serveExport(req: Request, { id, file }: { id: string; file: string }) {
let p: string;
+ let name: string;
try {
- p = exportPath(id, decodeURIComponent(file));
+ name = decodeURIComponent(file);
+ p = exportPath(id, name);
} catch {
return new Response("Bad request.", { status: 400 });
}
- return serveFileRange(p, req, { contentType: "video/mp4" });
+ return serveFileRange(p, req, {
+ contentType: "video/mp4",
+ ...(wantsDownload(req) ? { downloadName: name } : {}),
+ });
},
/** Reveal a rendered export in Finder (Cut runs on the user's own Mac). */
diff --git a/site/src/cut/server/serveFile.ts b/site/src/cut/server/serveFile.ts
index 7634f200..245e1b2b 100644
--- a/site/src/cut/server/serveFile.ts
+++ b/site/src/cut/server/serveFile.ts
@@ -28,6 +28,14 @@ export function contentTypeFor(p: string) {
return TYPES[path.extname(p).toLowerCase()] ?? "application/octet-stream";
}
+/** `?download=1` on a media URL asks for the bytes as an attachment. The same
+ * flag reads the same way on both backends: the engine sets the disposition
+ * header itself, the cloud signs the name into the object URL it redirects to.
+ * The name is always the stored file's own, never anything off the query. */
+export function wantsDownload(req: Request): boolean {
+ return new URL(req.url).searchParams.has("download");
+}
+
interface Opts {
/** Override the MIME type (defaults to the extension's type). */
contentType?: string;