Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Upload video button in dashboard (#574)

Richie McIlroyb1094ab41806
diff --git a/apps/web/actions/video/upload.ts b/apps/web/actions/video/upload.ts
new file mode 100644
index 000000000..7278e4f41
--- /dev/null
+++ b/apps/web/actions/video/upload.ts
@@ -0,0 +1,258 @@
+'use server';
+
+import { getCurrentUser } from "@cap/database/auth/session";
+import { createS3Client, getS3Bucket, getS3Config } from "@/utils/s3";
+import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
+import { db } from "@cap/database";
+import { s3Buckets, videos } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+import { serverEnv } from "@cap/env";
+import { nanoId } from "@cap/database/helpers";
+import {
+ CloudFrontClient,
+ CreateInvalidationCommand,
+} from "@aws-sdk/client-cloudfront";
+
+export async function getVideoUploadPresignedUrl({
+ fileKey,
+ duration,
+ resolution,
+ videoCodec,
+ audioCodec,
+}: {
+ fileKey: string;
+ duration?: string;
+ resolution?: string;
+ videoCodec?: string;
+ audioCodec?: string;
+}) {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Unauthorized");
+ }
+
+ try {
+ const [bucket] = await db()
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
+
+ const s3Config = bucket
+ ? {
+ endpoint: bucket.endpoint || undefined,
+ region: bucket.region,
+ accessKeyId: bucket.accessKeyId,
+ secretAccessKey: bucket.secretAccessKey,
+ }
+ : null;
+
+ if (
+ !bucket ||
+ !s3Config ||
+ bucket.bucketName !== serverEnv().CAP_AWS_BUCKET
+ ) {
+ const distributionId = serverEnv().CAP_CLOUDFRONT_DISTRIBUTION_ID;
+ if (distributionId) {
+
+ const cloudfront = new CloudFrontClient({
+ region: serverEnv().CAP_AWS_REGION || "us-east-1",
+ credentials: {
+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY || "",
+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY || "",
+ },
+ });
+
+ const pathToInvalidate = "/" + fileKey;
+
+ try {
+ const invalidation = await cloudfront.send(
+ new CreateInvalidationCommand({
+ DistributionId: distributionId,
+ InvalidationBatch: {
+ CallerReference: `${Date.now()}`,
+ Paths: {
+ Quantity: 1,
+ Items: [pathToInvalidate],
+ },
+ },
+ })
+ );
+ } catch (error) {
+ console.error("Failed to create CloudFront invalidation:", error);
+ }
+ }
+ }
+
+ const [s3Client] = await createS3Client(s3Config);
+
+ const contentType = fileKey.endsWith(".aac")
+ ? "audio/aac"
+ : fileKey.endsWith(".webm")
+ ? "audio/webm"
+ : fileKey.endsWith(".mp4")
+ ? "video/mp4"
+ : fileKey.endsWith(".mp3")
+ ? "audio/mpeg"
+ : fileKey.endsWith(".m3u8")
+ ? "application/x-mpegURL"
+ : "video/mp2t";
+
+ const Fields = {
+ "Content-Type": contentType,
+ "x-amz-meta-userid": user.id,
+ "x-amz-meta-duration": duration ?? "",
+ "x-amz-meta-resolution": resolution ?? "",
+ "x-amz-meta-videocodec": videoCodec ?? "",
+ "x-amz-meta-audiocodec": audioCodec ?? "",
+ };
+
+ const bucketName = await getS3Bucket(bucket);
+
+ const presignedPostData = await createPresignedPost(s3Client, {
+ Bucket: bucketName,
+ Key: fileKey,
+ Fields,
+ Expires: 1800,
+ });
+
+ const customEndpoint = serverEnv().CAP_AWS_ENDPOINT;
+ if (customEndpoint && !customEndpoint.includes("amazonaws.com")) {
+ if (serverEnv().S3_PATH_STYLE) {
+ presignedPostData.url = `${customEndpoint}/${bucketName}`;
+ } else {
+ presignedPostData.url = customEndpoint;
+ }
+ }
+
+ const videoId = fileKey.split("/")[1];
+ if (videoId) {
+ try {
+ await fetch(`${serverEnv().WEB_URL}/api/revalidate`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ videoId }),
+ });
+ } catch (revalidateError) {
+ console.error("Failed to revalidate page:", revalidateError);
+ }
+ }
+
+ return { presignedPostData };
+ } catch (error) {
+ console.error("Error getting presigned URL:", error);
+ throw new Error(
+ error instanceof Error ? error.message : "Failed to get presigned URL"
+ );
+ }
+}
+
+export async function createVideoAndGetUploadUrl({
+ videoId,
+ duration,
+ resolution,
+ videoCodec,
+ audioCodec,
+ isScreenshot = false,
+ isUpload = false,
+}: {
+ videoId?: string;
+ duration?: number;
+ resolution?: string;
+ videoCodec?: string;
+ audioCodec?: string;
+ isScreenshot?: boolean;
+ isUpload?: boolean;
+}) {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Unauthorized");
+ }
+
+ try {
+ const isUpgraded = user.stripeSubscriptionStatus === "active";
+
+ if (!isUpgraded && duration && duration > 300) {
+ throw new Error("upgrade_required");
+ }
+
+ const [bucket] = await db()
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
+
+ const s3Config = await getS3Config(bucket);
+ const bucketName = await getS3Bucket(bucket);
+
+ const date = new Date();
+ const formattedDate = `${date.getDate()} ${date.toLocaleString("default", {
+ month: "long",
+ })} ${date.getFullYear()}`;
+
+ if (videoId) {
+ const [existingVideo] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId));
+
+ if (existingVideo) {
+ const fileKey = `${user.id}/${videoId}/${isScreenshot ? "screenshot/screen-capture.jpg" : "result.mp4"}`;
+ const { presignedPostData } = await getVideoUploadPresignedUrl({
+ fileKey,
+ duration: duration?.toString(),
+ resolution,
+ videoCodec,
+ audioCodec,
+ });
+
+ return {
+ id: existingVideo.id,
+ user_id: user.id,
+ aws_region: existingVideo.awsRegion,
+ aws_bucket: existingVideo.awsBucket,
+ presignedPostData,
+ };
+ }
+ }
+
+ const idToUse = videoId || nanoId();
+
+ const videoData = {
+ id: idToUse,
+ name: `Cap ${isScreenshot ? "Screenshot" : isUpload ? "Upload" : "Recording"} - ${formattedDate}`,
+ ownerId: user.id,
+ awsRegion: s3Config.region,
+ awsBucket: bucketName,
+ source: { type: "desktopMP4" as const },
+ isScreenshot,
+ bucket: bucket?.id,
+ };
+
+ await db().insert(videos).values(videoData);
+
+ const fileKey = `${user.id}/${idToUse}/${isScreenshot ? "screenshot/screen-capture.jpg" : "result.mp4"}`;
+ const { presignedPostData } = await getVideoUploadPresignedUrl({
+ fileKey,
+ duration: duration?.toString(),
+ resolution,
+ videoCodec,
+ audioCodec,
+ });
+
+ return {
+ id: idToUse,
+ user_id: user.id,
+ aws_region: s3Config.region,
+ aws_bucket: bucketName,
+ presignedPostData,
+ };
+ } catch (error) {
+ console.error("Error creating video and getting upload URL:", error);
+ throw new Error(
+ error instanceof Error ? error.message : "Failed to create video"
+ );
+ }
+}
\ No newline at end of file
diff --git a/apps/web/app/api/desktop/[...route]/video.ts b/apps/web/app/api/desktop/[...route]/video.ts
index 4668a18a6..d5f8e52ff 100644
--- a/apps/web/app/api/desktop/[...route]/video.ts
+++ b/apps/web/app/api/desktop/[...route]/video.ts
@@ -20,7 +20,7 @@ app.get(
zValidator(
"query",
z.object({
- duration: z.number().optional(),
+ duration: z.coerce.number().optional(),
recordingMode: z
.union([z.literal("hls"), z.literal("desktopMP4")])
.optional(),
@@ -30,23 +30,29 @@ app.get(
})
),
async (c) => {
- const { duration, recordingMode, isScreenshot, videoId, name } =
- c.req.valid("query");
- const user = c.get("user");
+ try {
+ const { duration, recordingMode, isScreenshot, videoId, name } =
+ c.req.valid("query");
+ const user = c.get("user");
+
+ console.log("Video create request:", { duration, recordingMode, isScreenshot, videoId, userId: user.id });
+
+ const isUpgraded = user.stripeSubscriptionStatus === "active";
+
+ if (!isUpgraded && duration && duration > 300)
+ return c.json({ error: "upgrade_required" }, { status: 403 });
- // Check if user is on free plan and video is over 5 minutes
- const isUpgraded = user.stripeSubscriptionStatus === "active";
+ const [bucket] = await db()
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
- if (!isUpgraded && duration && duration > 300)
- return c.json({ error: "upgrade_required" }, { status: 403 });
+ console.log("User bucket:", bucket ? "found" : "not found");
- const [bucket] = await db()
- .select()
- .from(s3Buckets)
- .where(eq(s3Buckets.ownerId, user.id));
+ const s3Config = await getS3Config(bucket);
+ const bucketName = await getS3Bucket(bucket);
- const s3Config = await getS3Config(bucket);
- const bucketName = await getS3Bucket(bucket);
+ console.log("S3 Config:", { region: s3Config.region, bucketName });
const date = new Date();
const formattedDate = `${date.getDate()} ${date.toLocaleString("default", {
@@ -98,7 +104,6 @@ app.get(
key: idToUse,
});
- // Check if this is the user's first video and send the first shareable link email
try {
const videoCount = await db()
.select({ count: count() })
@@ -119,7 +124,6 @@ app.get(
? `https://cap.link/${idToUse}`
: `${serverEnv().WEB_URL}/s/${idToUse}`;
- // Send email with 5-minute delay using Resend's scheduling feature
await sendEmail({
email: user.email,
subject: "You created your first Cap! 🥳",
@@ -146,5 +150,9 @@ app.get(
aws_region: s3Config.region,
aws_bucket: bucketName,
});
+ } catch (error) {
+ console.error("Error in video create endpoint:", error);
+ return c.json({ error: "Internal server error" }, { status: 500 });
+ }
}
);
diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsx
index 1ca821d58..41b1bf16e 100644
--- a/apps/web/app/dashboard/caps/Caps.tsx
+++ b/apps/web/app/dashboard/caps/Caps.tsx
@@ -10,7 +10,9 @@ import { CapCard } from "./components/CapCard";
import { CapPagination } from "./components/CapPagination";
import { EmptyCapState } from "./components/EmptyCapState";
import { SelectedCapsBar } from "./components/SelectedCapsBar";
-
+import { UploadCapButton } from "./components/UploadCapButton";
+import { UploadPlaceholderCard } from "./components/UploadPlaceholderCard";
+import { serverEnv } from "@cap/env";
type VideoData = {
id: string;
@@ -21,7 +23,7 @@ type VideoData = {
totalReactions: number;
sharedOrganizations: { id: string; name: string }[];
ownerName: string;
- metadata?: VideoMetadata
+ metadata?: VideoMetadata;
hasPassword: boolean;
}[];
@@ -29,10 +31,12 @@ export const Caps = ({
data,
count,
userOrganizations,
+ dubApiKeyEnabled,
}: {
data: VideoData;
count: number;
userOrganizations: { id: string; name: string }[];
+ dubApiKeyEnabled: boolean;
}) => {
const { refresh } = useRouter();
const params = useSearchParams();
@@ -44,6 +48,14 @@ export const Caps = ({
const [selectedCaps, setSelectedCaps] = useState<string[]>([]);
const previousCountRef = useRef<number>(0);
const [isDeleting, setIsDeleting] = useState(false);
+ const [uploadPlaceholders, setUploadPlaceholders] = useState<
+ {
+ id: string;
+ progress: number;
+ thumbnail?: string;
+ uploadProgress?: number;
+ }[]
+ >([]);
const anyCapSelected = selectedCaps.length > 0;
@@ -51,6 +63,8 @@ export const Caps = ({
useEffect(() => {
const fetchAnalytics = async () => {
+ if (!dubApiKeyEnabled) return;
+
const analyticsData: Record<string, number> = {};
for (const video of data) {
@@ -167,30 +181,41 @@ export const Caps = ({
const results = await Promise.allSettled(
selectedCaps.map((capId) => deleteVideo(capId))
);
-
+
const successCount = results.filter(
(result) => result.status === "fulfilled" && result.value.success
).length;
-
+
const errorCount = selectedCaps.length - successCount;
-
+
if (successCount > 0 && errorCount > 0) {
return { success: successCount, error: errorCount };
} else if (successCount > 0) {
return { success: successCount };
} else {
- throw new Error(`Failed to delete ${errorCount} cap${errorCount === 1 ? "" : "s"}`);
+ throw new Error(
+ `Failed to delete ${errorCount} cap${errorCount === 1 ? "" : "s"}`
+ );
}
},
{
- loading: `Deleting ${selectedCaps.length} cap${selectedCaps.length === 1 ? "" : "s"}...`,
+ loading: `Deleting ${selectedCaps.length} cap${
+ selectedCaps.length === 1 ? "" : "s"
+ }...`,
success: (data) => {
if (data.error) {
- return `Successfully deleted ${data.success} cap${data.success === 1 ? "" : "s"}, but failed to delete ${data.error} cap${data.error === 1 ? "" : "s"}`;
+ return `Successfully deleted ${data.success} cap${
+ data.success === 1 ? "" : "s"
+ }, but failed to delete ${data.error} cap${
+ data.error === 1 ? "" : "s"
+ }`;
}
- return `Successfully deleted ${data.success} cap${data.success === 1 ? "" : "s"}`;
+ return `Successfully deleted ${data.success} cap${
+ data.success === 1 ? "" : "s"
+ }`;
},
- error: (error) => error.message || "An error occurred while deleting caps"
+ error: (error) =>
+ error.message || "An error occurred while deleting caps",
}
);
@@ -203,13 +228,47 @@ export const Caps = ({
}
};
+ const handleUploadStart = (id: string, thumbnail?: string) => {
+ setUploadPlaceholders((prev) => [{ id, progress: 0, thumbnail }, ...prev]);
+ };
+
+ const handleUploadProgress = (
+ id: string,
+ progress: number,
+ uploadProgress?: number
+ ) => {
+ setUploadPlaceholders((prev) =>
+ prev.map((u) => (u.id === id ? { ...u, progress, uploadProgress } : u))
+ );
+ };
+
+ const handleUploadComplete = (id: string) => {
+ setUploadPlaceholders((prev) => prev.filter((u) => u.id !== id));
+ refresh();
+ };
+
if (data.length === 0) {
return <EmptyCapState />;
}
return (
<div className="flex relative flex-col w-full">
+ <div className="flex justify-end mb-4">
+ <UploadCapButton
+ onStart={handleUploadStart}
+ onProgress={handleUploadProgress}
+ onComplete={handleUploadComplete}
+ />
+ </div>
<div className="grid grid-cols-1 gap-4 sm:gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
+ {uploadPlaceholders.map((u) => (
+ <UploadPlaceholderCard
+ key={u.id}
+ thumbnail={u.thumbnail}
+ progress={u.progress}
+ uploadProgress={u.uploadProgress}
+ />
+ ))}
{data.map((cap) => (
<CapCard
key={cap.id}
@@ -230,7 +289,6 @@ export const Caps = ({
</div>
)}
-
<SelectedCapsBar
selectedCaps={selectedCaps}
setSelectedCaps={setSelectedCaps}
diff --git a/apps/web/app/dashboard/caps/components/EmptyCapState.tsx b/apps/web/app/dashboard/caps/components/EmptyCapState.tsx
index 04bc06bfa..8e07e8676 100644
--- a/apps/web/app/dashboard/caps/components/EmptyCapState.tsx
+++ b/apps/web/app/dashboard/caps/components/EmptyCapState.tsx
@@ -1,6 +1,7 @@
import { Button } from "@cap/ui";
import { useRive } from "@rive-app/react-canvas";
import { useTheme } from "../../_components/DynamicSharedLayout";
+import { UploadCapButton } from "./UploadCapButton";
interface EmptyCapStateProps {
userName?: string;
@@ -27,7 +28,7 @@ export const EmptyCapState: React.FC<EmptyCapStateProps> = ({ userName }) => {
Craft your narrative with Cap - get projects done quicker.
</p>
</div>
- <div className="flex justify-center mt-4">
+ <div className="flex flex-col gap-3 justify-center mt-4">
<Button
size="lg"
href="/download"
@@ -36,6 +37,8 @@ export const EmptyCapState: React.FC<EmptyCapStateProps> = ({ userName }) => {
>
Download Cap
</Button>
+ <p className="text-gray-10 text-sm">or</p>
+ <UploadCapButton grey={true} />
</div>
</div>
</div>
diff --git a/apps/web/app/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/dashboard/caps/components/UploadCapButton.tsx
new file mode 100644
index 000000000..5eea6c6dd
--- /dev/null
+++ b/apps/web/app/dashboard/caps/components/UploadCapButton.tsx
@@ -0,0 +1,454 @@
+"use client";
+
+import { useRef, useState } from "react";
+import { Button } from "@cap/ui";
+import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
+import { createVideoAndGetUploadUrl } from "@/actions/video/upload";
+import { useRouter } from "next/navigation";
+import { toast } from "sonner";
+import {
+ getProgressCircleConfig,
+ calculateStrokeDashoffset,
+ getUploadStatus,
+ getDisplayProgress,
+ isUserOnProPlan,
+} from "@cap/utils";
+import { UpgradeModal } from "@/components/UpgradeModal";
+
+export const UploadCapButton = ({
+ onStart,
+ onProgress,
+ onComplete,
+ grey = false,
+}: {
+ onStart?: (id: string, thumbnail?: string) => void;
+ onProgress?: (id: string, progress: number, uploadProgress?: number) => void;
+ onComplete?: (id: string) => void;
+ grey?: boolean;
+}) => {
+ const { user, isSubscribed } = useSharedContext();
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [uploading, setUploading] = useState(false);
+ const [uploadProgress, setUploadProgress] = useState<number | undefined>(
+ undefined
+ );
+ const [processingProgress, setProcessingProgress] = useState(0);
+ const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
+ const router = useRouter();
+
+ const { circumference } = getProgressCircleConfig();
+ const status = getUploadStatus(uploadProgress);
+ const displayProgress = getDisplayProgress(
+ uploadProgress,
+ processingProgress
+ );
+ const strokeDashoffset = calculateStrokeDashoffset(
+ displayProgress,
+ circumference
+ );
+
+ const handleClick = () => {
+ if (!user) return;
+
+ const isCapPro = isUserOnProPlan({
+ subscriptionStatus: user.stripeSubscriptionStatus,
+ });
+
+ if (!isCapPro) {
+ setUpgradeModalOpen(true);
+ return;
+ }
+
+ inputRef.current?.click();
+ };
+
+ const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file || !user) return;
+
+ setUploading(true);
+ setUploadProgress(undefined);
+ setProcessingProgress(0);
+ try {
+ const parser = await import("@remotion/media-parser");
+ const webcodecs = await import("@remotion/webcodecs");
+
+ const metadata = await parser.parseMedia({
+ src: file,
+ fields: {
+ durationInSeconds: true,
+ dimensions: true,
+ fps: true,
+ numberOfAudioChannels: true,
+ sampleRate: true,
+ },
+ });
+
+ const duration = metadata.durationInSeconds
+ ? Math.round(metadata.durationInSeconds)
+ : undefined;
+
+ const videoData = await createVideoAndGetUploadUrl({
+ duration,
+ resolution: metadata.dimensions
+ ? `${metadata.dimensions.width}x${metadata.dimensions.height}`
+ : undefined,
+ videoCodec: "h264",
+ audioCodec: "aac",
+ isScreenshot: false,
+ isUpload: true,
+ });
+
+ const uploadId = videoData.id;
+ onStart?.(uploadId);
+ onProgress?.(uploadId, 10);
+
+ const fileSizeMB = file.size / (1024 * 1024);
+ onProgress?.(uploadId, 15);
+
+ let optimizedBlob: Blob;
+
+ try {
+ const calculateResizeOptions = () => {
+ if (!metadata.dimensions) return undefined;
+
+ const { width, height } = metadata.dimensions;
+ const maxWidth = 1920;
+ const maxHeight = 1080;
+
+ if (width <= maxWidth && height <= maxHeight) {
+ return undefined;
+ }
+
+ const widthScale = maxWidth / width;
+ const heightScale = maxHeight / height;
+ const scale = Math.min(widthScale, heightScale);
+
+ return { mode: "scale" as const, scale };
+ };
+
+ const resizeOptions = calculateResizeOptions();
+
+ const convertResult = await webcodecs.convertMedia({
+ src: file,
+ container: "mp4",
+ videoCodec: "h264",
+ audioCodec: "aac",
+ ...(resizeOptions && { resize: resizeOptions }),
+ onProgress: ({ overallProgress }) => {
+ if (overallProgress !== null) {
+ const progressValue = overallProgress * 100;
+ setProcessingProgress(progressValue);
+ onProgress?.(uploadId, progressValue);
+ }
+ },
+ });
+ optimizedBlob = await convertResult.save();
+
+ if (optimizedBlob.size === 0) {
+ throw new Error("Conversion produced empty file");
+ }
+ const isValidVideo = await new Promise<boolean>((resolve) => {
+ const testVideo = document.createElement("video");
+ testVideo.muted = true;
+ testVideo.playsInline = true;
+ testVideo.preload = "metadata";
+
+ const timeout = setTimeout(() => {
+ console.warn("Video validation timed out");
+ URL.revokeObjectURL(testVideo.src);
+ resolve(false);
+ }, 15000);
+
+ let metadataLoaded = false;
+
+ const validateVideo = () => {
+ if (metadataLoaded) return;
+ metadataLoaded = true;
+
+ const hasValidDuration =
+ testVideo.duration > 0 &&
+ !isNaN(testVideo.duration) &&
+ isFinite(testVideo.duration);
+
+ const hasValidDimensions =
+ (testVideo.videoWidth > 0 && testVideo.videoHeight > 0) ||
+ (metadata.dimensions &&
+ metadata.dimensions.width > 0 &&
+ metadata.dimensions.height > 0);
+
+ if (hasValidDuration && hasValidDimensions) {
+ clearTimeout(timeout);
+ URL.revokeObjectURL(testVideo.src);
+ resolve(true);
+ } else {
+ console.warn(
+ `Invalid video properties - Duration: ${testVideo.duration}, Dimensions: ${testVideo.videoWidth}x${testVideo.videoHeight}, Original dimensions: ${metadata.dimensions?.width}x${metadata.dimensions?.height}`
+ );
+ clearTimeout(timeout);
+ URL.revokeObjectURL(testVideo.src);
+ resolve(false);
+ }
+ };
+
+ testVideo.addEventListener("loadedmetadata", validateVideo);
+ testVideo.addEventListener("loadeddata", validateVideo);
+ testVideo.addEventListener("canplay", validateVideo);
+
+ testVideo.addEventListener("error", (e) => {
+ console.error("Video validation error:", e);
+ clearTimeout(timeout);
+ URL.revokeObjectURL(testVideo.src);
+ resolve(false);
+ });
+
+ testVideo.addEventListener("loadstart", () => {});
+
+ testVideo.src = URL.createObjectURL(optimizedBlob);
+ });
+
+ if (!isValidVideo) {
+ throw new Error("Converted video is not playable");
+ }
+ } catch (conversionError) {
+ console.error("Video conversion failed:", conversionError);
+ toast.error(
+ "Failed to process video file. This format may not be supported for upload."
+ );
+ return;
+ }
+
+ const captureThumbnail = (): Promise<Blob | null> => {
+ return new Promise((resolve) => {
+ const video = document.createElement("video");
+ video.src = URL.createObjectURL(optimizedBlob);
+ video.muted = true;
+ video.playsInline = true;
+ video.crossOrigin = "anonymous";
+
+ const cleanup = () => {
+ URL.revokeObjectURL(video.src);
+ };
+
+ const timeout = setTimeout(() => {
+ cleanup();
+ console.warn(
+ "Thumbnail generation timed out, proceeding without thumbnail"
+ );
+ resolve(null);
+ }, 10000);
+
+ video.addEventListener("loadedmetadata", () => {
+ try {
+ const seekTime = Math.min(1, video.duration / 4);
+ video.currentTime = seekTime;
+ } catch (err) {
+ console.warn("Failed to seek video for thumbnail:", err);
+ clearTimeout(timeout);
+ cleanup();
+ resolve(null);
+ }
+ });
+
+ video.addEventListener("seeked", () => {
+ try {
+ const canvas = document.createElement("canvas");
+ canvas.width = video.videoWidth || 640;
+ canvas.height = video.videoHeight || 480;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) {
+ console.warn("Failed to get canvas context");
+ clearTimeout(timeout);
+ cleanup();
+ resolve(null);
+ return;
+ }
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
+ canvas.toBlob(
+ (blob) => {
+ clearTimeout(timeout);
+ cleanup();
+ if (blob) {
+ resolve(blob);
+ } else {
+ console.warn("Failed to create thumbnail blob");
+ resolve(null);
+ }
+ },
+ "image/jpeg",
+ 0.8
+ );
+ } catch (err) {
+ console.warn("Error during thumbnail capture:", err);
+ clearTimeout(timeout);
+ cleanup();
+ resolve(null);
+ }
+ });
+
+ video.addEventListener("error", (err) => {
+ console.warn("Video loading error for thumbnail:", err);
+ clearTimeout(timeout);
+ cleanup();
+ resolve(null);
+ });
+
+ video.addEventListener("loadstart", () => {});
+ });
+ };
+
+ const thumbnailBlob = await captureThumbnail();
+ const thumbnailUrl = thumbnailBlob
+ ? URL.createObjectURL(thumbnailBlob)
+ : undefined;
+
+ onStart?.(uploadId, thumbnailUrl);
+ onProgress?.(uploadId, 100);
+
+ const formData = new FormData();
+ Object.entries(videoData.presignedPostData.fields).forEach(
+ ([key, value]) => {
+ formData.append(key, value as string);
+ }
+ );
+ formData.append("file", optimizedBlob);
+
+ setUploadProgress(0);
+
+ await new Promise<void>((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", videoData.presignedPostData.url);
+
+ xhr.upload.onprogress = (event) => {
+ if (event.lengthComputable) {
+ const percent = (event.loaded / event.total) * 100;
+ setUploadProgress(percent);
+ onProgress?.(uploadId, 100, percent);
+ }
+ };
+
+ xhr.onload = () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ resolve();
+ } else {
+ reject(new Error(`Upload failed with status ${xhr.status}`));
+ }
+ };
+ xhr.onerror = () => reject(new Error("Upload failed"));
+
+ xhr.send(formData);
+ });
+
+ if (thumbnailBlob) {
+ const screenshotData = await createVideoAndGetUploadUrl({
+ videoId: uploadId,
+ isScreenshot: true,
+ isUpload: true,
+ });
+
+ const screenshotFormData = new FormData();
+ Object.entries(screenshotData.presignedPostData.fields).forEach(
+ ([key, value]) => {
+ screenshotFormData.append(key, value as string);
+ }
+ );
+ screenshotFormData.append("file", thumbnailBlob);
+
+ await new Promise<void>((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open("POST", screenshotData.presignedPostData.url);
+
+ xhr.upload.onprogress = (event) => {
+ if (event.lengthComputable) {
+ const percent = (event.loaded / event.total) * 100;
+ const thumbnailProgress = 90 + percent * 0.1;
+ onProgress?.(uploadId, 100, thumbnailProgress);
+ }
+ };
+
+ xhr.onload = () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ resolve();
+ } else {
+ reject(
+ new Error(`Screenshot upload failed with status ${xhr.status}`)
+ );
+ }
+ };
+ xhr.onerror = () => reject(new Error("Screenshot upload failed"));
+
+ xhr.send(screenshotFormData);
+ });
+ } else {
+ }
+
+ onProgress?.(uploadId, 100, 100);
+ onComplete?.(uploadId);
+ router.refresh();
+ } catch (err) {
+ console.error("Video upload failed", err);
+ } finally {
+ setUploading(false);
+ setUploadProgress(undefined);
+ setProcessingProgress(0);
+ if (inputRef.current) inputRef.current.value = "";
+ }
+ };
+
+ return (
+ <>
+ <Button
+ onClick={handleClick}
+ disabled={uploading}
+ variant={grey ? "gray" : "primary"}
+ size="sm"
+ >
+ {uploading ? (
+ <div className="flex items-center gap-2">
+ {status}
+ <svg className="w-4 h-4 transform -rotate-90" viewBox="0 0 20 20">
+ <circle
+ cx="10"
+ cy="10"
+ r="8"
+ stroke="currentColor"
+ strokeWidth="3"
+ fill="none"
+ className={grey ? "text-black/30" : "text-white/30"}
+ />
+ <circle
+ cx="10"
+ cy="10"
+ r="8"
+ stroke="currentColor"
+ strokeWidth="3"
+ fill="none"
+ strokeLinecap="round"
+ className={`${
+ grey ? "text-black" : "text-white"
+ } transition-all duration-200 ease-out`}
+ style={{
+ strokeDasharray: `${circumference} ${circumference}`,
+ strokeDashoffset: `${strokeDashoffset}`,
+ }}
+ />
+ </svg>
+ </div>
+ ) : (
+ "Upload Video"
+ )}
+ </Button>
+ <input
+ ref={inputRef}
+ type="file"
+ accept="video/*,.mov,.MOV,.mp4,.MP4,.avi,.AVI,.mkv,.MKV,.webm,.WEBM,.m4v,.M4V"
+ onChange={handleChange}
+ className="hidden"
+ />
+ <UpgradeModal
+ open={upgradeModalOpen}
+ onOpenChange={setUpgradeModalOpen}
+ />
+ </>
+ );
+};
diff --git a/apps/web/app/dashboard/caps/components/UploadPlaceholderCard.tsx b/apps/web/app/dashboard/caps/components/UploadPlaceholderCard.tsx
new file mode 100644
index 000000000..c4d537762
--- /dev/null
+++ b/apps/web/app/dashboard/caps/components/UploadPlaceholderCard.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import { LogoSpinner } from "@cap/ui";
+import {
+ getProgressCircleConfig,
+ calculateStrokeDashoffset,
+ getUploadStatus,
+ getDisplayProgress,
+} from "@cap/utils";
+
+export const UploadPlaceholderCard = ({
+ thumbnail,
+ progress,
+ uploadProgress,
+}: {
+ thumbnail?: string;
+ progress: number;
+ uploadProgress?: number;
+}) => {
+ const { circumference } = getProgressCircleConfig();
+ const status = getUploadStatus(uploadProgress);
+ const displayProgress = getDisplayProgress(uploadProgress, progress);
+ const strokeDashoffset = calculateStrokeDashoffset(
+ displayProgress,
+ circumference
+ );
+
+ return (
+ <div className="flex flex-col gap-4 w-full h-full rounded-xl bg-gray-1 border-gray-3 border-[1px]">
+ <div className="relative w-full overflow-hidden bg-black rounded-t-xl border-b border-gray-3 aspect-video group">
+ {thumbnail ? (
+ <img
+ src={thumbnail}
+ alt="Uploading thumbnail"
+ className="w-full h-full object-cover"
+ />
+ ) : (
+ <div className="flex items-center justify-center w-full h-full">
+ <LogoSpinner className="w-8 h-8 animate-spin" />
+ </div>
+ )}
+
+ <div className="absolute inset-0 bg-black/60 transition-all duration-300"></div>
+
+ <div className="absolute bottom-3 left-3 flex items-center gap-2">
+ <span className="text-sm font-semibold text-white">{status}</span>
+ <svg className="w-4 h-4 transform -rotate-90" viewBox="0 0 20 20">
+ <circle
+ cx="10"
+ cy="10"
+ r="8"
+ stroke="currentColor"
+ strokeWidth="3"
+ fill="none"
+ className="text-white/30"
+ />
+ <circle
+ cx="10"
+ cy="10"
+ r="8"
+ stroke="currentColor"
+ strokeWidth="3"
+ fill="none"
+ strokeLinecap="round"
+ className="text-white transition-all duration-200 ease-out"
+ style={{
+ strokeDasharray: `${circumference} ${circumference}`,
+ strokeDashoffset: `${strokeDashoffset}`,
+ }}
+ />
+ </svg>
+ </div>
+ </div>
+ <div className="flex flex-col flex-grow gap-3 px-4 pb-4 w-full">
+ <div>
+ <div className="h-[1.25rem] mb-1">
+ <div className="h-4 bg-gray-3 rounded animate-pulse"></div>
+ </div>
+ <div className="mb-1 h-[1.25rem]">
+ <div className="h-3 bg-gray-3 rounded animate-pulse w-24"></div>
+ </div>
+ <div className="mb-1 h-[1.5rem]">
+ <div className="h-3 bg-gray-3 rounded animate-pulse w-20"></div>
+ </div>
+ </div>
+ <div className="flex items-center gap-4 text-sm text-gray-10">
+ <div className="h-3 bg-gray-3 rounded animate-pulse w-16"></div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsx
index f655a57e5..f065011be 100644
--- a/apps/web/app/dashboard/caps/page.tsx
+++ b/apps/web/app/dashboard/caps/page.tsx
@@ -12,6 +12,7 @@ import { count, desc, eq, sql } from "drizzle-orm";
import { Metadata } from "next";
import { redirect } from "next/navigation";
import { Caps } from "./Caps";
+import { serverEnv } from "@cap/env";
export const metadata: Metadata = {
title: "My Caps — Cap",
@@ -136,6 +137,7 @@ export default async function CapsPage({
data={processedVideoData}
count={totalCount}
userOrganizations={userOrganizations}
+ dubApiKeyEnabled={!!serverEnv().DUB_API_KEY}
/>
);
}
diff --git a/apps/web/components/UpgradeModal.tsx b/apps/web/components/UpgradeModal.tsx
index e5a2c4d2f..0a0228971 100644
--- a/apps/web/components/UpgradeModal.tsx
+++ b/apps/web/components/UpgradeModal.tsx
@@ -18,6 +18,7 @@ import {
Shield,
Sparkles,
Users,
+ Video,
} from "lucide-react";
import { useRouter } from "next/navigation";
import { memo, useState } from "react";
@@ -108,9 +109,9 @@ export const UpgradeModal = ({ open, onOpenChange }: UpgradeModalProps) => {
description: "Commercial license for desktop app automatically included",
},
{
- icon: <Users className={iconStyling} />,
- title: "Team features",
- description: "Collaborate with your team and create shared spaces",
+ icon: <Video className={iconStyling} />,
+ title: "Upload videos",
+ description: "Upload custom videos directly to Cap",
},
{
icon: <Infinity className={iconStyling} />,
diff --git a/apps/web/utils/video/upload/helpers.ts b/apps/web/utils/video/upload/helpers.ts
deleted file mode 100644
index 9b2a82015..000000000
--- a/apps/web/utils/video/upload/helpers.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { serverEnv } from "@cap/env";
-
-export async function uploadToS3({
- filename,
- blobData,
- userId,
- duration,
- resolution,
- videoCodec,
- audioCodec,
- awsBucket,
- awsRegion,
-}: {
- filename: string;
- blobData: Blob;
- userId: string;
- duration?: string;
- resolution?: string;
- videoCodec?: string;
- audioCodec?: string;
- awsBucket: string;
- awsRegion: string;
-}) {
- const response = await fetch(`${serverEnv().WEB_URL}/api/upload/signed`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- userId: userId,
- fileKey: filename,
- duration: duration,
- resolution: resolution,
- videoCodec: videoCodec,
- audioCodec: audioCodec,
- awsBucket: awsBucket,
- awsRegion: awsRegion,
- }),
- });
-
- const { presignedPostData } = await response.json();
-
- const formData = new FormData();
- Object.entries(presignedPostData.fields).forEach(([key, value]) => {
- formData.append(key, value as string);
- });
- formData.append("file", blobData);
-
- const uploadResponse = await fetch(presignedPostData.url, {
- method: "POST",
- body: formData,
- });
-
- if (!uploadResponse.ok) {
- return false;
- }
-
- return true;
-}
diff --git a/packages/utils/src/helpers.ts b/packages/utils/src/helpers.ts
index ef33bd2ed..aedfb28b2 100644
--- a/packages/utils/src/helpers.ts
+++ b/packages/utils/src/helpers.ts
@@ -59,3 +59,25 @@ export const isUserPro = async () => {
return false;
};
+
+export const getProgressCircleConfig = () => {
+ const radius = 8;
+ const circumference = 2 * Math.PI * radius;
+
+ return { radius, circumference };
+};
+
+export const calculateStrokeDashoffset = (progress: number, circumference: number) => {
+ return circumference - (progress / 100) * circumference;
+};
+
+export const getUploadStatus = (uploadProgress?: number) => {
+ if (uploadProgress !== undefined) {
+ return "Uploading";
+ }
+ return "Processing";
+};
+
+export const getDisplayProgress = (uploadProgress?: number, processingProgress: number = 0) => {
+ return uploadProgress !== undefined ? uploadProgress : processingProgress;
+};