Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

13.4 KB
Raw Blame
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import {
	comments,
	organizations,
	sharedVideos,
	spaces,
	spaceVideos,
	users,
	videos,
	videoUploads,
} from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { buildEnv } from "@cap/env";
import { Logo } from "@cap/ui";
import { userIsPro } from "@cap/utils";
import {
	ImageUploads,
	provideOptionalAuth,
	resolveEffectiveVideoRules,
	Videos,
	VideosPolicy,
} from "@cap/web-backend";
import { type Organisation, Policy, Video } from "@cap/web-domain";
import { and, eq, isNull, sql } from "drizzle-orm";
import { Effect, Option } from "effect";
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { after } from "next/server";
import {
	getPendingLoomProcessing,
	startDeferredLoomProcessing,
} from "@/lib/loom-deferred-processing";
import { resolveDefaultPlaybackSpeed } from "@/lib/playback-speed";
import * as EffectRuntime from "@/lib/server";
import { getSharePageBranding } from "@/lib/share-branding";
import { parseShareCallToAction } from "@/lib/share-call-to-action";
import { buildShareVideoMetadata } from "@/lib/share-video-metadata";
import { isVideoOverShareableLinkLimit } from "@/lib/shareable-link-quota";
import { transcribeVideo } from "@/lib/transcribe";
import { isAiGenerationEnabled } from "@/utils/flags";
import { EmbedVideo } from "./_components/EmbedVideo";
import { PasswordOverlay } from "./_components/PasswordOverlay";

export async function generateMetadata(
	props: PageProps<"/embed/[videoId]">,
): Promise<Metadata> {
	const params = await props.params;
	const videoId = params.videoId as Video.VideoId;

	return Effect.flatMap(Videos, (v) => v.getByIdForViewing(videoId)).pipe(
		Effect.map(
			Option.match({
				onNone: () => notFound(),
				onSome: ([video]) => ({
					...buildShareVideoMetadata({
						videoId,
						name: video.name,
						sourceType: video.source.type,
						width: Option.getOrNull(video.width),
						height: Option.getOrNull(video.height),
						webUrl: buildEnv.NEXT_PUBLIC_WEB_URL,
					}),
					robots: "index, follow",
				}),
			}),
		),
		Effect.catchTags({
			PolicyDenied: () =>
				Effect.succeed({
					title: "Cap: This video is private",
					description: "This video is private and cannot be shared.",
					robots: "noindex, nofollow",
				}),
			VerifyVideoPasswordError: () =>
				Effect.succeed({
					title: "Cap: Password Protected Video",
					description: "This video is password protected.",
					robots: "noindex, nofollow",
				}),
		}),
		provideOptionalAuth,
		EffectRuntime.runPromise,
	);
}

const renderEmbedPolicyDenied = () =>
	Effect.succeed(
		<div className="flex flex-col justify-center items-center min-h-screen text-center text-white bg-black">
			<h1 className="mb-4 text-2xl font-bold">This video is private</h1>
			<p className="text-gray-400">
				If you own this video, please <Link href="/login">sign in</Link> to
				manage sharing.
			</p>
		</div>,
	);

const renderNoSuchElement = () => Effect.sync(() => notFound());

export default async function EmbedVideoPage(
	props: PageProps<"/embed/[videoId]">,
) {
	const params = await props.params;
	const searchParams = await props.searchParams;
	const videoId = params.videoId as Video.VideoId;
	const autoplay = searchParams.autoplay === "true";
	const minimal = searchParams.slack === "true";
	// `?t=` mirrors the share page, so an embed snippet copied "at 1:23" opens
	// there too. Repeated params arrive as an array; take the first.
	const startTimeParam = Array.isArray(searchParams.t)
		? searchParams.t[0]
		: searchParams.t;
	const parsedStartTime = Number.parseInt(startTimeParam ?? "", 10);
	const startTime =
		Number.isFinite(parsedStartTime) && parsedStartTime > 0
			? parsedStartTime
			: null;

	return Effect.gen(function* () {
		const videosPolicy = yield* VideosPolicy;

		const [video] = yield* Effect.promise(() =>
			db()
				.select({
					id: videos.id,
					name: videos.name,
					ownerId: videos.ownerId,
					orgId: videos.orgId,
					settings: videos.settings,
					createdAt: videos.createdAt,
					effectiveCreatedAt: videos.effectiveCreatedAt,
					updatedAt: videos.updatedAt,
					bucket: videos.bucket,
					storageIntegrationId: videos.storageIntegrationId,
					metadata: videos.metadata,
					public: videos.public,
					videoStartTime: videos.videoStartTime,
					audioStartTime: videos.audioStartTime,
					awsRegion: videos.awsRegion,
					awsBucket: videos.awsBucket,
					xStreamInfo: videos.xStreamInfo,
					jobId: videos.jobId,
					jobStatus: videos.jobStatus,
					isScreenshot: videos.isScreenshot,
					skipProcessing: videos.skipProcessing,
					transcriptionStatus: videos.transcriptionStatus,
					source: videos.source,
					folderId: videos.folderId,
					width: videos.width,
					height: videos.height,
					duration: videos.duration,
					fps: videos.fps,
					firstViewEmailSentAt: videos.firstViewEmailSentAt,
					hasPassword: sql`${videos.password} IS NOT NULL`.mapWith(Boolean),
					sharedOrganization: {
						organizationId: sharedVideos.organizationId,
					},
					orgSettings: organizations.settings,
					organizationName: organizations.name,
					organizationIconUrl: organizations.iconUrl,
					shareableLinkIconUrl: organizations.shareableLinkIconUrl,
					hasActiveUpload:
						sql`${videoUploads.videoId} IS NOT NULL AND ${videos.isScreenshot} = false`.mapWith(
							Boolean,
						),
				})
				.from(videos)
				.leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))
				.leftJoin(videoUploads, eq(videos.id, videoUploads.videoId))
				.leftJoin(organizations, eq(videos.orgId, organizations.id))
				.where(and(eq(videos.id, videoId), isNull(organizations.tombstoneAt))),
		).pipe(Policy.withPublicPolicy(videosPolicy.canView(videoId)));

		return Option.fromNullable(video);
	}).pipe(
		Effect.flatten,
		Effect.map((video) => ({ needsPassword: false, video }) as const),
		Effect.catchTag("VerifyVideoPasswordError", () =>
			Effect.succeed({ needsPassword: true } as const),
		),
		Effect.map((data) => (
			<div
				key={videoId}
				className={
					minimal
						? "h-screen overflow-hidden bg-black"
						: "min-h-screen bg-black"
				}
			>
				<PasswordOverlay isOpen={data.needsPassword} videoId={videoId} />
				{!data.needsPassword && (
					<EmbedContent
						video={data.video}
						autoplay={autoplay}
						startTime={startTime}
						minimal={minimal}
					/>
				)}
			</div>
		)),
		Effect.catchTags({
			PolicyDenied: renderEmbedPolicyDenied,
			NoSuchElementException: renderNoSuchElement,
		}),
		provideOptionalAuth,
		EffectRuntime.runPromise,
	);
}

async function EmbedContent({
	video,
	autoplay,
	startTime,
	minimal,
}: {
	video: Omit<typeof videos.$inferSelect, "password"> & {
		sharedOrganization: { organizationId: Organisation.OrganisationId } | null;
		hasActiveUpload: boolean | undefined;
		orgSettings?: (typeof organizations.$inferSelect)["settings"] | null;
		organizationName: (typeof organizations.$inferSelect)["name"] | null;
		organizationIconUrl: (typeof organizations.$inferSelect)["iconUrl"];
		shareableLinkIconUrl: (typeof organizations.$inferSelect)["shareableLinkIconUrl"];
	};
	autoplay: boolean;
	startTime: number | null;
	minimal: boolean;
}) {
	const user = await getCurrentUser();
	const sharedSpaces = await db()
		.select({
			id: spaces.id,
			name: spaces.name,
			settings: spaces.settings,
			hasPassword: sql`${spaces.password} IS NOT NULL`.mapWith(Boolean),
		})
		.from(spaceVideos)
		.innerJoin(spaces, eq(spaceVideos.spaceId, spaces.id))
		.where(eq(spaceVideos.videoId, video.id));

	const rules = resolveEffectiveVideoRules({
		videoSettings: video.settings,
		organizationSettings: video.orgSettings,
		spaces: sharedSpaces,
	});

	let aiGenerationEnabled = false;
	let ownerIsProUser = false;
	const videoOwnerQuery = await db()
		.select({
			email: users.email,
			stripeSubscriptionStatus: users.stripeSubscriptionStatus,
			thirdPartyStripeSubscriptionId: users.thirdPartyStripeSubscriptionId,
		})
		.from(users)
		.where(eq(users.id, video.ownerId))
		.limit(1);

	if (videoOwnerQuery.length > 0 && videoOwnerQuery[0]) {
		const videoOwner = videoOwnerQuery[0];
		aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);
		ownerIsProUser = userIsPro(videoOwner);
	}

	if (
		video.isScreenshot !== true &&
		!rules.settings.disableTranscript &&
		video.transcriptionStatus !== "COMPLETE" &&
		video.transcriptionStatus !== "PROCESSING" &&
		video.transcriptionStatus !== "SKIPPED" &&
		video.transcriptionStatus !== "NO_AUDIO" &&
		video.transcriptionStatus !== "ERROR"
	) {
		transcribeVideo(video.id, video.ownerId, aiGenerationEnabled);
	}

	const currentMetadata = (video.metadata as VideoMetadata) || {};
	const deferredLoomRawFileKey = video.hasActiveUpload
		? null
		: getPendingLoomProcessing(currentMetadata, video.ownerId, video.id);
	if (deferredLoomRawFileKey) {
		const rawFileKey = deferredLoomRawFileKey;
		after(() =>
			startDeferredLoomProcessing({
				videoId: video.id,
				ownerId: video.ownerId,
				bucketId: video.bucket,
				rawFileKey,
			}).catch((error) => {
				console.error(
					`[EmbedVideoPage] Error starting deferred processing for ${video.id}:`,
					error,
				);
			}),
		);
	}
	let initialAiData = null;

	if (
		currentMetadata.summary ||
		currentMetadata.chapters ||
		currentMetadata.aiTitle
	) {
		initialAiData = {
			title: currentMetadata.aiTitle || null,
			summary: currentMetadata.summary || null,
			chapters: currentMetadata.chapters || null,
		};
	}

	if (video.isScreenshot === true) {
		return (
			<div className="flex justify-center items-center min-h-screen text-white bg-black">
				<p>Screenshots cannot be embedded</p>
			</div>
		);
	}

	// Same quota gate as the share page, so embeds are not a loophole around
	// it. Fail-open: a broken count must never take the embed down.
	const overShareLimit =
		!ownerIsProUser &&
		(await isVideoOverShareableLinkLimit({
			id: video.id,
			ownerId: video.ownerId,
			createdAt: video.createdAt,
			isScreenshot: video.isScreenshot,
		}).catch((error) => {
			console.error(
				`[EmbedVideoPage] Shareable link quota check failed for ${video.id}:`,
				error,
			);
			return false;
		}));

	if (overShareLimit) {
		return (
			<div className="flex flex-col gap-3 justify-center items-center px-6 min-h-screen text-center bg-black">
				<Logo className="w-auto h-7" white />
				<h1 className="text-lg font-semibold text-white">
					This video is over its free limit
				</h1>
				<p className="max-w-sm text-sm leading-relaxed text-white/60">
					{`The owner of this video has used all ${Video.FREE_PLAN_SHAREABLE_LINKS_PER_MONTH} shareable links included with Cap's free plan this month. As soon as they upgrade to Cap Pro, this video will be instantly viewable.`}
				</p>
				<a
					href={`${buildEnv.NEXT_PUBLIC_WEB_URL}/s/${video.id}`}
					target="_blank"
					rel="noreferrer"
					className="mt-2 rounded-full border border-gray-5 bg-gray-3 px-5 py-2 text-sm font-medium text-gray-12 transition-colors hover:bg-gray-6"
				>
					Open on Cap
				</a>
			</div>
		);
	}

	const commentsQuery = await db()
		.select({
			id: comments.id,
			content: comments.content,
			timestamp: comments.timestamp,
			type: comments.type,
			authorId: comments.authorId,
			videoId: comments.videoId,
			createdAt: comments.createdAt,
			updatedAt: comments.updatedAt,
			parentCommentId: comments.parentCommentId,
			mediaKey: comments.mediaKey,
			mediaDuration: comments.mediaDuration,
			mediaMeta: comments.mediaMeta,
			authorName: users.name,
		})
		.from(comments)
		.leftJoin(users, eq(comments.authorId, users.id))
		.where(eq(comments.videoId, video.id));

	const videoOwner = await db()
		.select({
			name: users.name,
			image: users.image,
		})
		.from(users)
		.where(eq(users.id, video.ownerId))
		.limit(1);

	const ownerImageUrl = await Effect.gen(function* () {
		const imageUploads = yield* ImageUploads;
		return yield* Option.fromNullable(videoOwner[0]?.image).pipe(
			Option.map(imageUploads.resolveImageUrl),
			Effect.transposeOption,
			Effect.map(Option.getOrNull),
		);
	}).pipe(EffectRuntime.runPromise);

	const branding = await Effect.gen(function* () {
		const brandingInput = {
			owner: { isPro: ownerIsProUser },
			orgSettings: video.orgSettings,
			organizationName: video.organizationName,
		};
		const icon = video.orgSettings?.shareableLinkUseOrganizationIcon
			? video.organizationIconUrl
			: video.shareableLinkIconUrl;

		if (!ownerIsProUser || !icon || minimal) {
			return getSharePageBranding(brandingInput);
		}

		const imageUploads = yield* ImageUploads;
		const imageUrl = yield* imageUploads.resolveImageUrl(icon);

		return getSharePageBranding({
			...brandingInput,
			organizationIconUrl: imageUrl,
			shareableLinkIconUrl: imageUrl,
		});
	}).pipe(EffectRuntime.runPromise);

	return (
		<EmbedVideo
			data={video}
			branding={branding}
			user={user}
			comments={commentsQuery}
			chapters={
				rules.settings.disableChapters ? [] : initialAiData?.chapters || []
			}
			ownerName={videoOwner[0]?.name || null}
			ownerImageUrl={ownerImageUrl}
			autoplay={autoplay}
			startTime={startTime}
			minimal={minimal}
			defaultPlaybackSpeed={resolveDefaultPlaybackSpeed(
				video.settings?.defaultPlaybackSpeed,
				video.orgSettings?.defaultPlaybackSpeed,
			)}
			viewerSettings={rules.settings}
			showPlaybackStatusBadge={user?.id === video.ownerId}
			callToAction={
				ownerIsProUser && !minimal
					? parseShareCallToAction(video.settings)
					: null
			}
		/>
	);
}