Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

improve: reduce share page and video startup latency

Richie McIlroyf80e097e2cd0
diff --git a/apps/web/__tests__/unit/playback-source.test.ts b/apps/web/__tests__/unit/playback-source.test.ts
index 86736b64c..a3c9ce976 100644
--- a/apps/web/__tests__/unit/playback-source.test.ts
+++ b/apps/web/__tests__/unit/playback-source.test.ts
@@ -101,6 +101,128 @@ describe("canPlayRawContentType", () => {
});
describe("resolvePlaybackSource", () => {
+ it("uses the page's signed URL without a playlist request or changing its signature", async () => {
+ const initialUrl =
+ "https://bucket.s3.amazonaws.com/result.mp4?signature=abc";
+ const fetchImpl = vi.fn<typeof fetch>().mockResolvedValueOnce(
+ createResponse(initialUrl, {
+ status: 206,
+ redirected: false,
+ }),
+ );
+ expect(
+ await resolvePlaybackSource({
+ videoSrc: "/api/playlist?videoType=mp4",
+ initialUrl,
+ enableCrossOrigin: true,
+ fetchImpl,
+ now: () => 123,
+ }),
+ ).toEqual({ url: initialUrl, type: "mp4", supportsCrossOrigin: true });
+ expect(fetchImpl).toHaveBeenCalledExactlyOnceWith(initialUrl, {
+ headers: { range: "bytes=0-0" },
+ });
+ });
+
+ it.each([401, 403, 404, 500])(
+ "refreshes a failed initial URL through the authorized playlist route (HTTP %s)",
+ async (status) => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response(null, { status }))
+ .mockResolvedValueOnce(
+ createResponse("https://media.example.com/fresh.mp4", {
+ status: 206,
+ redirected: true,
+ }),
+ );
+ expect(
+ await resolvePlaybackSource({
+ videoSrc: "/api/playlist?videoType=mp4",
+ initialUrl: "https://media.example.com/expired.mp4",
+ fetchImpl,
+ now: () => 123,
+ }),
+ ).toMatchObject({
+ url: "https://media.example.com/fresh.mp4",
+ type: "mp4",
+ });
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ expect(fetchImpl).toHaveBeenLastCalledWith(
+ "/api/playlist?videoType=mp4&_t=123",
+ { headers: { range: "bytes=0-0" } },
+ );
+ },
+ );
+
+ it("uses native playback without repeating a CORS-blocked signed probe", async () => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockRejectedValue(new TypeError("CORS"));
+ expect(
+ await resolvePlaybackSource({
+ videoSrc: "/api/playlist?videoType=mp4",
+ initialUrl: "https://media.example.com/result.mp4",
+ fetchImpl,
+ enableCrossOrigin: true,
+ now: () => 123,
+ }),
+ ).toEqual({
+ url: "/api/playlist?videoType=mp4&_t=123",
+ type: "mp4",
+ supportsCrossOrigin: false,
+ });
+ expect(fetchImpl).toHaveBeenCalledExactlyOnceWith(
+ "https://media.example.com/result.mp4",
+ { headers: { range: "bytes=0-0" } },
+ );
+ });
+
+ it("preserves the raw fallback after the initial and refreshed MP4 are missing", async () => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response(null, { status: 404 }))
+ .mockResolvedValueOnce(new Response(null, { status: 404 }))
+ .mockResolvedValueOnce(
+ createResponse("https://media.example.com/raw.webm", {
+ status: 206,
+ headers: { "content-type": "video/webm" },
+ redirected: true,
+ }),
+ );
+ expect(
+ await resolvePlaybackSource({
+ videoSrc: "/api/playlist?videoType=mp4",
+ initialUrl: "https://media.example.com/result.mp4",
+ rawFallbackSrc: "/api/playlist?videoType=raw-preview",
+ fetchImpl,
+ createVideoElement: () => ({ canPlayType: () => "probably" }),
+ }),
+ ).toMatchObject({ type: "raw", url: "https://media.example.com/raw.webm" });
+ });
+
+ it("does not retry the initial MP4 when switching to raw playback", async () => {
+ const fetchImpl = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(
+ createResponse("https://media.example.com/raw.mp4", { status: 206 }),
+ );
+ expect(
+ await resolvePlaybackSource({
+ videoSrc: "/api/playlist?videoType=mp4",
+ initialUrl: "https://media.example.com/result.mp4",
+ rawFallbackSrc: "/api/playlist?videoType=raw-preview",
+ preferredSource: "raw",
+ fetchImpl,
+ now: () => 123,
+ }),
+ ).toMatchObject({ type: "raw" });
+ expect(fetchImpl).toHaveBeenCalledExactlyOnceWith(
+ "/api/playlist?videoType=raw-preview&_t=123",
+ { headers: { range: "bytes=0-0" } },
+ );
+ });
+
it.each([200, 206, 404])(
"closes the probe body after reading HTTP %s headers",
async (status) => {
diff --git a/apps/web/__tests__/unit/share-page-loading.test.ts b/apps/web/__tests__/unit/share-page-loading.test.ts
new file mode 100644
index 000000000..5d708320a
--- /dev/null
+++ b/apps/web/__tests__/unit/share-page-loading.test.ts
@@ -0,0 +1,272 @@
+import { Context, Effect, Option } from "effect";
+import { isValidElement, type ReactElement } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ select: vi.fn(),
+ policy: vi.fn(),
+ reconcile: vi.fn(),
+ playbackUrl: vi.fn(),
+ quota: vi.fn(),
+ user: vi.fn(),
+ sharedOrganizations: [] as {
+ id: string;
+ name: string;
+ organizationId: string;
+ }[],
+}));
+
+vi.mock("@cap/database", () => ({ db: () => ({ select: mocks.select }) }));
+vi.mock("@cap/database/auth/session", () => ({ getCurrentUser: mocks.user }));
+vi.mock("@cap/env", () => ({
+ buildEnv: { NEXT_PUBLIC_WEB_URL: "https://cap.so" },
+ serverEnv: () => ({}),
+}));
+vi.mock("@cap/ui", () => ({ Logo: () => null }));
+vi.mock("@cap/utils", () => ({ userIsPro: () => false }));
+vi.mock("@cap/web-backend", () => ({
+ Database: Context.GenericTag("ShareTestDatabase"),
+ ImageUploads: Context.GenericTag("ShareTestImages"),
+ Videos: Context.GenericTag("ShareTestVideos"),
+ provideOptionalAuth: <A, E, R>(effect: Effect.Effect<A, E, R>) => effect,
+ resolveEffectiveVideoRules: () => ({
+ settings: {},
+ hasInheritedPassword: false,
+ inheritedPasswordSources: [],
+ inheritedSettings: {},
+ }),
+}));
+vi.mock("@cap/web-backend/src/Videos/VideosPolicy", () => ({
+ VideosPolicy: Context.GenericTag("ShareTestPolicy"),
+}));
+vi.mock("@/lib/server", () => ({
+ runPromise: <A, E>(effect: Effect.Effect<A, E, unknown>) =>
+ effect.pipe(
+ Effect.provideService(Context.GenericTag("ShareTestPolicy"), {
+ canViewLoaded: mocks.policy,
+ }),
+ Effect.provideService(Context.GenericTag("ShareTestDatabase"), {
+ use: () => Effect.succeed([]),
+ }),
+ Effect.provideService(Context.GenericTag("ShareTestImages"), {
+ resolveImageUrl: (url: string) => Effect.succeed(url),
+ }),
+ Effect.provideService(Context.GenericTag("ShareTestVideos"), {
+ getThumbnailURL: () =>
+ Effect.succeed(Option.some("https://media.example.com/image.jpg")),
+ }),
+ Effect.runPromise,
+ ),
+}));
+vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
+vi.mock("next/navigation", () => ({
+ notFound: () => {
+ throw new Error("NOT_FOUND");
+ },
+}));
+vi.mock("@/actions/videos/get-analytics", () => ({
+ getVideoAnalytics: async () => ({ count: 12 }),
+}));
+vi.mock("@/app/(org)/dashboard/dashboard-data", () => ({
+ getDashboardSpacesData: async () => [],
+}));
+vi.mock("@/lib/ai/provider", () => ({ isAiConfigured: () => false }));
+vi.mock("@/lib/desktop-segments-recovery", () => ({
+ completeDesktopSegmentsManifestAndQueue: vi.fn(),
+}));
+vi.mock("@/lib/Notification", () => ({ createNotification: vi.fn() }));
+vi.mock("@/lib/public-share-video", () => ({ getPublicShareVideo: vi.fn() }));
+vi.mock("@/lib/share-playback", () => ({
+ getSharePlaybackUrl: mocks.playbackUrl,
+}));
+vi.mock("@/lib/shareable-link-quota", () => ({
+ isVideoOverShareableLinkLimit: mocks.quota,
+}));
+vi.mock("@/lib/share-web-url", () => ({ resolveShareWebUrl: vi.fn() }));
+vi.mock("@/lib/transcribe", () => ({ transcribeVideo: vi.fn() }));
+vi.mock("@/lib/video-download-permissions", () => ({
+ canUserDownloadVideo: async () => false,
+}));
+vi.mock("@/lib/video-edit-processing", () => ({
+ isEditSourceKey: ({ rawFileKey }: { rawFileKey: string | null }) =>
+ rawFileKey === "owner/video/source/original.mp4",
+ reconcileStaleEditUpload: mocks.reconcile,
+}));
+vi.mock("@/utils/flags", () => ({ isAiGenerationEnabled: async () => false }));
+vi.mock("@/app/s/[videoId]/_components/PasswordOverlay", () => ({
+ PasswordOverlay: () => null,
+}));
+vi.mock("@/app/s/[videoId]/_components/PendingRecordingShare", () => ({
+ PendingRecordingShare: () => null,
+}));
+vi.mock("@/app/s/[videoId]/_components/ShareHeader", () => ({
+ ShareHeader: () => null,
+}));
+vi.mock("@/app/s/[videoId]/Share", () => ({ Share: () => null }));
+
+import ShareVideoPage from "@/app/s/[videoId]/page";
+
+const createVideo = () => ({
+ id: "video",
+ name: "Recording",
+ ownerId: "owner",
+ owner: { id: "owner", image: null },
+ orgId: "organization",
+ public: true,
+ password: null,
+ source: { type: "desktopMP4" },
+ isScreenshot: false,
+ hasActiveUpload: false,
+ activeUploadRawFileKey: null as string | null,
+ organizationTombstoneAt: null as Date | null,
+ metadata: null,
+ transcriptionStatus: "COMPLETE",
+ createdAt: new Date("2026-09-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-09-01T00:00:00.000Z"),
+});
+
+function arrangeRows(rows: ReturnType<typeof createVideo>[]) {
+ mocks.select.mockImplementation((selection: Record<string, unknown>) => {
+ const result =
+ "ownerId" in selection
+ ? rows
+ : "organizationId" in selection && !("settings" in selection)
+ ? mocks.sharedOrganizations
+ : [];
+ const query = {
+ from: () => query,
+ leftJoin: () => query,
+ innerJoin: () => query,
+ where: () => Promise.resolve(result),
+ };
+ return query;
+ });
+}
+
+const renderPage = () =>
+ ShareVideoPage({
+ params: Promise.resolve({ videoId: "video" }),
+ searchParams: Promise.resolve({}),
+ });
+
+async function renderAuthorizedContent() {
+ const page = (await renderPage()) as ReactElement<{ children: unknown[] }>;
+ const content = page.props.children[1];
+ if (!isValidElement(content) || typeof content.type !== "function") {
+ throw new Error("Expected authorized share content");
+ }
+ return (await (content.type as (props: unknown) => Promise<unknown>)(
+ content.props,
+ )) as ReactElement<{
+ children: ReactElement<{
+ initialPlaybackUrl?: Promise<string | null>;
+ data: { sharedOrganizations: unknown[]; ownerIsOverShareLimit: boolean };
+ }>;
+ }>;
+}
+
+describe("share page loading", () => {
+ beforeEach(() => {
+ mocks.policy.mockReturnValue(Effect.void);
+ mocks.reconcile.mockResolvedValue(false);
+ mocks.playbackUrl.mockResolvedValue("https://media.example.com/result.mp4");
+ mocks.quota.mockResolvedValue(false);
+ mocks.user.mockResolvedValue(null);
+ mocks.sharedOrganizations = [];
+ arrangeRows([createVideo()]);
+ });
+
+ it("reuses the organization sharing query for the header and video data", async () => {
+ mocks.sharedOrganizations = [
+ { id: "shared", organizationId: "shared", name: "Shared team" },
+ ];
+ const content = await renderAuthorizedContent();
+ expect(content.props.children.props.data.sharedOrganizations).toEqual([
+ { id: "shared", name: "Shared team" },
+ ]);
+ expect(mocks.select).toHaveBeenCalledTimes(3);
+ });
+
+ it("does not expose videos belonging to a deleted organization", async () => {
+ arrangeRows([{ ...createVideo(), organizationTombstoneAt: new Date() }]);
+ await expect(renderPage()).rejects.toThrow("NOT_FOUND");
+ expect(mocks.playbackUrl).not.toHaveBeenCalled();
+ });
+
+ it("loads ordinary recordings once and authorizes the exact loaded row", async () => {
+ await renderPage();
+ expect(mocks.select).toHaveBeenCalledOnce();
+ expect(mocks.reconcile).not.toHaveBeenCalled();
+ expect(mocks.policy).toHaveBeenCalledExactlyOnceWith(
+ createVideo(),
+ Option.none(),
+ );
+ });
+
+ it("retains stale edit recovery and reloads the row after recovery changes it", async () => {
+ arrangeRows([
+ {
+ ...createVideo(),
+ activeUploadRawFileKey: "owner/video/source/original.mp4",
+ },
+ ]);
+ mocks.reconcile.mockImplementation(async () => {
+ arrangeRows([createVideo()]);
+ return true;
+ });
+ await renderPage();
+ expect(mocks.select).toHaveBeenCalledTimes(2);
+ expect(mocks.policy).toHaveBeenCalledExactlyOnceWith(
+ createVideo(),
+ Option.none(),
+ );
+ });
+
+ it("does not sign playback URLs before private-video authorization succeeds", async () => {
+ mocks.policy.mockReturnValue(Effect.fail({ _tag: "PolicyDenied" }));
+ await renderPage();
+ expect(mocks.playbackUrl).not.toHaveBeenCalled();
+ });
+
+ it("keeps password-protected videos behind the password overlay", async () => {
+ mocks.policy.mockReturnValue(
+ Effect.fail({ _tag: "VerifyVideoPasswordError" }),
+ );
+ const page = (await renderPage()) as ReactElement<{
+ children: [ReactElement<{ isOpen: boolean }>, boolean];
+ }>;
+ expect(page.props.children[0].props.isOpen).toBe(true);
+ expect(page.props.children[1]).toBe(false);
+ expect(mocks.playbackUrl).not.toHaveBeenCalled();
+ });
+
+ it("streams the authorized MP4 URL without waiting for signing to finish", async () => {
+ mocks.playbackUrl.mockReturnValue(new Promise(() => {}));
+ const content = await renderAuthorizedContent();
+ expect(content.props.children.props.initialPlaybackUrl).toBeInstanceOf(
+ Promise,
+ );
+ expect(mocks.playbackUrl).toHaveBeenCalledOnce();
+ });
+
+ it("does not sign media hidden by the shareable link quota", async () => {
+ mocks.quota.mockResolvedValue(true);
+ const content = await renderAuthorizedContent();
+ expect(await content.props.children.props.initialPlaybackUrl).toBeNull();
+ expect(content.props.children.props.data.ownerIsOverShareLimit).toBe(true);
+ expect(mocks.playbackUrl).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { isScreenshot: true },
+ { hasActiveUpload: true },
+ { source: { type: "desktopSegments" } },
+ { source: { type: "local" } },
+ { source: { type: "MediaConvert" } },
+ ])("retains the existing player resolution for %j", async (changes) => {
+ arrangeRows([{ ...createVideo(), ...changes }]);
+ const content = await renderAuthorizedContent();
+ expect(content.props.children.props.initialPlaybackUrl).toBeUndefined();
+ expect(mocks.playbackUrl).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/share-playback.test.ts b/apps/web/__tests__/unit/share-playback.test.ts
new file mode 100644
index 000000000..1b6c9e87d
--- /dev/null
+++ b/apps/web/__tests__/unit/share-playback.test.ts
@@ -0,0 +1,104 @@
+import { Effect, Option } from "effect";
+import { describe, expect, it, vi } from "vitest";
+import { getSharePlaybackUrl } from "@/lib/share-playback";
+
+const mocks = vi.hoisted(() => ({
+ access: vi.fn(),
+ sign: vi.fn(),
+}));
+
+vi.mock("@cap/web-backend", () => ({
+ Storage: { getAccessForVideo: mocks.access },
+}));
+
+vi.mock("@/lib/server", () => ({ runPromise: Effect.runPromise }));
+
+const video = {
+ id: "video",
+ owner: { id: "owner" },
+ orgId: "organization",
+ name: "Recording",
+ public: true,
+ source: { type: "desktopMP4" },
+ metadata: null,
+ bucket: "custom-bucket",
+ storageIntegrationId: null,
+ transcriptionStatus: "COMPLETE",
+ width: 1920,
+ height: 1080,
+ duration: 60,
+ createdAt: new Date("2026-09-09T00:00:00.000Z"),
+ updatedAt: new Date("2026-09-09T00:00:00.000Z"),
+} as unknown as Parameters<typeof getSharePlaybackUrl>[0];
+
+describe("share page playback URL", () => {
+ it.each(["desktopMP4", "webMP4"] as const)(
+ "resolves %s through the existing storage access using the loaded video",
+ async (type) => {
+ mocks.sign.mockReturnValue(
+ Effect.succeed("https://media.example.com/video.mp4"),
+ );
+ mocks.access.mockReturnValue(
+ Effect.succeed([{ getSignedObjectUrl: mocks.sign }, Option.none()]),
+ );
+ expect(await getSharePlaybackUrl({ ...video, source: { type } })).toBe(
+ "https://media.example.com/video.mp4",
+ );
+ expect(mocks.access).toHaveBeenCalledOnce();
+ expect(mocks.access.mock.calls[0]?.[0]).toMatchObject({
+ id: "video",
+ ownerId: "owner",
+ bucketId: Option.some("custom-bucket"),
+ source: { type },
+ });
+ expect(mocks.sign).toHaveBeenCalledExactlyOnceWith(
+ "owner/video/result.mp4",
+ );
+ },
+ );
+
+ it("retains the published output key and Google Drive integration for storage resolution", async () => {
+ mocks.sign.mockReturnValue(
+ Effect.succeed("https://media.example.com/output.mp4"),
+ );
+ mocks.access.mockReturnValue(
+ Effect.succeed([{ getSignedObjectUrl: mocks.sign }, Option.none()]),
+ );
+ const publishedVideo = {
+ ...video,
+ storageIntegrationId: "drive-integration" as NonNullable<
+ typeof video.storageIntegrationId
+ >,
+ source: {
+ type: "desktopMP4" as const,
+ outputKey: "owner/video/.recording/outputs/generation/result.mp4",
+ },
+ };
+ await getSharePlaybackUrl(publishedVideo);
+ expect(mocks.access.mock.calls[0]?.[0]).toMatchObject({
+ source: publishedVideo.source,
+ storageIntegrationId: Option.some("drive-integration"),
+ });
+ });
+
+ it("allows the player to use its existing route when storage resolution fails", async () => {
+ mocks.access.mockReturnValue(Effect.fail(new Error("Storage unavailable")));
+ expect(await getSharePlaybackUrl(video)).toBeNull();
+ expect(mocks.sign).not.toHaveBeenCalled();
+ });
+
+ it("keeps signing defects out of the streamed page", async () => {
+ mocks.access.mockReturnValue(Effect.die(new Error("Signer configuration")));
+ expect(await getSharePlaybackUrl(video)).toBeNull();
+ });
+
+ it("does not resolve storage when the loaded source is invalid", async () => {
+ expect(
+ await getSharePlaybackUrl({
+ ...video,
+ name: null,
+ } as unknown as typeof video),
+ ).toBeNull();
+ expect(mocks.access).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index 2917c8a34..92cf33f03 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -184,6 +184,7 @@ type TranscriptionStatus =
interface ShareProps {
data: VideoData;
+ initialPlaybackUrl?: Promise<string | null>;
comments: MaybePromise<CommentWithAuthor[]>;
views: MaybePromise<number>;
screenshotImageUrl?: string | null;
@@ -319,6 +320,7 @@ const useVideoStatus = (
export const Share = ({
data,
+ initialPlaybackUrl,
comments,
views,
screenshotImageUrl,
@@ -959,6 +961,7 @@ export const Share = ({
/>
) : (
<ShareVideo
+ initialPlaybackUrl={initialPlaybackUrl}
data={shareVideoData}
comments={comments}
areChaptersDisabled={areChaptersDisabled}
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
index a72d05eb4..60901846a 100644
--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -93,6 +93,7 @@ interface CaptionOption {
interface Props {
videoSrc: string;
+ initialPlaybackUrl?: Promise<string | null>;
rawFallbackSrc?: string;
videoId: Video.VideoId;
chaptersSrc: string;
@@ -141,6 +142,7 @@ interface Props {
export function CapVideoPlayer({
videoSrc,
+ initialPlaybackUrl,
rawFallbackSrc,
videoId,
chaptersSrc,
@@ -191,6 +193,9 @@ export function CapVideoPlayer({
null,
);
const queryClient = useQueryClient();
+ const initialPlaybackUrlUsed = useRef<Promise<string | null> | undefined>(
+ undefined,
+ );
useEffect(() => {
const checkMobile = () => {
@@ -240,13 +245,22 @@ export function CapVideoPlayer({
],
queryFn: shouldDeferResolvedSource
? skipToken
- : () =>
- resolvePlaybackSource({
+ : async () => {
+ const useInitialUrl =
+ preferredSource === "mp4" &&
+ initialPlaybackUrl !== initialPlaybackUrlUsed.current;
+ if (useInitialUrl)
+ initialPlaybackUrlUsed.current = initialPlaybackUrl;
+ return resolvePlaybackSource({
videoSrc,
+ initialUrl: useInitialUrl
+ ? await initialPlaybackUrl?.catch(() => null)
+ : undefined,
rawFallbackSrc,
enableCrossOrigin,
preferredSource,
- }),
+ });
+ },
refetchOnWindowFocus: false,
staleTime: Number.POSITIVE_INFINITY,
retry: false,
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 0cc8ff064..06eee253f 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -79,6 +79,7 @@ export const ShareVideo = forwardRef<
data: VideoData & {
hasActiveUpload?: boolean;
};
+ initialPlaybackUrl?: Promise<string | null>;
comments: MaybePromise<CommentWithAuthor[]>;
chapters?: { title: string; start: number }[];
areChaptersDisabled?: boolean;
@@ -102,6 +103,7 @@ export const ShareVideo = forwardRef<
(
{
data,
+ initialPlaybackUrl,
comments,
chapters = NO_CHAPTERS,
areCaptionsDisabled,
@@ -546,6 +548,7 @@ export const ShareVideo = forwardRef<
)}
videoSrc={videoSrc}
rawFallbackSrc={rawFallbackSrc}
+ initialPlaybackUrl={initialPlaybackUrl}
duration={data.duration}
defaultPlaybackSpeed={defaultPlaybackSpeed}
showPlaybackStatusBadge={showPlaybackStatusBadge}
diff --git a/apps/web/app/s/[videoId]/_components/playback-source.ts b/apps/web/app/s/[videoId]/_components/playback-source.ts
index 96a858b76..817b93ad1 100644
--- a/apps/web/app/s/[videoId]/_components/playback-source.ts
+++ b/apps/web/app/s/[videoId]/_components/playback-source.ts
@@ -20,6 +20,7 @@ type ProbeOutcome = ProbeFailure | ProbeResult;
type ResolvePlaybackSourceInput = {
videoSrc: string;
+ initialUrl?: string | null;
rawFallbackSrc?: string;
enableCrossOrigin?: boolean;
fetchImpl?: typeof fetch;
@@ -57,8 +58,9 @@ async function probePlaybackSource(
url: string,
fetchImpl: typeof fetch,
now: () => number,
+ cacheBust = true,
): Promise<ProbeOutcome> {
- const requestUrl = appendCacheBust(url, now());
+ const requestUrl = cacheBust ? appendCacheBust(url, now()) : url;
try {
const response = await fetchImpl(requestUrl, {
@@ -131,6 +133,7 @@ export function shouldFallbackToRawPlaybackSource(
export async function resolvePlaybackSource({
videoSrc,
+ initialUrl,
rawFallbackSrc,
enableCrossOrigin = false,
fetchImpl = fetch,
@@ -170,6 +173,31 @@ export async function resolvePlaybackSource({
const rawSource = await resolveRaw();
if (rawSource) return rawSource;
}
+ if (preferredSource === "mp4" && initialUrl) {
+ const initialResult = await probePlaybackSource(
+ initialUrl,
+ fetchImpl,
+ now,
+ false,
+ );
+ if (isProbeResult(initialResult)) {
+ return {
+ url: initialResult.url,
+ type: "mp4",
+ supportsCrossOrigin: enableCrossOrigin,
+ };
+ }
+ if (
+ initialResult.reason === "network-error" &&
+ canUseUnprobedSource(videoSrc)
+ ) {
+ return {
+ url: appendCacheBust(videoSrc, now()),
+ type: "mp4",
+ supportsCrossOrigin: false,
+ };
+ }
+ }
const mp4Result = await probePlaybackSource(videoSrc, fetchImpl, now);
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index c803a6e83..24dd3edc8 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -56,6 +56,7 @@ import { getPublicShareVideo } from "@/lib/public-share-video";
import * as EffectRuntime from "@/lib/server";
import { runPromise } from "@/lib/server";
import { getSharePageBranding } from "@/lib/share-branding";
+import { getSharePlaybackUrl } from "@/lib/share-playback";
import { buildShareVideoMetadata } from "@/lib/share-video-metadata";
import { resolveShareWebUrl } from "@/lib/share-web-url";
import { isVideoOverShareableLinkLimit } from "@/lib/shareable-link-quota";
@@ -180,7 +181,10 @@ async function getSharedSpacesForVideo(videoId: Video.VideoId) {
});
});
- return sharedSpaces;
+ return {
+ sharedSpaces,
+ sharedOrganizations: orgSharing.map(({ id, name }) => ({ id, name })),
+ };
}
function PolicyDeniedView({ reason }: { reason?: string }) {
@@ -328,12 +332,9 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
const awaitRecording =
isValidVideoIdParam(videoId) && hasRecordingStoppedParam(searchParams);
- await reconcileStaleEditUpload(videoId);
-
return Effect.gen(function* () {
const videosPolicy = yield* VideosPolicy;
-
- const [row] = yield* Effect.promise(() =>
+ const loadVideo = () =>
db()
.select({
id: videos.id,
@@ -386,13 +387,20 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {
.innerJoin(users, eq(videos.ownerId, users.id))
.leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
.leftJoin(organizations, eq(videos.orgId, organizations.id))
- .where(eq(videos.id, videoId)),
- );
+ .where(eq(videos.id, videoId));
+ let [row] = yield* Effect.promise(loadVideo);
+ if (
+ row &&
+ isEditSourceKey({
+ ownerId: row.ownerId,
+ videoId,
+ rawFileKey: row.activeUploadRawFileKey,
+ }) &&
+ (yield* Effect.promise(() => reconcileStaleEditUpload(videoId)))
+ ) {
+ [row] = yield* Effect.promise(loadVideo);
+ }
- // The access decision runs on the row already loaded above instead of
- // re-reading it, and stays ahead of the tombstone check so a denied or
- // password-gated video on a deleted org still resolves the way it did
- // when the policy ran before the select.
if (row) {
yield* videosPolicy.canViewLoaded(row, Option.fromNullable(row.password));
}
@@ -486,17 +494,16 @@ async function AuthorizedContent({
!hasActiveUpload &&
Date.now() - video.updatedAt.getTime() >= VIEW_NOTIFICATION_DELAY_MS;
- if (user && video && user.id !== video.owner.id && canRegisterView) {
- try {
- await createNotification({
- type: "view",
- videoId: video.id,
- authorId: user.id,
- });
- } catch (error) {
- console.warn("Failed to create view notification:", error);
- }
- }
+ const viewNotificationPromise =
+ user && user.id !== video.owner.id && canRegisterView
+ ? createNotification({
+ type: "view",
+ videoId: video.id,
+ authorId: user.id,
+ }).catch((error) => {
+ console.warn("Failed to create view notification:", error);
+ })
+ : Promise.resolve();
const userId = user?.id;
const commentId = optionFromTOrFirst(searchParams.comment).pipe(
@@ -536,8 +543,30 @@ async function AuthorizedContent({
);
return false;
});
+ const initialPlaybackUrlPromise =
+ !video.isScreenshot &&
+ !hasActiveUpload &&
+ (video.source.type === "desktopMP4" || video.source.type === "webMP4")
+ ? overShareLimitPromise.then((overLimit) =>
+ overLimit ? null : getSharePlaybackUrl(video),
+ )
+ : undefined;
const aiGenerationEnabledPromise = isAiGenerationEnabled(video.owner);
+ const imagesPromise = Effect.gen(function* () {
+ const imageUploads = yield* ImageUploads;
+ const resolveImage = (
+ image: ImageUpload.ImageUrlOrKey | null | undefined,
+ ) => (image ? imageUploads.resolveImageUrl(image) : Effect.succeed(null));
+ return yield* Effect.all(
+ {
+ owner: resolveImage(video.owner.image),
+ organization: resolveImage(video.organizationIconUrl),
+ shareableLink: resolveImage(video.shareableLinkIconUrl),
+ },
+ { concurrency: 3 },
+ );
+ }).pipe(runPromise);
const screenshotImageUrlPromise = video.isScreenshot
? Effect.flatMap(Videos, (videos) => videos.getThumbnailURL(videoId)).pipe(
@@ -547,7 +576,7 @@ async function AuthorizedContent({
: Promise.resolve(null);
const customDomainPromise = (async () => {
- if (!user) {
+ if (!user || user.id !== video.owner.id) {
return { customDomain: null, domainVerified: false };
}
const activeOrganizationId = user.activeOrganizationId;
@@ -576,12 +605,6 @@ async function AuthorizedContent({
return { customDomain: null, domainVerified: false };
})();
- const sharedOrganizationsPromise = db()
- .select({ id: sharedVideos.organizationId, name: organizations.name })
- .from(sharedVideos)
- .innerJoin(organizations, eq(sharedVideos.organizationId, organizations.id))
- .where(eq(sharedVideos.videoId, videoId));
-
const userOrganizationsPromise = (async () => {
if (!userId) return [];
@@ -759,17 +782,17 @@ async function AuthorizedContent({
const [
spacesData,
- sharedSpaces,
+ { sharedSpaces, sharedOrganizations },
aiGenerationEnabled,
screenshotImageUrl,
membersList,
userOrganizations,
- sharedOrganizations,
{ customDomain, domainVerified },
canManageSharePageBranding,
canDownloadVideo,
videoHasEdits,
ownerIsOverShareLimit,
+ resolvedImages,
] = await Promise.all([
spacesDataPromise,
sharedSpacesPromise,
@@ -777,12 +800,13 @@ async function AuthorizedContent({
screenshotImageUrlPromise,
membersListPromise,
userOrganizationsPromise,
- sharedOrganizationsPromise,
customDomainPromise,
canManageSharePageBrandingPromise,
canDownloadVideoPromise,
videoHasEditsPromise,
overShareLimitPromise,
+ imagesPromise,
+ viewNotificationPromise,
]);
const rules = resolveEffectiveVideoRules({
@@ -827,42 +851,32 @@ async function AuthorizedContent({
aiGenerationStatus,
};
- const videoWithOrganizationInfo = await Effect.gen(function* () {
- const imageUploads = yield* ImageUploads;
-
- return {
- ...video,
- hasActiveUpload,
- ownerIsOverShareLimit,
- owner: {
- id: video.owner.id,
- name: video.owner.name,
- isPro: ownerIsPro,
- image: video.owner.image
- ? yield* imageUploads.resolveImageUrl(video.owner.image)
- : null,
- },
- organization: {
- organizationMembers: membersList.map((member) => member.userId),
- organizationId: video.sharedOrganization?.organizationId ?? undefined,
- },
- sharedOrganizations: sharedOrganizations,
- password: null,
- folderId: null,
- orgSettings: video.orgSettings || null,
- organizationName: video.organizationName,
- organizationIconUrl: video.organizationIconUrl
- ? yield* imageUploads.resolveImageUrl(video.organizationIconUrl)
- : null,
- shareableLinkIconUrl: video.shareableLinkIconUrl
- ? yield* imageUploads.resolveImageUrl(video.shareableLinkIconUrl)
- : null,
- settings: rules.settings,
- hasInheritedPassword: rules.hasInheritedPassword,
- inheritedPasswordSources: rules.inheritedPasswordSources,
- inheritedSpaceSettings: rules.inheritedSettings,
- };
- }).pipe(runPromise);
+ const videoWithOrganizationInfo = {
+ ...video,
+ hasActiveUpload,
+ ownerIsOverShareLimit,
+ owner: {
+ id: video.owner.id,
+ name: video.owner.name,
+ isPro: ownerIsPro,
+ image: resolvedImages.owner,
+ },
+ organization: {
+ organizationMembers: membersList.map((member) => member.userId),
+ organizationId: video.sharedOrganization?.organizationId ?? undefined,
+ },
+ sharedOrganizations: sharedOrganizations,
+ password: null,
+ folderId: null,
+ orgSettings: video.orgSettings || null,
+ organizationName: video.organizationName,
+ organizationIconUrl: resolvedImages.organization,
+ shareableLinkIconUrl: resolvedImages.shareableLink,
+ settings: rules.settings,
+ hasInheritedPassword: rules.hasInheritedPassword,
+ inheritedPasswordSources: rules.inheritedPasswordSources,
+ inheritedSpaceSettings: rules.inheritedSettings,
+ };
const isEditProcessing =
isEditSourceKey({
ownerId: video.owner.id,
@@ -919,6 +933,7 @@ async function AuthorizedContent({
/>
}
data={videoWithOrganizationInfo}
+ initialPlaybackUrl={initialPlaybackUrlPromise}
screenshotImageUrl={screenshotImageUrl}
videoSettings={videoWithOrganizationInfo.settings}
comments={commentsPromise}
diff --git a/apps/web/lib/share-playback.ts b/apps/web/lib/share-playback.ts
new file mode 100644
index 000000000..00da54028
--- /dev/null
+++ b/apps/web/lib/share-playback.ts
@@ -0,0 +1,28 @@
+import type { videos } from "@cap/database/schema";
+import { Storage } from "@cap/web-backend";
+import { type User, Video } from "@cap/web-domain";
+import { Effect, Schema } from "effect";
+import { runPromise } from "@/lib/server";
+
+type SharePlaybackVideo = Omit<
+ typeof videos.$inferSelect,
+ "folderId" | "password" | "settings" | "ownerId"
+> & { owner: { id: User.UserId } };
+
+export const getSharePlaybackUrl = (video: SharePlaybackVideo) =>
+ Effect.gen(function* () {
+ const loadedVideo = yield* Schema.decodeUnknown(Video.Video)({
+ ...video,
+ ownerId: video.owner.id,
+ bucketId: video.bucket,
+ folderId: null,
+ createdAt: video.createdAt.toISOString(),
+ updatedAt: video.updatedAt.toISOString(),
+ });
+ const [bucket] = yield* Storage.getAccessForVideo(loadedVideo);
+ return yield* bucket.getSignedObjectUrl(
+ `${video.owner.id}/${video.id}/result.mp4`,
+ );
+ })
+ .pipe(runPromise)
+ .catch(() => null);