Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add Loom import workflow and import UI

Richie McIlroy5325e70ff6a8
diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.ts
index 281ffd941..a68092b71 100644
--- a/apps/web/actions/loom.ts
+++ b/apps/web/actions/loom.ts
@@ -1,6 +1,23 @@
"use server";
import { randomUUID } from "node:crypto";
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { nanoId } from "@cap/database/helpers";
+import {
+ importedVideos,
+ s3Buckets,
+ videos,
+ videoUploads,
+} from "@cap/database/schema";
+import { buildEnv, NODE_ENV, serverEnv } from "@cap/env";
+import { dub, userIsPro } from "@cap/utils";
+import type { Organisation } from "@cap/web-domain";
+import { Video } from "@cap/web-domain";
+import { and, eq } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+import { start } from "workflow/api";
+import { importLoomVideoWorkflow } from "@/workflows/import-loom-video";
interface LoomUrlResponse {
url?: string;
@@ -13,6 +30,12 @@ interface LoomDownloadResult {
error?: string;
}
+export interface LoomImportResult {
+ success: boolean;
+ videoId?: string;
+ error?: string;
+}
+
function extractLoomVideoId(url: string): string | null {
try {
const parsed = new URL(url);
@@ -102,6 +125,48 @@ async function fetchVideoName(videoId: string): Promise<string | null> {
}
}
+function isStreamingUrl(url: string): boolean {
+ const path = (url.split("?")[0] ?? "").toLowerCase();
+ return path.endsWith(".m3u8") || path.endsWith(".mpd");
+}
+
+async function getLoomDownloadUrl(loomVideoId: string): Promise<string | null> {
+ const endpoints = ["transcoded-url", "raw-url"] as const;
+
+ let fallbackStreamingUrl: string | null = null;
+
+ for (const endpoint of endpoints) {
+ const url = await fetchLoomEndpoint(loomVideoId, endpoint);
+ if (!url) continue;
+
+ if (!isStreamingUrl(url)) return url;
+
+ if (!fallbackStreamingUrl) fallbackStreamingUrl = url;
+ }
+
+ return fallbackStreamingUrl;
+}
+
+async function fetchLoomOEmbed(
+ loomVideoId: string,
+): Promise<{ duration?: number; width?: number; height?: number } | null> {
+ try {
+ const response = await fetch(
+ `https://www.loom.com/v1/oembed?url=https://www.loom.com/share/${loomVideoId}`,
+ { headers: { Accept: "application/json" } },
+ );
+ if (!response.ok) return null;
+ const data = await response.json();
+ return {
+ duration: data.duration ? Math.round(data.duration) : undefined,
+ width: data.width ?? undefined,
+ height: data.height ?? undefined,
+ };
+ } catch {
+ return null;
+ }
+}
+
export async function downloadLoomVideo(
url: string,
): Promise<LoomDownloadResult> {
@@ -145,3 +210,128 @@ export async function downloadLoomVideo(
};
}
}
+
+export async function importFromLoom({
+ loomUrl,
+ orgId,
+}: {
+ loomUrl: string;
+ orgId: Organisation.OrganisationId;
+}): Promise<LoomImportResult> {
+ const user = await getCurrentUser();
+ if (!user) return { success: false, error: "Unauthorized" };
+
+ if (!userIsPro(user)) {
+ return {
+ success: false,
+ error: "Importing from Loom requires a Cap Pro subscription.",
+ };
+ }
+
+ const loomVideoId = extractLoomVideoId(loomUrl.trim());
+ if (!loomVideoId) {
+ return {
+ success: false,
+ error:
+ "Invalid Loom URL. Please paste a valid Loom video link (e.g. https://www.loom.com/share/abc123).",
+ };
+ }
+
+ const existing = await db()
+ .select()
+ .from(importedVideos)
+ .where(
+ and(
+ eq(importedVideos.orgId, orgId),
+ eq(importedVideos.source, "loom"),
+ eq(importedVideos.sourceId, loomVideoId),
+ ),
+ );
+
+ if (existing.length > 0) {
+ return {
+ success: false,
+ error: "This Loom video has already been imported.",
+ };
+ }
+
+ const downloadUrl = await getLoomDownloadUrl(loomVideoId);
+ if (!downloadUrl) {
+ return {
+ success: false,
+ error:
+ "Could not retrieve a download URL. The video may be private, password-protected, or the link may have expired.",
+ };
+ }
+
+ const [videoName, oembedMeta] = await Promise.all([
+ fetchVideoName(loomVideoId),
+ fetchLoomOEmbed(loomVideoId),
+ ]);
+
+ const [customBucket] = await db()
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
+
+ const videoId = Video.VideoId.make(nanoId());
+ const name =
+ videoName ||
+ `Loom Import - ${new Date().toLocaleDateString("en-US", { day: "numeric", month: "long", year: "numeric" })}`;
+
+ await db()
+ .insert(videos)
+ .values({
+ id: videoId,
+ name,
+ ownerId: user.id,
+ orgId,
+ source: { type: "webMP4" as const },
+ bucket: customBucket?.id,
+ public: serverEnv().CAP_VIDEOS_DEFAULT_PUBLIC,
+ ...(oembedMeta?.duration ? { duration: oembedMeta.duration } : {}),
+ ...(oembedMeta?.width ? { width: oembedMeta.width } : {}),
+ ...(oembedMeta?.height ? { height: oembedMeta.height } : {}),
+ });
+
+ await db().insert(videoUploads).values({
+ videoId,
+ phase: "uploading",
+ processingProgress: 0,
+ processingMessage: "Importing from Loom...",
+ });
+
+ const importId = nanoId();
+ await db().insert(importedVideos).values({
+ id: importId,
+ orgId,
+ source: "loom",
+ sourceId: loomVideoId,
+ });
+
+ const rawFileKey = `${user.id}/${videoId}/raw-upload.mp4`;
+
+ if (buildEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production") {
+ await dub()
+ .links.create({
+ url: `${serverEnv().WEB_URL}/s/${videoId}`,
+ domain: "cap.link",
+ key: videoId,
+ })
+ .catch(() => {});
+ }
+
+ await start(importLoomVideoWorkflow, [
+ {
+ videoId,
+ userId: user.id,
+ rawFileKey,
+ bucketId: customBucket?.id ?? null,
+ loomDownloadUrl: downloadUrl,
+ },
+ ]);
+
+ revalidatePath("/dashboard/caps");
+
+ return { success: true, videoId };
+}
diff --git a/apps/web/app/(org)/dashboard/_components/AnimatedIcons/Import.tsx b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/Import.tsx
new file mode 100644
index 000000000..ff8e5786f
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/Import.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import type { Variants } from "motion/react";
+import { motion, useAnimation } from "motion/react";
+import type { HTMLAttributes } from "react";
+import { forwardRef, useCallback, useImperativeHandle, useRef } from "react";
+import { cn } from "@/lib/utils";
+
+export interface ImportIconHandle {
+ startAnimation: () => void;
+ stopAnimation: () => void;
+}
+
+interface ImportIconProps extends HTMLAttributes<HTMLDivElement> {
+ size?: number;
+}
+
+const arrowVariants: Variants = {
+ normal: { y: 0 },
+ animate: {
+ y: -2,
+ transition: {
+ type: "spring",
+ stiffness: 200,
+ damping: 10,
+ mass: 1,
+ },
+ },
+};
+
+const ImportIcon = forwardRef<ImportIconHandle, ImportIconProps>(
+ ({ onMouseEnter, onMouseLeave, className, size = 28, ...props }, ref) => {
+ const controls = useAnimation();
+ const isControlledRef = useRef(false);
+
+ useImperativeHandle(ref, () => {
+ isControlledRef.current = true;
+
+ return {
+ startAnimation: () => controls.start("animate"),
+ stopAnimation: () => controls.start("normal"),
+ };
+ });
+
+ const handleMouseEnter = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!isControlledRef.current) {
+ controls.start("animate");
+ } else {
+ onMouseEnter?.(e);
+ }
+ },
+ [controls, onMouseEnter],
+ );
+
+ const handleMouseLeave = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!isControlledRef.current) {
+ controls.start("normal");
+ } else {
+ onMouseLeave?.(e);
+ }
+ },
+ [controls, onMouseLeave],
+ );
+
+ return (
+ <div
+ className={cn(className)}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ {...props}
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
+ <motion.g variants={arrowVariants} animate={controls}>
+ <polyline points="17 8 12 3 7 8" />
+ <line x1="12" x2="12" y1="3" y2="15" />
+ </motion.g>
+ </svg>
+ </div>
+ );
+ },
+);
+
+ImportIcon.displayName = "ImportIcon";
+
+export default ImportIcon;
diff --git a/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts
index f41eb1e9a..a78bba9d4 100644
--- a/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts
+++ b/apps/web/app/(org)/dashboard/_components/AnimatedIcons/index.ts
@@ -7,6 +7,7 @@ import ClapIcon from "./Clap";
import CogIcon from "./Cog";
import DownloadIcon from "./Download";
import HomeIcon from "./Home";
+import ImportIcon from "./Import";
import LayersIcon from "./Layers";
import LogoutIcon from "./Logout";
import ReactionIcon from "./Reaction";
@@ -20,6 +21,7 @@ export {
CogIcon,
DownloadIcon,
HomeIcon,
+ ImportIcon,
LayersIcon,
LogoutIcon,
SettingsGearIcon,
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
index 286797545..160105bbc 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx
@@ -35,7 +35,13 @@ import { SignedImageUrl } from "@/components/SignedImageUrl";
import { Tooltip } from "@/components/Tooltip";
import { UsageButton } from "@/components/UsageButton";
import { useDashboardContext } from "../../Contexts";
-import { CapIcon, ChartLineIcon, CogIcon, RecordIcon } from "../AnimatedIcons";
+import {
+ CapIcon,
+ ChartLineIcon,
+ CogIcon,
+ ImportIcon,
+ RecordIcon,
+} from "../AnimatedIcons";
import type { CogIconHandle } from "../AnimatedIcons/Cog";
import SpacesList from "./SpacesList";
import { updateActiveOrganization } from "./server";
@@ -70,6 +76,13 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {
icon: <RecordIcon />,
subNav: [],
},
+ {
+ name: "Import Video",
+ href: `/dashboard/import`,
+ matchChildren: true,
+ icon: <ImportIcon />,
+ subNav: [],
+ },
{
name: "Organization Settings",
href: `/dashboard/settings/organization`,
diff --git a/apps/web/app/(org)/dashboard/caps/Caps.tsx b/apps/web/app/(org)/dashboard/caps/Caps.tsx
index bb4a846e2..4106cc732 100644
--- a/apps/web/app/(org)/dashboard/caps/Caps.tsx
+++ b/apps/web/app/(org)/dashboard/caps/Caps.tsx
@@ -241,7 +241,7 @@ export const Caps = ({
open={openNewFolderDialog}
onOpenChange={setOpenNewFolderDialog}
/>
- <div className="flex gap-3 items-center mb-10 w-full">
+ <div className="flex flex-wrap gap-3 items-center mb-10 w-full">
<Button
onClick={() => setOpenNewFolderDialog(true)}
size="sm"
diff --git a/apps/web/app/(org)/dashboard/caps/components/ImportLoomButton.tsx b/apps/web/app/(org)/dashboard/caps/components/ImportLoomButton.tsx
new file mode 100644
index 000000000..4cd2791b5
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/caps/components/ImportLoomButton.tsx
@@ -0,0 +1,148 @@
+"use client";
+
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Input,
+} from "@cap/ui";
+import { faFileImport } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { importFromLoom } from "@/actions/loom";
+import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
+import { UpgradeModal } from "@/components/UpgradeModal";
+
+export const ImportLoomButton = ({
+ size = "md",
+}: {
+ size?: "sm" | "lg" | "md";
+}) => {
+ const { user, activeOrganization } = useDashboardContext();
+ const router = useRouter();
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [loomUrl, setLoomUrl] = useState("");
+ const [isImporting, setIsImporting] = useState(false);
+ const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
+
+ const handleClick = () => {
+ if (!user) return;
+
+ if (!user.isPro) {
+ setUpgradeModalOpen(true);
+ return;
+ }
+
+ setDialogOpen(true);
+ };
+
+ const handleImport = async () => {
+ if (!loomUrl.trim() || !activeOrganization) return;
+
+ setIsImporting(true);
+
+ try {
+ const result = await importFromLoom({
+ loomUrl: loomUrl.trim(),
+ orgId: activeOrganization.organization.id,
+ });
+
+ if (!result.success) {
+ toast.error(result.error || "Failed to import video.");
+ setIsImporting(false);
+ return;
+ }
+
+ toast.success(
+ "Loom video import started! It will appear in your caps shortly.",
+ );
+ setDialogOpen(false);
+ setLoomUrl("");
+ router.refresh();
+ } catch {
+ toast.error("An unexpected error occurred. Please try again.");
+ } finally {
+ setIsImporting(false);
+ }
+ };
+
+ const isValidLoomUrl = (() => {
+ try {
+ const parsed = new URL(loomUrl.trim());
+ return parsed.hostname.includes("loom.com");
+ } catch {
+ return false;
+ }
+ })();
+
+ return (
+ <>
+ <Button
+ onClick={handleClick}
+ variant="dark"
+ className="flex gap-2 items-center"
+ size={size}
+ >
+ <FontAwesomeIcon className="size-3.5" icon={faFileImport} />
+ Import from Loom
+ </Button>
+
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogContent className="w-[calc(100%-20px)] max-w-md">
+ <DialogHeader
+ icon={<FontAwesomeIcon icon={faFileImport} className="size-3.5" />}
+ >
+ <DialogTitle>Import from Loom</DialogTitle>
+ </DialogHeader>
+ <div className="p-5">
+ <p className="mb-3 text-sm text-gray-11">
+ Paste a Loom video URL to import it to Cap. The video will be
+ downloaded and processed in the background.
+ </p>
+ <Input
+ value={loomUrl}
+ onChange={(e) => setLoomUrl(e.target.value)}
+ placeholder="https://www.loom.com/share/..."
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && isValidLoomUrl && !isImporting) {
+ handleImport();
+ }
+ }}
+ />
+ </div>
+ <DialogFooter>
+ <Button
+ size="sm"
+ variant="gray"
+ onClick={() => {
+ setDialogOpen(false);
+ setLoomUrl("");
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleImport}
+ size="sm"
+ spinner={isImporting}
+ variant="dark"
+ disabled={!isValidLoomUrl || isImporting}
+ >
+ {isImporting ? "Importing..." : "Import"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <UpgradeModal
+ open={upgradeModalOpen}
+ onOpenChange={setUpgradeModalOpen}
+ />
+ </>
+ );
+};
diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
index 17f3661ab..f55dbfe62 100644
--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
@@ -1,39 +1,22 @@
"use client";
import { Button } from "@cap/ui";
-import type { Folder, Organisation } from "@cap/web-domain";
import { faUpload } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { useQueryClient } from "@tanstack/react-query";
-import { useStore } from "@tanstack/react-store";
import { useRouter } from "next/navigation";
-import { useRef, useState } from "react";
-import { toast } from "sonner";
-import { createVideoForServerProcessing } from "@/actions/video/create-for-processing";
-import { triggerVideoProcessing } from "@/actions/video/trigger-processing";
+import { useState } from "react";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
-import {
- type UploadStatus,
- useUploadingContext,
-} from "@/app/(org)/dashboard/caps/UploadingContext";
import { UpgradeModal } from "@/components/UpgradeModal";
-import { sendProgressUpdate } from "./sendProgressUpdate";
export const UploadCapButton = ({
size = "md",
- folderId,
}: {
size?: "sm" | "lg" | "md";
grey?: boolean;
- folderId?: Folder.FolderId;
}) => {
- const { user, activeOrganization } = useDashboardContext();
- const inputRef = useRef<HTMLInputElement>(null);
- const { uploadingStore, setUploadStatus } = useUploadingContext();
- const isUploading = useStore(uploadingStore, (s) => !!s.uploadStatus);
+ const { user } = useDashboardContext();
const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);
const router = useRouter();
- const queryClient = useQueryClient();
const handleClick = () => {
if (!user) return;
@@ -43,48 +26,20 @@ export const UploadCapButton = ({
return;
}
- inputRef.current?.click();
- };
-
- const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (!file || !user) return;
-
- if (activeOrganization === null) {
- alert("No organization active!");
- return;
- }
-
- const ok = await uploadVideoForServerProcessing(
- file,
- folderId,
- activeOrganization.organization.id,
- setUploadStatus,
- );
- if (ok) router.refresh();
- if (inputRef.current) inputRef.current.value = "";
+ router.push("/dashboard/import");
};
return (
<>
<Button
onClick={handleClick}
- disabled={isUploading}
variant="dark"
className="flex gap-2 items-center"
size={size}
- spinner={isUploading}
>
<FontAwesomeIcon className="size-3.5" icon={faUpload} />
- {isUploading ? "Uploading..." : "Upload Video"}
+ Import 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}
@@ -92,195 +47,3 @@ export const UploadCapButton = ({
</>
);
};
-
-async function uploadVideoForServerProcessing(
- file: File,
- folderId: Folder.FolderId | undefined,
- orgId: Organisation.OrganisationId,
- setUploadStatus: (state: UploadStatus | undefined) => void,
-) {
- try {
- setUploadStatus({ status: "parsing" });
-
- let duration: number | undefined;
- let resolution: string | undefined;
-
- try {
- const parser = await import("@remotion/media-parser");
- const metadata = await parser.parseMedia({
- src: file,
- fields: {
- durationInSeconds: true,
- dimensions: true,
- },
- });
-
- duration = metadata.durationInSeconds
- ? Math.round(metadata.durationInSeconds)
- : undefined;
- resolution = metadata.dimensions
- ? `${metadata.dimensions.width}x${metadata.dimensions.height}`
- : undefined;
- } catch (parseError) {
- console.warn(
- "Failed to parse video metadata, continuing without it:",
- parseError,
- );
- }
-
- setUploadStatus({ status: "creating" });
- const videoData = await createVideoForServerProcessing({
- duration,
- resolution,
- folderId,
- orgId,
- });
-
- const uploadId = videoData.id;
-
- setUploadStatus({
- status: "uploadingVideo",
- capId: uploadId,
- progress: 0,
- thumbnailUrl: undefined,
- });
-
- const formData = new FormData();
- Object.entries(videoData.presignedPostData.fields).forEach(
- ([key, value]) => {
- formData.append(key, value as string);
- },
- );
- formData.append("file", file);
-
- const createProgressTracker = () => {
- const uploadState = {
- videoId: uploadId,
- uploaded: 0,
- total: 0,
- pendingTask: undefined as ReturnType<typeof setTimeout> | undefined,
- lastUpdateTime: Date.now(),
- };
-
- const scheduleProgressUpdate = (uploaded: number, total: number) => {
- uploadState.uploaded = uploaded;
- uploadState.total = total;
- uploadState.lastUpdateTime = Date.now();
-
- if (uploadState.pendingTask) {
- clearTimeout(uploadState.pendingTask);
- uploadState.pendingTask = undefined;
- }
-
- const shouldSendImmediately = uploaded >= total;
-
- if (shouldSendImmediately) {
- return;
- } else {
- uploadState.pendingTask = setTimeout(() => {
- if (uploadState.videoId) {
- sendProgressUpdate(
- uploadState.videoId,
- uploadState.uploaded,
- uploadState.total,
- );
- }
- uploadState.pendingTask = undefined;
- }, 2000);
- }
- };
-
- const cleanup = () => {
- if (uploadState.pendingTask) {
- clearTimeout(uploadState.pendingTask);
- uploadState.pendingTask = undefined;
- }
- };
-
- const getTotal = () => uploadState.total;
-
- return { scheduleProgressUpdate, cleanup, getTotal };
- };
-
- const progressTracker = createProgressTracker();
-
- try {
- 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;
- setUploadStatus({
- status: "uploadingVideo",
- capId: uploadId,
- progress: percent,
- thumbnailUrl: undefined,
- });
-
- progressTracker.scheduleProgressUpdate(event.loaded, event.total);
- }
- };
-
- xhr.onload = () => {
- if (xhr.status >= 200 && xhr.status < 300) {
- progressTracker.cleanup();
- const total = progressTracker.getTotal() || 1;
- sendProgressUpdate(uploadId, total, total);
- resolve();
- } else {
- progressTracker.cleanup();
- reject(new Error(`Upload failed with status ${xhr.status}`));
- }
- };
- xhr.onerror = () => {
- progressTracker.cleanup();
- reject(new Error("Upload failed"));
- };
-
- xhr.send(formData);
- });
- } catch (uploadError) {
- progressTracker.cleanup();
- throw uploadError;
- }
-
- setUploadStatus({
- status: "serverProcessing",
- capId: uploadId,
- });
-
- try {
- await triggerVideoProcessing({
- videoId: uploadId,
- rawFileKey: videoData.rawFileKey,
- bucketId: videoData.bucketId,
- });
- } catch (triggerError) {
- console.error("Failed to trigger processing:", triggerError);
- toast.error("Failed to start video processing. Please try again.");
- setUploadStatus(undefined);
- return false;
- }
-
- setUploadStatus(undefined);
- toast.success(
- "Video uploaded! Processing will continue in the background.",
- );
- return true;
- } catch (err) {
- console.error("Video upload failed", err);
-
- if (err instanceof Error && err.message === "upgrade_required") {
- toast.error(
- "Video duration exceeds the limit for free accounts. Please upgrade to Pro.",
- );
- } else {
- toast.error("Failed to upload video. Please try again.");
- }
- }
-
- setUploadStatus(undefined);
- return false;
-}
diff --git a/apps/web/app/(org)/dashboard/folder/[id]/page.tsx b/apps/web/app/(org)/dashboard/folder/[id]/page.tsx
index 4f63bf6b7..ec78a99be 100644
--- a/apps/web/app/(org)/dashboard/folder/[id]/page.tsx
+++ b/apps/web/app/(org)/dashboard/folder/[id]/page.tsx
@@ -40,7 +40,7 @@ const FolderPage = async (props: PageProps<"/dashboard/folder/[id]">) => {
<div>
<div className="flex gap-2 items-center mb-10">
<NewSubfolderButton parentFolderId={folderId} />
- <UploadCapButton size="sm" folderId={folderId} />
+ <UploadCapButton size="sm" />
</div>
<div className="flex justify-between items-center mb-6 w-full">
<div className="flex overflow-x-auto items-center font-medium">
diff --git a/apps/web/app/(org)/dashboard/import/ImportPage.tsx b/apps/web/app/(org)/dashboard/import/ImportPage.tsx
new file mode 100644
index 000000000..8db3d1e07
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/import/ImportPage.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import { faUpload } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import Link from "next/link";
+
+export const ImportPage = () => {
+ return (
+ <div className="flex flex-col w-full h-full">
+ <div className="mb-8">
+ <h1 className="text-2xl font-medium text-gray-12">Import</h1>
+ <p className="mt-1 text-sm text-gray-10">
+ Import videos from external sources or upload from your device.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 max-w-2xl">
+ <Link
+ href="/dashboard/import/file"
+ className="group relative flex overflow-hidden flex-col w-full rounded-xl border border-gray-3 bg-gray-1 transition-all duration-200 hover:border-blue-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-8"
+ >
+ <div className="flex items-center justify-center w-full h-32 bg-gray-3 transition-colors duration-200 group-hover:bg-gray-4">
+ <div className="flex items-center justify-center size-14 rounded-full bg-gray-1 text-gray-10 transition-all duration-200 group-hover:text-gray-12 group-hover:scale-110">
+ <FontAwesomeIcon className="size-5" icon={faUpload} />
+ </div>
+ </div>
+ <div className="flex flex-col gap-1 p-4">
+ <p className="text-sm font-medium text-gray-12 text-left">
+ Upload File
+ </p>
+ <p className="text-xs text-gray-10 text-left">
+ Upload a video file from your device
+ </p>
+ </div>
+ </Link>
+
+ <Link
+ href="/dashboard/import/loom"
+ className="group relative flex overflow-hidden flex-col w-full rounded-xl border border-gray-3 bg-gray-1 transition-all duration-200 hover:border-blue-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-8"
+ >
+ <div className="flex items-center justify-center w-full h-32 bg-gray-3 transition-colors duration-200 group-hover:bg-gray-4">
+ <div className="flex items-center justify-center size-14 rounded-full bg-gray-1 transition-all duration-200 group-hover:scale-110">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="22"
+ height="22"
+ viewBox="0 0 16 16"
+ fill="none"
+ role="img"
+ aria-label="Loom"
+ >
+ <path
+ fill="#625DF5"
+ d="M15 7.222h-4.094l3.546-2.047-.779-1.35-3.545 2.048 2.046-3.546-1.349-.779L8.78 5.093V1H7.22v4.094L5.174 1.548l-1.348.779 2.046 3.545-3.545-2.046-.779 1.348 3.546 2.047H1v1.557h4.093l-3.545 2.047.779 1.35 3.545-2.047-2.047 3.545 1.35.779 2.046-3.546V15h1.557v-4.094l2.047 3.546 1.349-.779-2.047-3.546 3.545 2.047.779-1.349-3.545-2.046h4.093L15 7.222zm-7 2.896a2.126 2.126 0 110-4.252 2.126 2.126 0 010 4.252z"
+ />
+ </svg>
+ </div>
+ </div>
+ <div className="flex flex-col gap-1 p-4">
+ <p className="text-sm font-medium text-gray-12 text-left">Loom</p>
+ <p className="text-xs text-gray-10 text-left">
+ Import a video from a Loom share link
+ </p>
+ </div>
+ </Link>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/app/(org)/dashboard/import/file/ImportFilePage.tsx b/apps/web/app/(org)/dashboard/import/file/ImportFilePage.tsx
new file mode 100644
index 000000000..2721f655c
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/import/file/ImportFilePage.tsx
@@ -0,0 +1,382 @@
+"use client";
+
+import { Button } from "@cap/ui";
+import type { Folder, Organisation } from "@cap/web-domain";
+import { faArrowLeft, faUpload } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useStore } from "@tanstack/react-store";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useRef, useState } from "react";
+import { toast } from "sonner";
+import { createVideoForServerProcessing } from "@/actions/video/create-for-processing";
+import { triggerVideoProcessing } from "@/actions/video/trigger-processing";
+import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
+import { sendProgressUpdate } from "@/app/(org)/dashboard/caps/components/sendProgressUpdate";
+import {
+ type UploadStatus,
+ useUploadingContext,
+} from "@/app/(org)/dashboard/caps/UploadingContext";
+import { UpgradeModal } from "@/components/UpgradeModal";
+
+export const ImportFilePage = () => {
+ const { user, activeOrganization } = useDashboardContext();
+ const router = useRouter();
+ const inputRef = useRef<HTMLInputElement>(null);
+ const { uploadingStore, setUploadStatus } = useUploadingContext();
+ const isUploading = useStore(uploadingStore, (s) => !!s.uploadStatus);
+ const [upgradeModalOpen, setUpgradeModalOpen] = useState(!user?.isPro);
+ const [isDragOver, setIsDragOver] = useState(false);
+
+ const processFile = useCallback(
+ async (file: File) => {
+ if (!user || !activeOrganization) return;
+
+ if (!user.isPro) {
+ setUpgradeModalOpen(true);
+ return;
+ }
+
+ const ok = await uploadVideoForServerProcessing(
+ file,
+ undefined,
+ activeOrganization.organization.id,
+ setUploadStatus,
+ );
+ if (ok) router.push("/dashboard/caps");
+ },
+ [user, activeOrganization, setUploadStatus, router],
+ );
+
+ const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ await processFile(file);
+ if (inputRef.current) inputRef.current.value = "";
+ };
+
+ const handleDrop = useCallback(
+ async (e: React.DragEvent) => {
+ e.preventDefault();
+ setIsDragOver(false);
+ const file = e.dataTransfer.files[0];
+ if (!file) return;
+
+ const isVideo =
+ file.type.startsWith("video/") ||
+ /\.(mov|mp4|avi|mkv|webm|m4v)$/i.test(file.name);
+ if (!isVideo) {
+ toast.error("Please drop a video file.");
+ return;
+ }
+ await processFile(file);
+ },
+ [processFile],
+ );
+
+ const handleBrowseClick = () => {
+ if (!user) return;
+
+ if (!user.isPro) {
+ setUpgradeModalOpen(true);
+ return;
+ }
+
+ inputRef.current?.click();
+ };
+
+ const uploadStatus = useStore(uploadingStore, (s) => s.uploadStatus);
+ const progressPercent =
+ uploadStatus && "progress" in uploadStatus
+ ? Math.round(uploadStatus.progress)
+ : null;
+ const statusLabel = uploadStatus
+ ? uploadStatus.status === "parsing"
+ ? "Analyzing video..."
+ : uploadStatus.status === "creating"
+ ? "Preparing upload..."
+ : uploadStatus.status === "uploadingVideo"
+ ? `Uploading... ${progressPercent ?? 0}%`
+ : uploadStatus.status === "serverProcessing"
+ ? "Processing on server..."
+ : "Working..."
+ : null;
+
+ return (
+ <div className="flex flex-col w-full h-full">
+ <div className="mb-8">
+ <Link
+ href="/dashboard/import"
+ className="inline-flex gap-2 items-center text-sm text-gray-10 hover:text-gray-12 transition-colors mb-4"
+ >
+ <FontAwesomeIcon className="size-3" icon={faArrowLeft} />
+ Back to Import
+ </Link>
+ <h1 className="text-2xl font-medium text-gray-12">Upload File</h1>
+ <p className="mt-1 text-sm text-gray-10">
+ Upload a video file from your device.
+ </p>
+ </div>
+
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ if (!isUploading) setIsDragOver(true);
+ }}
+ onDragLeave={() => setIsDragOver(false)}
+ onDrop={handleDrop}
+ className={`relative flex flex-col items-center justify-center w-full max-w-2xl rounded-xl border-2 border-dashed transition-all duration-200 py-16 px-8 ${
+ isUploading
+ ? "border-gray-4 bg-gray-2 cursor-not-allowed"
+ : isDragOver
+ ? "border-blue-10 bg-blue-3"
+ : "border-gray-4 bg-gray-1 hover:border-gray-6 hover:bg-gray-2"
+ }`}
+ >
+ {isUploading ? (
+ <div className="flex flex-col items-center gap-4">
+ <div className="flex items-center justify-center size-16 rounded-full bg-gray-3">
+ <div className="size-6 border-2 border-gray-8 border-t-blue-10 rounded-full animate-spin" />
+ </div>
+ <div className="flex flex-col items-center gap-1">
+ <p className="text-sm font-medium text-gray-12">{statusLabel}</p>
+ {progressPercent !== null && (
+ <div className="w-48 h-1.5 rounded-full bg-gray-4 mt-2 overflow-hidden">
+ <div
+ className="h-full rounded-full bg-blue-10 transition-all duration-300"
+ style={{ width: `${progressPercent}%` }}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col items-center gap-4">
+ <div className="flex items-center justify-center size-16 rounded-full bg-gray-3 text-gray-10">
+ <FontAwesomeIcon className="size-6" icon={faUpload} />
+ </div>
+ <div className="flex flex-col items-center gap-1">
+ <p className="text-sm font-medium text-gray-12">
+ Drag and drop your video here
+ </p>
+ <p className="text-xs text-gray-10">
+ MP4, MOV, AVI, MKV, WebM up to any size
+ </p>
+ </div>
+ <Button
+ onClick={handleBrowseClick}
+ variant="dark"
+ size="sm"
+ className="mt-2"
+ >
+ Browse Files
+ </Button>
+ </div>
+ )}
+ </div>
+
+ <input
+ ref={inputRef}
+ type="file"
+ accept="video/*,.mov,.MOV,.mp4,.MP4,.avi,.AVI,.mkv,.MKV,.webm,.WEBM,.m4v,.M4V"
+ onChange={handleFileChange}
+ className="hidden"
+ />
+
+ <UpgradeModal
+ open={upgradeModalOpen}
+ onOpenChange={setUpgradeModalOpen}
+ />
+ </div>
+ );
+};
+
+async function uploadVideoForServerProcessing(
+ file: File,
+ folderId: Folder.FolderId | undefined,
+ orgId: Organisation.OrganisationId,
+ setUploadStatus: (state: UploadStatus | undefined) => void,
+) {
+ try {
+ setUploadStatus({ status: "parsing" });
+
+ let duration: number | undefined;
+ let resolution: string | undefined;
+
+ try {
+ const parser = await import("@remotion/media-parser");
+ const metadata = await parser.parseMedia({
+ src: file,
+ fields: {
+ durationInSeconds: true,
+ dimensions: true,
+ },
+ });
+
+ duration = metadata.durationInSeconds
+ ? Math.round(metadata.durationInSeconds)
+ : undefined;
+ resolution = metadata.dimensions
+ ? `${metadata.dimensions.width}x${metadata.dimensions.height}`
+ : undefined;
+ } catch (parseError) {
+ console.warn(
+ "Failed to parse video metadata, continuing without it:",
+ parseError,
+ );
+ }
+
+ setUploadStatus({ status: "creating" });
+ const videoData = await createVideoForServerProcessing({
+ duration,
+ resolution,
+ folderId,
+ orgId,
+ });
+
+ const uploadId = videoData.id;
+
+ setUploadStatus({
+ status: "uploadingVideo",
+ capId: uploadId,
+ progress: 0,
+ thumbnailUrl: undefined,
+ });
+
+ const formData = new FormData();
+ Object.entries(videoData.presignedPostData.fields).forEach(
+ ([key, value]) => {
+ formData.append(key, value as string);
+ },
+ );
+ formData.append("file", file);
+
+ const createProgressTracker = () => {
+ const uploadState = {
+ videoId: uploadId,
+ uploaded: 0,
+ total: 0,
+ pendingTask: undefined as ReturnType<typeof setTimeout> | undefined,
+ lastUpdateTime: Date.now(),
+ };
+
+ const scheduleProgressUpdate = (uploaded: number, total: number) => {
+ uploadState.uploaded = uploaded;
+ uploadState.total = total;
+ uploadState.lastUpdateTime = Date.now();
+
+ if (uploadState.pendingTask) {
+ clearTimeout(uploadState.pendingTask);
+ uploadState.pendingTask = undefined;
+ }
+
+ const shouldSendImmediately = uploaded >= total;
+
+ if (!shouldSendImmediately) {
+ uploadState.pendingTask = setTimeout(() => {
+ if (uploadState.videoId) {
+ sendProgressUpdate(
+ uploadState.videoId,
+ uploadState.uploaded,
+ uploadState.total,
+ );
+ }
+ uploadState.pendingTask = undefined;
+ }, 2000);
+ }
+ };
+
+ const cleanup = () => {
+ if (uploadState.pendingTask) {
+ clearTimeout(uploadState.pendingTask);
+ uploadState.pendingTask = undefined;
+ }
+ };
+
+ const getTotal = () => uploadState.total;
+
+ return { scheduleProgressUpdate, cleanup, getTotal };
+ };
+
+ const progressTracker = createProgressTracker();
+
+ try {
+ 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;
+ setUploadStatus({
+ status: "uploadingVideo",
+ capId: uploadId,
+ progress: percent,
+ thumbnailUrl: undefined,
+ });
+
+ progressTracker.scheduleProgressUpdate(event.loaded, event.total);
+ }
+ };
+
+ xhr.onload = () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ progressTracker.cleanup();
+ const total = progressTracker.getTotal() || 1;
+ sendProgressUpdate(uploadId, total, total);
+ resolve();
+ } else {
+ progressTracker.cleanup();
+ reject(new Error(`Upload failed with status ${xhr.status}`));
+ }
+ };
+ xhr.onerror = () => {
+ progressTracker.cleanup();
+ reject(new Error("Upload failed"));
+ };
+
+ xhr.send(formData);
+ });
+ } catch (uploadError) {
+ progressTracker.cleanup();
+ throw uploadError;
+ }
+
+ setUploadStatus({
+ status: "serverProcessing",
+ capId: uploadId,
+ });
+
+ try {
+ await triggerVideoProcessing({
+ videoId: uploadId,
+ rawFileKey: videoData.rawFileKey,
+ bucketId: videoData.bucketId,
+ });
+ } catch (triggerError) {
+ console.error("Failed to trigger processing:", triggerError);
+ toast.error("Failed to start video processing. Please try again.");
+ setUploadStatus(undefined);
+ return false;
+ }
+
+ setUploadStatus(undefined);
+ toast.success(
+ "Video uploaded! Processing will continue in the background.",
+ );
+ return true;
+ } catch (err) {
+ console.error("Video upload failed", err);
+
+ if (err instanceof Error && err.message === "upgrade_required") {
+ toast.error(
+ "Video duration exceeds the limit for free accounts. Please upgrade to Pro.",
+ );
+ } else {
+ toast.error("Failed to upload video. Please try again.");
+ }
+ }
+
+ setUploadStatus(undefined);
+ return false;
+}
diff --git a/apps/web/app/(org)/dashboard/import/file/page.tsx b/apps/web/app/(org)/dashboard/import/file/page.tsx
new file mode 100644
index 000000000..86804a43f
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/import/file/page.tsx
@@ -0,0 +1,10 @@
+import type { Metadata } from "next";
+import { ImportFilePage } from "./ImportFilePage";
+
+export const metadata: Metadata = {
+ title: "Upload File — Cap",
+};
+
+export default function Page() {
+ return <ImportFilePage />;
+}
diff --git a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx
new file mode 100644
index 000000000..29ac3c8af
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import { Button, Input } from "@cap/ui";
+import { faArrowLeft } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { importFromLoom } from "@/actions/loom";
+import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
+import { UpgradeModal } from "@/components/UpgradeModal";
+
+export const ImportLoomPage = () => {
+ const { user, activeOrganization } = useDashboardContext();
+ const router = useRouter();
+ const [loomUrl, setLoomUrl] = useState("");
+ const [isImporting, setIsImporting] = useState(false);
+ const [upgradeModalOpen, setUpgradeModalOpen] = useState(!user?.isPro);
+
+ const handleImport = async () => {
+ if (!user || !activeOrganization) return;
+
+ if (!user.isPro) {
+ setUpgradeModalOpen(true);
+ return;
+ }
+
+ if (!loomUrl.trim()) return;
+
+ setIsImporting(true);
+
+ try {
+ const result = await importFromLoom({
+ loomUrl: loomUrl.trim(),
+ orgId: activeOrganization.organization.id,
+ });
+
+ if (!result.success) {
+ toast.error(result.error || "Failed to import video.");
+ setIsImporting(false);
+ return;
+ }
+
+ toast.success(
+ "Loom video import started! It will appear in your caps shortly.",
+ );
+ router.push("/dashboard/caps");
+ } catch {
+ toast.error("An unexpected error occurred. Please try again.");
+ } finally {
+ setIsImporting(false);
+ }
+ };
+
+ const isValidLoomUrl = (() => {
+ try {
+ const parsed = new URL(loomUrl.trim());
+ return parsed.hostname.includes("loom.com");
+ } catch {
+ return false;
+ }
+ })();
+
+ return (
+ <div className="flex flex-col w-full h-full">
+ <div className="mb-8">
+ <Link
+ href="/dashboard/import"
+ className="inline-flex gap-2 items-center text-sm text-gray-10 hover:text-gray-12 transition-colors mb-4"
+ >
+ <FontAwesomeIcon className="size-3" icon={faArrowLeft} />
+ Back to Import
+ </Link>
+ <h1 className="text-2xl font-medium text-gray-12">Import from Loom</h1>
+ <p className="mt-1 text-sm text-gray-10">
+ Paste a Loom video URL to import it to Cap.
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-6 w-full max-w-2xl">
+ <div className="flex flex-col gap-4 p-6 rounded-xl border border-gray-3 bg-gray-1">
+ <div className="flex items-center gap-3">
+ <div className="flex items-center justify-center size-10 rounded-full bg-gray-3">
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="18"
+ height="18"
+ viewBox="0 0 16 16"
+ fill="none"
+ role="img"
+ aria-label="Loom"
+ >
+ <path
+ fill="#625DF5"
+ d="M15 7.222h-4.094l3.546-2.047-.779-1.35-3.545 2.048 2.046-3.546-1.349-.779L8.78 5.093V1H7.22v4.094L5.174 1.548l-1.348.779 2.046 3.545-3.545-2.046-.779 1.348 3.546 2.047H1v1.557h4.093l-3.545 2.047.779 1.35 3.545-2.047-2.047 3.545 1.35.779 2.046-3.546V15h1.557v-4.094l2.047 3.546 1.349-.779-2.047-3.546 3.545 2.047.779-1.349-3.545-2.046h4.093L15 7.222zm-7 2.896a2.126 2.126 0 110-4.252 2.126 2.126 0 010 4.252z"
+ />
+ </svg>
+ </div>
+ <div>
+ <p className="text-sm font-medium text-gray-12">Loom Video URL</p>
+ <p className="text-xs text-gray-10">
+ The video will be downloaded and processed in the background.
+ </p>
+ </div>
+ </div>
+
+ <Input
+ value={loomUrl}
+ onChange={(e) => setLoomUrl(e.target.value)}
+ placeholder="https://www.loom.com/share/..."
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && isValidLoomUrl && !isImporting) {
+ handleImport();
+ }
+ }}
+ />
+
+ <div className="flex gap-3 justify-end">
+ <Button
+ size="sm"
+ variant="gray"
+ onClick={() => router.push("/dashboard/import")}
+ >
+ Cancel
+ </Button>
+ <Button
+ onClick={handleImport}
+ size="sm"
+ spinner={isImporting}
+ variant="dark"
+ disabled={!isValidLoomUrl || isImporting}
+ >
+ {isImporting ? "Importing..." : "Import Video"}
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ <UpgradeModal
+ open={upgradeModalOpen}
+ onOpenChange={setUpgradeModalOpen}
+ />
+ </div>
+ );
+};
diff --git a/apps/web/app/(org)/dashboard/import/loom/page.tsx b/apps/web/app/(org)/dashboard/import/loom/page.tsx
new file mode 100644
index 000000000..6e9def333
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/import/loom/page.tsx
@@ -0,0 +1,10 @@
+import type { Metadata } from "next";
+import { ImportLoomPage } from "./ImportLoomPage";
+
+export const metadata: Metadata = {
+ title: "Import from Loom — Cap",
+};
+
+export default function Page() {
+ return <ImportLoomPage />;
+}
diff --git a/apps/web/app/(org)/dashboard/import/page.tsx b/apps/web/app/(org)/dashboard/import/page.tsx
new file mode 100644
index 000000000..c7661b56c
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/import/page.tsx
@@ -0,0 +1,10 @@
+import type { Metadata } from "next";
+import { ImportPage } from "./ImportPage";
+
+export const metadata: Metadata = {
+ title: "Import — Cap",
+};
+
+export default function Page() {
+ return <ImportPage />;
+}
diff --git a/apps/web/workflows/import-loom-video.ts b/apps/web/workflows/import-loom-video.ts
new file mode 100644
index 000000000..3f2219f15
--- /dev/null
+++ b/apps/web/workflows/import-loom-video.ts
@@ -0,0 +1,258 @@
+import { db } from "@cap/database";
+import { videos, videoUploads } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import { S3Buckets } from "@cap/web-backend";
+import { S3Bucket, type Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
+import { FatalError } from "workflow";
+import { runPromise } from "@/lib/server";
+
+interface ImportLoomPayload {
+ videoId: string;
+ userId: string;
+ rawFileKey: string;
+ bucketId: string | null;
+ loomDownloadUrl: string;
+}
+
+interface VideoProcessingResult {
+ success: boolean;
+ message: string;
+ metadata?: {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ };
+}
+
+export async function importLoomVideoWorkflow(
+ payload: ImportLoomPayload,
+): Promise<VideoProcessingResult> {
+ "use workflow";
+
+ await downloadLoomToS3(payload);
+
+ const result = await processVideoOnMediaServer(payload);
+
+ await saveMetadataAndComplete(payload.videoId, result.metadata);
+
+ return {
+ success: true,
+ message: "Loom video imported successfully",
+ metadata: result.metadata,
+ };
+}
+
+async function downloadLoomToS3(payload: ImportLoomPayload): Promise<void> {
+ "use step";
+
+ const { videoId, loomDownloadUrl, rawFileKey, bucketId } = payload;
+
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "uploading",
+ processingProgress: 0,
+ processingMessage: "Downloading from Loom...",
+ rawFileKey,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId));
+
+ const bucketIdOption = Option.fromNullable(bucketId).pipe(
+ Option.map((id) => S3Bucket.S3BucketId.make(id)),
+ );
+
+ const presignedPutUrl = await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess(bucketIdOption);
+ return yield* bucket.getInternalPresignedPutUrl(rawFileKey, {
+ ContentType: "video/mp4",
+ });
+ }).pipe(runPromise);
+
+ const loomResponse = await fetch(loomDownloadUrl);
+ if (!loomResponse.ok) {
+ throw new FatalError(
+ `Failed to download from Loom: ${loomResponse.status} ${loomResponse.statusText}`,
+ );
+ }
+
+ const videoBuffer = Buffer.from(await loomResponse.arrayBuffer());
+
+ const uploadResponse = await fetch(presignedPutUrl, {
+ method: "PUT",
+ body: videoBuffer,
+ headers: {
+ "Content-Type": "video/mp4",
+ "Content-Length": videoBuffer.length.toString(),
+ },
+ });
+
+ if (!uploadResponse.ok) {
+ throw new FatalError(
+ `Failed to upload to S3: ${uploadResponse.status} ${uploadResponse.statusText}`,
+ );
+ }
+
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "processing",
+ processingProgress: 0,
+ processingMessage: "Starting video processing...",
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId));
+}
+
+interface MediaServerProcessResult {
+ metadata: {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ };
+}
+
+async function processVideoOnMediaServer(
+ payload: ImportLoomPayload,
+): Promise<MediaServerProcessResult> {
+ "use step";
+
+ const { videoId, userId, rawFileKey, bucketId } = payload;
+
+ const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
+ if (!mediaServerUrl) {
+ throw new FatalError("MEDIA_SERVER_URL is not configured");
+ }
+
+ const webhookBaseUrl =
+ serverEnv().MEDIA_SERVER_WEBHOOK_URL || serverEnv().WEB_URL;
+
+ const bucketIdOption = Option.fromNullable(bucketId).pipe(
+ Option.map((id) => S3Bucket.S3BucketId.make(id)),
+ );
+
+ const { rawVideoUrl, outputPresignedUrl, thumbnailPresignedUrl } =
+ await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess(bucketIdOption);
+
+ const outputKey = `${userId}/${videoId}/result.mp4`;
+ const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
+
+ const rawVideoUrl = yield* bucket.getInternalSignedObjectUrl(rawFileKey);
+
+ const outputPresignedUrl = yield* bucket.getInternalPresignedPutUrl(
+ outputKey,
+ { ContentType: "video/mp4" },
+ );
+
+ const thumbnailPresignedUrl = yield* bucket.getInternalPresignedPutUrl(
+ thumbnailKey,
+ {
+ ContentType: "image/jpeg",
+ },
+ );
+
+ return { rawVideoUrl, outputPresignedUrl, thumbnailPresignedUrl };
+ }).pipe(runPromise);
+
+ const webhookUrl = `${webhookBaseUrl}/api/webhooks/media-server/progress`;
+
+ const response = await fetch(`${mediaServerUrl}/video/process`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ videoId,
+ userId,
+ videoUrl: rawVideoUrl,
+ outputPresignedUrl,
+ thumbnailPresignedUrl,
+ webhookUrl,
+ }),
+ });
+
+ if (!response.ok) {
+ const errorData = (await response.json().catch(() => ({}))) as {
+ error?: string;
+ };
+ throw new Error(errorData.error || "Video processing failed to start");
+ }
+
+ const { jobId } = (await response.json()) as { jobId: string };
+
+ return await pollForCompletion(mediaServerUrl, jobId);
+}
+
+async function pollForCompletion(
+ mediaServerUrl: string,
+ jobId: string,
+): Promise<MediaServerProcessResult> {
+ const maxAttempts = 360;
+ const pollIntervalMs = 5000;
+
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
+
+ const response = await fetch(
+ `${mediaServerUrl}/video/process/${jobId}/status`,
+ {
+ method: "GET",
+ headers: { Accept: "application/json" },
+ },
+ );
+
+ if (!response.ok) continue;
+
+ const status = (await response.json()) as {
+ phase: string;
+ progress: number;
+ error?: string;
+ metadata?: {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ };
+ };
+
+ if (status.phase === "complete") {
+ if (!status.metadata) {
+ throw new Error("Processing completed but no metadata returned");
+ }
+ return { metadata: status.metadata };
+ }
+
+ if (status.phase === "error") {
+ throw new Error(status.error || "Video processing failed");
+ }
+
+ if (status.phase === "cancelled") {
+ throw new Error("Video processing was cancelled");
+ }
+ }
+
+ throw new Error("Video processing timed out");
+}
+
+async function saveMetadataAndComplete(
+ videoId: string,
+ metadata: { duration: number; width: number; height: number; fps: number },
+): Promise<void> {
+ "use step";
+
+ await db()
+ .update(videos)
+ .set({
+ width: metadata.width,
+ height: metadata.height,
+ duration: metadata.duration,
+ })
+ .where(eq(videos.id, videoId as Video.VideoId));
+
+ await db()
+ .delete(videoUploads)
+ .where(eq(videoUploads.videoId, videoId as Video.VideoId));
+}