Skip to content

Open source CapCut alternative.

TypeScript

feat(site): share links unfurl with the project's own card [rebuild]

David Le61d31536175f
diff --git a/site/src/app/cut/s/[token]/SharedProjectView.tsx b/site/src/app/cut/s/[token]/SharedProjectView.tsx
new file mode 100644
index 00000000..6a8853da
--- /dev/null
+++ b/site/src/app/cut/s/[token]/SharedProjectView.tsx
@@ -0,0 +1,105 @@
+"use client";
+
+import { Suspense, useEffect, useState } from "react";
+import { useParams } from "next/navigation";
+import { Clapperboard, Loader2 } from "lucide-react";
+import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
+import { Button } from "@/components/ui/button";
+import { Editor } from "@/cut/components/Editor";
+import { setCutMode } from "@/cut/lib/backend";
+import { bindSharedBackend } from "@/cut/lib/backend/shared";
+import { useEditor } from "@/cut/lib/store";
+import type { ShareFeatures } from "@/cut/lib/types";
+import { authClient } from "@/lib/auth-client";
+
+// The read-only share view. This route sits beside the app subtree on purpose:
+// /cut/app is session-gated (RequireSession) and engine-gated (ConnectGate),
+// and a public share link must open with neither. The share meta fetch is the
+// access check — the server answers 401 (sign in), 403 (not invited), or 404
+// (no such share) — and on success the page binds the shared backend and
+// mounts the editor in viewer mode.
+
+type Gate =
+ | { state: "loading" }
+ | { state: "ready"; projectId: string }
+ | { state: "signin" }
+ | { state: "denied" }
+ | { state: "missing" };
+
+export function SharedProject() {
+ const { token } = useParams<{ token: string }>();
+ const [gate, setGate] = useState<Gate>({ state: "loading" });
+ const { data: session } = authClient.useSession();
+
+ useEffect(() => {
+ let alive = true;
+ void fetch(`/api/cut-shared/${encodeURIComponent(token)}`)
+ .then(async (res) => {
+ if (!alive) return;
+ if (res.status === 401) return setGate({ state: "signin" });
+ if (res.status === 403) return setGate({ state: "denied" });
+ if (!res.ok) return setGate({ state: "missing" });
+ const meta = (await res.json()) as { projectId: string; features: ShareFeatures };
+ bindSharedBackend(token);
+ setCutMode("shared");
+ useEditor.getState().setSharedView(meta.features);
+ setGate({ state: "ready", projectId: meta.projectId });
+ })
+ .catch(() => alive && setGate({ state: "missing" }));
+ return () => {
+ alive = false;
+ };
+ }, [token]);
+
+ if (gate.state === "ready") return <Editor projectId={gate.projectId} viewer />;
+
+ if (gate.state === "loading") {
+ return (
+ <div className="grid h-screen place-items-center text-muted-foreground">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ );
+ }
+
+ const signIn = () => {
+ const here = window.location.pathname + window.location.search;
+ window.location.href = authHrefFor("/sign-in", here);
+ };
+
+ return (
+ <div className="grid h-screen place-items-center">
+ <div className="flex max-w-sm flex-col items-center gap-3 text-center">
+ <Clapperboard className="size-7 text-muted-foreground" />
+ {gate.state === "signin" ? (
+ <>
+ <p className="text-sm text-muted-foreground">
+ This project is shared with specific people — sign in to see if
+ that&apos;s you.
+ </p>
+ <Button onClick={signIn}>Sign in</Button>
+ </>
+ ) : gate.state === "denied" ? (
+ <p className="text-sm text-muted-foreground">
+ You don&apos;t have access to this project
+ {session?.user.email ? ` as ${session.user.email}` : ""}. Ask the
+ owner to invite you.
+ </p>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ This share link isn&apos;t active anymore.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export function SharedProjectView() {
+ return (
+ <div className="min-h-screen bg-white font-system text-foreground antialiased">
+ <Suspense>
+ <SharedProject />
+ </Suspense>
+ </div>
+ );
+}
diff --git a/site/src/app/cut/s/[token]/card/[ext]/route.ts b/site/src/app/cut/s/[token]/card/[ext]/route.ts
new file mode 100644
index 00000000..8f007ada
--- /dev/null
+++ b/site/src/app/cut/s/[token]/card/[ext]/route.ts
@@ -0,0 +1,50 @@
+import { resolveShare } from "@/cut/server/cloud/sharedView";
+import {
+ CARD_CACHE_SECONDS,
+ cardUrl,
+ placeholderCard,
+ shareProjectName,
+ type CardKind,
+} from "@/cut/server/cloud/shareCard";
+
+// The image a shared link unfurls with. Crawlers fetch this directly, so it
+// answers for the token alone with no session and no client bundle in the way.
+// The version in the query string is what makes a re-share pick up a newer
+// card: the bytes behind it live on a fixed R2 key.
+//
+// A public share's card is cacheable by anyone — the token is already the
+// gate. A restricted share's is not: it 404s for anyone the share doesn't name,
+// so the answer depends on the viewer's session and must stay out of shared
+// caches.
+
+export const runtime = "nodejs";
+
+export async function GET(
+ request: Request,
+ { params }: { params: Promise<{ token: string; ext: string }> }
+) {
+ const { token, ext } = await params;
+ const view = await resolveShare(token, request);
+ if (view instanceof Response) return view;
+ const target = { userId: view.share.userId, projectId: view.share.projectId };
+ const cacheable = view.share.access === "public";
+ const headers: Record<string, string> = cacheable
+ ? { "Cache-Control": `public, s-maxage=${CARD_CACHE_SECONDS}, stale-while-revalidate=86400` }
+ : { "Cache-Control": "private, no-store" };
+
+ if (ext === "gif" || ext === "jpg") {
+ const url = await cardUrl(target, ext as CardKind);
+ if (url) return new Response(null, { status: 302, headers: { ...headers, Location: url } });
+ }
+
+ // No card yet — draw one so the link never unfurls blank. Kept on a short
+ // leash so the rendered card takes over as soon as it exists.
+ const name = await shareProjectName(target);
+ if (!name) return new Response("Not found.", { status: 404 });
+ const image = placeholderCard(name);
+ const short = cacheable ? "public, s-maxage=60, stale-while-revalidate=600" : "private, no-store";
+ return new Response(image.body, {
+ status: 200,
+ headers: { "Content-Type": "image/png", "Cache-Control": short },
+ });
+}
diff --git a/site/src/app/cut/s/[token]/page.tsx b/site/src/app/cut/s/[token]/page.tsx
index 2cbbe7fd..910c23e9 100644
--- a/site/src/app/cut/s/[token]/page.tsx
+++ b/site/src/app/cut/s/[token]/page.tsx
@@ -1,105 +1,81 @@
-"use client";
+import type { Metadata } from "next";
+import { headers } from "next/headers";
+import { cutAppBase } from "@/cut/lib/hosts";
+import { shareMetaForToken } from "@/cut/server/cloud/shareCard";
+import { SharedProjectView } from "./SharedProjectView";
-import { Suspense, useEffect, useState } from "react";
-import { useParams } from "next/navigation";
-import { Clapperboard, Loader2 } from "lucide-react";
-import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";
-import { Button } from "@/components/ui/button";
-import { Editor } from "@/cut/components/Editor";
-import { setCutMode } from "@/cut/lib/backend";
-import { bindSharedBackend } from "@/cut/lib/backend/shared";
-import { useEditor } from "@/cut/lib/store";
-import type { ShareFeatures } from "@/cut/lib/types";
-import { authClient } from "@/lib/auth-client";
+// The share page is a client view — it fetches its own access decision and
+// mounts the editor read-only — but the document around it is server-rendered,
+// which is the only thing a link crawler ever sees. So the title, description,
+// and card come from here.
+//
+// Only a public share describes itself. A restricted share is a link that
+// means nothing without the right account, so it unfurls as a neutral invite
+// and stays out of search: naming the project there would leak it to anyone
+// holding the URL.
-// The read-only share view. This route sits beside the app subtree on purpose:
-// /cut/app is session-gated (RequireSession) and engine-gated (ConnectGate),
-// and a public share link must open with neither. The share meta fetch is the
-// access check — the server answers 401 (sign in), 403 (not invited), or 404
-// (no such share) — and on success the page binds the shared backend and
-// mounts the editor in viewer mode.
-
-type Gate =
- | { state: "loading" }
- | { state: "ready"; projectId: string }
- | { state: "signin" }
- | { state: "denied" }
- | { state: "missing" };
+/** Absolute origin for this request — card URLs must be absolute for crawlers. */
+async function origin(): Promise<string> {
+ const h = await headers();
+ const host = h.get("host") ?? "donkeycut.com";
+ const proto = h.get("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https");
+ return `${proto}://${host}`;
+}
-function SharedProject() {
- const { token } = useParams<{ token: string }>();
- const [gate, setGate] = useState<Gate>({ state: "loading" });
- const { data: session } = authClient.useSession();
+/** The public path of this share, mirroring the link the Share dialog copies:
+ * the app base without its /app segment. */
+function sharePath(host: string | null, token: string): string {
+ return `${cutAppBase(host).replace(/\/app$/, "")}/s/${encodeURIComponent(token)}`;
+}
- useEffect(() => {
- let alive = true;
- void fetch(`/api/cut-shared/${encodeURIComponent(token)}`)
- .then(async (res) => {
- if (!alive) return;
- if (res.status === 401) return setGate({ state: "signin" });
- if (res.status === 403) return setGate({ state: "denied" });
- if (!res.ok) return setGate({ state: "missing" });
- const meta = (await res.json()) as { projectId: string; features: ShareFeatures };
- bindSharedBackend(token);
- setCutMode("shared");
- useEditor.getState().setSharedView(meta.features);
- setGate({ state: "ready", projectId: meta.projectId });
- })
- .catch(() => alive && setGate({ state: "missing" }));
- return () => {
- alive = false;
+export async function generateMetadata({
+ params,
+}: {
+ params: Promise<{ token: string }>;
+}): Promise<Metadata> {
+ const { token } = await params;
+ const meta = await shareMetaForToken(token);
+ if (!meta || !meta.isPublic) {
+ return {
+ title: "Shared project · Donkey Cut",
+ description: "This project is shared with specific people.",
+ robots: { index: false, follow: false },
};
- }, [token]);
-
- if (gate.state === "ready") return <Editor projectId={gate.projectId} viewer />;
-
- if (gate.state === "loading") {
- return (
- <div className="grid h-screen place-items-center text-muted-foreground">
- <Loader2 className="size-5 animate-spin" />
- </div>
- );
}
-
- const signIn = () => {
- const here = window.location.pathname + window.location.search;
- window.location.href = authHrefFor("/sign-in", here);
+ const h = await headers();
+ const base = await origin();
+ const url = `${base}${sharePath(h.get("host"), token)}`;
+ const card = (kind: "gif" | "jpg") => `${url}/card/${kind}?v=${meta.version}`;
+ const description = `A video project shared from Donkey Cut. Watch ${meta.name} in the browser.`;
+ // The GIF leads: the platforms that animate it play the opening seconds, and
+ // the rest fall back to its first frame — the same picture the JPEG carries
+ // for anything that would rather not take a multi-megabyte image. Either URL
+ // answers before a card has rendered; the route draws one.
+ const images = [
+ { url: card("gif"), width: 1200, height: 630, alt: meta.name },
+ { url: card("jpg"), width: 1200, height: 630, alt: meta.name },
+ ];
+ return {
+ title: `${meta.name} · Donkey Cut`,
+ description,
+ alternates: { canonical: url },
+ openGraph: {
+ type: "video.other",
+ title: meta.name,
+ description,
+ url,
+ siteName: "Donkey Cut",
+ images,
+ },
+ twitter: {
+ card: "summary_large_image",
+ title: meta.name,
+ description,
+ images: images.map((i) => i.url),
+ },
};
-
- return (
- <div className="grid h-screen place-items-center">
- <div className="flex max-w-sm flex-col items-center gap-3 text-center">
- <Clapperboard className="size-7 text-muted-foreground" />
- {gate.state === "signin" ? (
- <>
- <p className="text-sm text-muted-foreground">
- This project is shared with specific people — sign in to see if
- that&apos;s you.
- </p>
- <Button onClick={signIn}>Sign in</Button>
- </>
- ) : gate.state === "denied" ? (
- <p className="text-sm text-muted-foreground">
- You don&apos;t have access to this project
- {session?.user.email ? ` as ${session.user.email}` : ""}. Ask the
- owner to invite you.
- </p>
- ) : (
- <p className="text-sm text-muted-foreground">
- This share link isn&apos;t active anymore.
- </p>
- )}
- </div>
- </div>
- );
}
export default function SharedProjectPage() {
- return (
- <div className="min-h-screen bg-white font-system text-foreground antialiased">
- <Suspense>
- <SharedProject />
- </Suspense>
- </div>
- );
+ return <SharedProjectView />;
}
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 64d3e832..58ab22a6 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -6,7 +6,7 @@ import { Clapperboard, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { apiFetch, setCutMode } from "@/cut/lib/backend";
import { loadedDocVersion } from "@/cut/lib/backend/shared";
-import { renderPreviewProxy } from "@/cut/lib/exportClient";
+import { refreshShareCard, renderPreviewProxy } from "@/cut/lib/exportClient";
import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
// Side-effect import: registers the brief-to-video resume subscription, so a
@@ -196,6 +196,7 @@ export function Editor({
};
try {
await renderPreviewProxy(projectId, doc, s.aspect);
+ refreshShareCard(projectId);
} finally {
rendering = false;
}
diff --git a/site/src/cut/components/ShareDialog.tsx b/site/src/cut/components/ShareDialog.tsx
index 5699bbc6..0f025345 100644
--- a/site/src/cut/components/ShareDialog.tsx
+++ b/site/src/cut/components/ShareDialog.tsx
@@ -18,6 +18,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { Switch } from "@/components/ui/switch";
import { apiFetch } from "@/cut/lib/backend";
+import { refreshShareCard } from "@/cut/lib/exportClient";
import { useCutBase } from "@/cut/lib/nav";
import type { ShareFeatures } from "@/cut/lib/types";
@@ -85,6 +86,10 @@ export function ShareDialog({
.then((r) => (r.ok ? (r.json() as Promise<{ share: ShareState | null }>) : { share: null }))
.then((body) => {
if (!alive) return;
+ // Opening the dialog is the moment before a link gets pasted
+ // somewhere, so bring an existing share's preview card up to date with
+ // the cut as it stands.
+ if (body.share) refreshShareCard(projectId);
setShare(body.share);
setLoading(false);
})
@@ -114,6 +119,9 @@ export function ShareDialog({
});
if (!res.ok) throw new Error();
const body = (await res.json()) as { share: ShareState };
+ // Sharing for the first time: build the link's preview card now, so the
+ // first person to see the link sees the cut rather than a placeholder.
+ if (!share) refreshShareCard(projectId);
setShare(body.share);
return body.share;
} catch {
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index f7e5996f..2228f049 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -176,7 +176,7 @@ async function buildExportPayload(
projectId: string,
doc: ExportDoc,
settings: ExportSettings,
- target: "export" | "preview"
+ target: "export" | "preview" | "card"
): Promise<ExportPayload> {
const spans = getClipSpans(doc.clips, doc.assets);
const duration = projectDuration(doc);
@@ -538,3 +538,101 @@ export async function renderPreviewProxy(projectId: string, doc: ExportDoc, aspe
if (!res.ok || !body.id) return; // a slot was busy; try again later
await pollExport(body.id, () => {}, undefined, backend).catch(() => {});
}
+
+/** Seconds of the cut a share card shows. */
+const CARD_SECONDS = 5;
+
+/** The cut's first `seconds`, as a doc. Clips keep their trim-in and lose
+ * whatever hangs past the cut-off; everything starting after it drops. Used
+ * for the share card, which is a five-second window onto the opening rather
+ * than a render of the whole project. */
+export function docFirstSeconds(doc: ExportDoc, seconds: number): ExportDoc {
+ // A clip's timeline footprint is (out - in) / speed, so the trim that ends
+ // it at `seconds` scales back through the speed.
+ const clampOut = <T extends { start: number; in: number; out: number; speed?: number }>(
+ clip: T
+ ): T => {
+ const speed = clip.speed && clip.speed > 0 ? clip.speed : 1;
+ const room = (seconds - clip.start) * speed;
+ return clip.out - clip.in <= room ? clip : { ...clip, out: clip.in + room };
+ };
+ const starts = <T extends { start: number }>(item: T) => item.start < seconds;
+ return {
+ ...doc,
+ clips: doc.clips.filter(starts).map(clampOut),
+ audioClips: doc.audioClips.filter(starts).map(clampOut),
+ overlays: doc.overlays
+ .filter(starts)
+ .map((o) => (o.end <= seconds ? o : { ...o, end: seconds })),
+ subtitles: {
+ ...doc.subtitles,
+ cues: doc.subtitles.cues
+ .filter(starts)
+ .map((c) => (c.end <= seconds ? c : { ...c, end: seconds })),
+ },
+ // A fade-out belongs to the end of the project, which the card cuts away.
+ fadeOut: 0,
+ };
+}
+
+/** Card frame size for an aspect: 16:9 sits close to the 1.91:1 social cards
+ * want, and portrait cuts get a tall card rather than a letterboxed wide one. */
+function cardSettings(aspect: Aspect): ExportSettings {
+ const [width, height] = aspect === "16:9" ? [1280, 720] : [720, 1280];
+ return { width, height, fps: 15, crf: 26, preset: "veryfast" };
+}
+
+/** Render the project's link-preview card: the opening five seconds, which
+ * the worker turns into the still frame and the animated thumbnail a shared
+ * link unfurls with. Only shared projects have one, so this asks first and
+ * costs a single small request when the project isn't shared.
+ *
+ * Best-effort throughout — a project with no footage, an unconfigured
+ * backend, or a busy render slot simply keeps the card it already had. */
+async function renderShareCard(projectId: string, doc: ExportDoc, aspect: Aspect): Promise<void> {
+ const backend = getBackend(); // pinned: the card render outlives navigation
+ if (backend.kind !== "cloud") return;
+ try {
+ const res = await backend.fetch(`/api/cut/projects/${projectId}/share`);
+ const body = (await res.json().catch(() => ({}))) as { share?: unknown | null };
+ if (!res.ok || !body.share) return;
+ } catch {
+ return;
+ }
+ let res: Response;
+ try {
+ const payload = await buildExportPayload(
+ projectId,
+ docFirstSeconds(doc, CARD_SECONDS),
+ cardSettings(aspect),
+ "card"
+ );
+ res = await postExport(projectId, payload, "card.mp4", backend);
+ } catch {
+ return; // no clips yet
+ }
+ const body = (await res.json().catch(() => ({}))) as { id?: string };
+ if (!res.ok || !body.id) return;
+ await pollExport(body.id, () => {}, undefined, backend).catch(() => {});
+}
+
+/** Rebuild the open project's share card from the cut as it stands. Fire and
+ * forget: the card is an accessory to the link, and a failed render leaves the
+ * previous one (or the generated placeholder) in place. */
+export function refreshShareCard(projectId: string): void {
+ const s = useEditor.getState();
+ if (!s.loaded || s.projectId !== projectId || s.clips.length === 0) return;
+ void renderShareCard(
+ projectId,
+ {
+ assets: s.assets,
+ clips: s.clips,
+ audioClips: s.audioClips,
+ overlays: s.overlays,
+ subtitles: s.subtitles,
+ fadeIn: s.fadeIn,
+ fadeOut: s.fadeOut,
+ },
+ s.aspect
+ ).catch(() => {});
+}
diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.ts
index f2d2c48d..c1305684 100644
--- a/site/src/cut/server/cloud/jobs.ts
+++ b/site/src/cut/server/cloud/jobs.ts
@@ -110,19 +110,25 @@ export const jobsCloud = {
return err("Invalid overlay key.", 400);
}
}
- const preview = body.spec.target === "preview";
- if (!preview) {
+ // Hover proxies and share cards are small internal renders the editor
+ // fires on its own; only renders the user asked for count against the
+ // cap.
+ const target = body.spec.target === "preview" || body.spec.target === "card"
+ ? body.spec.target
+ : "export";
+ if (target === "export") {
const capped = await renderJobCheck(userId);
if (capped) return capped;
}
- const outName = preview
- ? "preview.mp4"
- : await exportName(userId, projectId, body.outName?.trim() || project.name);
+ const outName =
+ target === "export"
+ ? await exportName(userId, projectId, body.outName?.trim() || project.name)
+ : `${target}.mp4`;
const row = await prisma.cutRenderJob.create({
data: {
userId,
projectId,
- kind: preview ? "preview" : "export",
+ kind: target,
spec: {
spec: body.spec,
overlays: body.overlays ?? [],
diff --git a/site/src/cut/server/cloud/r2.ts b/site/src/cut/server/cloud/r2.ts
index cc602e17..cdde7e62 100644
--- a/site/src/cut/server/cloud/r2.ts
+++ b/site/src/cut/server/cloud/r2.ts
@@ -49,6 +49,11 @@ export const projectExportKey = (userId: string, projectId: string, fileName: st
`cut/${userId}/projects/${projectId}/exports/${fileName}`;
export const projectPreviewKey = (userId: string, projectId: string) =>
`cut/${userId}/projects/${projectId}/preview.mp4`;
+/** The link-preview card's artifacts. Fixed keys, rewritten by each card
+ * render: the public URL carries the doc version, so freshness rides the URL
+ * and R2 keeps one copy instead of one per edit. */
+export const projectCardKey = (userId: string, projectId: string, ext: "jpg" | "gif") =>
+ `cut/${userId}/projects/${projectId}/card.${ext}`;
export const libraryKey = (userId: string, fileName: string) =>
`cut/${userId}/library/${fileName}`;
export const overlayKey = (userId: string, batchId: string, name: string) =>
diff --git a/site/src/cut/server/cloud/shareCard.tsx b/site/src/cut/server/cloud/shareCard.tsx
new file mode 100644
index 00000000..328d2ccb
--- /dev/null
+++ b/site/src/cut/server/cloud/shareCard.tsx
@@ -0,0 +1,126 @@
+// The share card: the image a link to a shared project unfurls with.
+//
+// The render worker derives two artifacts from the cut's opening seconds — a
+// still of the first frame and an animated GIF — and stores them on fixed R2
+// keys. Freshness rides the public URL, which carries the doc version, so a
+// crawler that has seen one version asks again for the next while the bytes
+// stay one object per project.
+//
+// Until a card has rendered (a link shared seconds ago, a project shared
+// before cards existed) the page still needs something to point at, so this
+// also draws the placeholder: the project's name on Cut's own backdrop.
+import { ImageResponse } from "next/og";
+import { prisma } from "@/lib/prisma";
+import { head, presignGet, projectCardKey } from "./r2";
+
+export type CardKind = "gif" | "jpg";
+
+/** OG's 1.91:1, the size every platform crops toward. */
+const CARD_WIDTH = 1200;
+const CARD_HEIGHT = 630;
+/** A card URL names its version, so a crawler holding one can be handed the
+ * edge copy for as long as the signature behind it lives. */
+export const CARD_CACHE_SECONDS = 45 * 60;
+
+export interface ShareCardTarget {
+ userId: string;
+ projectId: string;
+}
+
+/** A signed URL for one stored artifact, or null when it hasn't rendered.
+ * Storage being unreachable reads the same as no card — the route draws one
+ * rather than failing. */
+export async function cardUrl(
+ target: ShareCardTarget,
+ kind: CardKind
+): Promise<string | null> {
+ try {
+ const key = projectCardKey(target.userId, target.projectId, kind);
+ if (!(await head(key))) return null;
+ return await presignGet(key);
+ } catch {
+ return null;
+ }
+}
+
+/** The project's display name for the card and the page title. */
+export async function shareProjectName(target: ShareCardTarget): Promise<string | null> {
+ const row = await prisma.cutProject.findFirst({
+ where: { id: target.projectId, userId: target.userId },
+ select: { name: true },
+ });
+ return row?.name ?? null;
+}
+
+export interface ShareMeta {
+ name: string;
+ /** Doc version, so a card URL changes when the cut does. */
+ version: number;
+ isPublic: boolean;
+}
+
+/** Everything the share page's document needs, read straight from the rows —
+ * two indexed lookups and no storage round trip, because this runs on every
+ * viewer's page load, not just a crawler's. Whether a card has actually
+ * rendered is the card route's business: it draws one when it hasn't.
+ *
+ * A restricted share resolves far enough to know it is restricted and no
+ * further — the page describes those without naming them. */
+export async function shareMetaForToken(token: string): Promise<ShareMeta | null> {
+ if (!token || token.length > 64) return null;
+ const share = await prisma.cutProjectShare.findUnique({
+ where: { id: token },
+ select: { projectId: true, userId: true, access: true },
+ });
+ if (!share) return null;
+ const project = await prisma.cutProject.findFirst({
+ where: { id: share.projectId, userId: share.userId },
+ select: { name: true, version: true },
+ });
+ if (!project) return null;
+ return { name: project.name, version: project.version, isPublic: share.access === "public" };
+}
+
+/** The stand-in card, drawn rather than rendered: no ffmpeg runs on the hosted
+ * side, so this is what a link shows in the seconds before its first card
+ * lands. */
+export function placeholderCard(name: string): ImageResponse {
+ return new ImageResponse(
+ (
+ <div
+ style={{
+ width: "100%",
+ height: "100%",
+ display: "flex",
+ flexDirection: "column",
+ justifyContent: "flex-end",
+ padding: 72,
+ background: "linear-gradient(135deg, #0b0b0f 0%, #1b1a24 55%, #2a2333 100%)",
+ color: "#fff",
+ }}
+ >
+ <div style={{ display: "flex", fontSize: 30, letterSpacing: 2, opacity: 0.6 }}>
+ DONKEY CUT
+ </div>
+ <div
+ style={{
+ display: "flex",
+ fontSize: 68,
+ fontWeight: 700,
+ lineHeight: 1.1,
+ marginTop: 16,
+ // Two lines of a long project name, then an ellipsis.
+ maxHeight: 150,
+ overflow: "hidden",
+ }}
+ >
+ {name}
+ </div>
+ <div style={{ display: "flex", fontSize: 28, marginTop: 20, opacity: 0.65 }}>
+ Shared video project
+ </div>
+ </div>
+ ),
+ { width: CARD_WIDTH, height: CARD_HEIGHT }
+ );
+}
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index abde74d3..b3f2d344 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -12,9 +12,10 @@ import { lookFilterLines } from "../lib/looks";
export interface ExportSpec {
projectId: string;
- /** "preview" renders the low-res hover proxy into the project's preview.mp4
- * instead of a stamped file in exports/. */
- target?: "export" | "preview";
+ /** Where the render lands instead of a stamped file in exports/: "preview"
+ * writes the project's low-res hover proxy, "card" the opening seconds the
+ * cloud worker derives a shared link's preview image from. */
+ target?: "export" | "preview" | "card";
width: number;
height: number;
fps: number;
diff --git a/site/src/cut/worker/cardJob.ts b/site/src/cut/worker/cardJob.ts
new file mode 100644
index 00000000..8b1f9cd7
--- /dev/null
+++ b/site/src/cut/worker/cardJob.ts
@@ -0,0 +1,130 @@
+import { spawn } from "node:child_process";
+import { stat } from "node:fs/promises";
+import path from "node:path";
+import type { RenderHandle } from "../server/exportPipeline";
+import { prisma, registerObject, type ClaimedJob } from "./db";
+import { cardKey, uploadFile } from "./r2";
+
+// The share card: what a link to a shared project unfurls with. The render
+// itself is an ordinary export of the cut's opening seconds (runExportJob
+// produces it); this module turns that clip into the two artifacts a social
+// card needs — the true first frame as a JPEG, and an animated GIF of the
+// opening. Platforms split on GIFs: some animate them, the rest fall back to
+// the first frame, which is the same picture either way.
+
+/** Animated card: small enough that no crawler refuses it, big enough to read
+ * on a phone. Tried in order until one lands under MAX_GIF_BYTES. */
+const GIF_RECIPES = [
+ { fps: 12, width: 600, colors: 128 },
+ { fps: 10, width: 480, colors: 96 },
+ { fps: 8, width: 400, colors: 64 },
+];
+const MAX_GIF_BYTES = 3 * 1024 * 1024;
+
+/** ffmpeg for the derivations: short, bounded, and its own runner so the
+ * engine's export pipeline keeps a single entry point. */
+function ffmpeg(args: string[]): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const proc = spawn("ffmpeg", ["-hide_banner", "-y", ...args]);
+ let tail = "";
+ proc.stderr.on("data", (chunk: Buffer) => {
+ tail = (tail + chunk.toString()).slice(-2000);
+ });
+ const timer = setTimeout(() => proc.kill("SIGKILL"), 120_000);
+ timer.unref();
+ proc.on("error", (err) => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ proc.on("close", (code) => {
+ clearTimeout(timer);
+ if (code === 0) resolve();
+ else reject(new Error(`ffmpeg exited with code ${code}.\n${tail}`));
+ });
+ });
+}
+
+async function bytesOf(file: string): Promise<number> {
+ return (await stat(file)).size;
+}
+
+/** Still frame at t=0 — the video's actual first frame, not a poster picked
+ * from the middle. */
+async function renderStill(source: string, dest: string): Promise<number> {
+ await ffmpeg(["-i", source, "-frames:v", "1", "-q:v", "3", dest]);
+ return bytesOf(dest);
+}
+
+/** Animated card, stepping down through the recipes until it fits. The last
+ * recipe's output ships whatever its size — a card slightly over budget beats
+ * no card. */
+async function renderAnimation(source: string, dest: string): Promise<number> {
+ let bytes = 0;
+ for (const [i, recipe] of GIF_RECIPES.entries()) {
+ await ffmpeg([
+ "-i",
+ source,
+ "-vf",
+ `fps=${recipe.fps},scale=${recipe.width}:-2:flags=lanczos,split[s0][s1];` +
+ `[s0]palettegen=max_colors=${recipe.colors}[p];[s1][p]paletteuse=dither=bayer:bayer_scale=3`,
+ "-loop",
+ "0",
+ dest,
+ ]);
+ bytes = await bytesOf(dest);
+ if (bytes <= MAX_GIF_BYTES || i === GIF_RECIPES.length - 1) break;
+ }
+ return bytes;
+}
+
+/**
+ * Derive and store a project's card artifacts from the rendered opening clip.
+ * Both land on fixed keys, so a re-render replaces the pair in place and the
+ * project never accumulates one card per edit — the public URL carries the
+ * doc version instead. Returns the key the job row records.
+ */
+export async function storeCardArtifacts(
+ job: ClaimedJob,
+ handle: RenderHandle,
+ projectId: string
+): Promise<{ outputKey: string; outName: string }> {
+ const dir = path.dirname(handle.outPath);
+ const stillPath = path.join(dir, "card.jpg");
+ const animPath = path.join(dir, "card.gif");
+ const stillBytes = await renderStill(handle.outPath, stillPath);
+ const animBytes = await renderAnimation(handle.outPath, animPath);
+
+ // Same guard the export path uses: a project deleted mid-render must not
+ // leave storage charged for bytes nothing can free.
+ const live = await prisma.cutRenderJob.findUnique({
+ where: { id: job.id },
+ select: { state: true },
+ });
+ if (live?.state !== "running") throw new Error("Canceled.");
+
+ const stillKey = cardKey(job.userId, projectId, "jpg");
+ const animKey = cardKey(job.userId, projectId, "gif");
+ await Promise.all([
+ uploadFile(stillKey, stillPath, "image/jpeg"),
+ uploadFile(animKey, animPath, "image/gif"),
+ ]);
+ await registerObject({
+ userId: job.userId,
+ projectId,
+ r2Key: stillKey,
+ fileName: "card.jpg",
+ mime: "image/jpeg",
+ bytes: stillBytes,
+ kind: "card",
+ });
+ await registerObject({
+ userId: job.userId,
+ projectId,
+ r2Key: animKey,
+ fileName: "card.gif",
+ mime: "image/gif",
+ bytes: animBytes,
+ kind: "card",
+ });
+ return { outputKey: animKey, outName: "card.gif" };
+}
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
index f30055e8..adb94cff 100644
--- a/site/src/cut/worker/exportJob.ts
+++ b/site/src/cut/worker/exportJob.ts
@@ -2,6 +2,7 @@ import { mkdir, mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { runExport, type ExportSpec, type RenderHandle } from "../server/exportPipeline";
+import { storeCardArtifacts } from "./cardJob";
import { prisma, registerObject, type ClaimedJob } from "./db";
import { downloadToFile, exportKey, mediaKey, previewKey, uploadFile } from "./r2";
@@ -26,9 +27,11 @@ export function overlayKeysOf(job: ClaimedJob): string[] {
}
/**
- * Run one export or preview job: stage a project-shaped work dir (media/ +
- * overlay PNGs in the pipeline tmp dir), render through the engine's shared
- * pipeline, and land the mp4 back in R2. Returns what the job row records.
+ * Run one export, preview, or card job: stage a project-shaped work dir
+ * (media/ + overlay PNGs in the pipeline tmp dir), render through the engine's
+ * shared pipeline, and land the result back in R2 — the mp4 for an export or
+ * hover proxy, the derived still and animation for a card. Returns what the
+ * job row records.
*/
export async function runExportJob(
job: ClaimedJob,
@@ -39,7 +42,13 @@ export async function runExportJob(
if (!spec || !Array.isArray(spec.clips)) throw new Error("Malformed export spec.");
const projectId = job.projectId ?? spec.projectId;
if (!projectId) throw new Error("Export job has no project.");
- const preview = job.kind === "preview" || spec.target === "preview";
+ const mode: "export" | "preview" | "card" =
+ job.kind === "preview" || spec.target === "preview"
+ ? "preview"
+ : job.kind === "card" || spec.target === "card"
+ ? "card"
+ : "export";
+ const preview = mode === "preview";
const work = await mkdtemp(path.join(os.tmpdir(), "cut-worker-"));
try {
@@ -67,12 +76,16 @@ export async function runExportJob(
),
]);
- const outName = preview ? "preview.mp4" : job.outName?.trim() || "export.mp4";
+ const outName = mode === "export" ? job.outName?.trim() || "export.mp4" : `${mode}.mp4`;
handle.outPath = path.join(work, "out", outName);
await mkdir(path.dirname(handle.outPath), { recursive: true });
await runExport(handle, spec, (file) => path.join(mediaDir, path.basename(file)));
+ // A card's rendered clip is scratch: only the still and the animation it
+ // derives are stored, so the mp4 never reaches R2.
+ if (mode === "card") return storeCardArtifacts(job, handle, projectId);
+
// The project may have been deleted (its jobs canceled) between the
// watcher's last tick and now; registering the output then would charge
// storage nothing can ever free.
diff --git a/site/src/cut/worker/main.ts b/site/src/cut/worker/main.ts
index 903d942f..01c0f3ec 100644
--- a/site/src/cut/worker/main.ts
+++ b/site/src/cut/worker/main.ts
@@ -118,7 +118,7 @@ async function runJob(job: ClaimedJob): Promise<void> {
active.set(job.id, entry);
const watcher = watchJob(job.id, entry);
try {
- if (job.kind === "export" || job.kind === "preview") {
+ if (job.kind === "export" || job.kind === "preview" || job.kind === "card") {
const { outputKey, outName } = await runExportJob(job, handle);
await prisma.cutRenderJob.updateMany({
where: { id: job.id, state: "running" },
diff --git a/site/src/cut/worker/r2.ts b/site/src/cut/worker/r2.ts
index 0916547b..a85e036b 100644
--- a/site/src/cut/worker/r2.ts
+++ b/site/src/cut/worker/r2.ts
@@ -15,6 +15,7 @@ import {
// routes can never drift apart.
export {
+ projectCardKey as cardKey,
projectExportKey as exportKey,
projectMediaKey as mediaKey,
projectPreviewKey as previewKey,