Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add server-side video processing workflow

Richie McIlroyf77abc3480b1
diff --git a/apps/web/actions/video/create-for-processing.ts b/apps/web/actions/video/create-for-processing.ts
new file mode 100644
index 000000000..a2a6776f6
--- /dev/null
+++ b/apps/web/actions/video/create-for-processing.ts
@@ -0,0 +1,123 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { nanoId } from "@cap/database/helpers";
+import { s3Buckets, videos, videoUploads } from "@cap/database/schema";
+import { buildEnv, NODE_ENV, serverEnv } from "@cap/env";
+import { dub, userIsPro } from "@cap/utils";
+import { S3Buckets } from "@cap/web-backend";
+import {
+ type Folder,
+ type Organisation,
+ S3Bucket,
+ Video,
+} from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
+import { revalidatePath } from "next/cache";
+import { runPromise } from "@/lib/server";
+
+export interface CreateForProcessingResult {
+ id: Video.VideoId;
+ rawFileKey: string;
+ bucketId: string | null;
+ presignedPostData: {
+ url: string;
+ fields: Record<string, string>;
+ };
+}
+
+export async function createVideoForServerProcessing({
+ duration,
+ resolution,
+ folderId,
+ orgId,
+}: {
+ duration?: number;
+ resolution?: string;
+ folderId?: Folder.FolderId;
+ orgId: Organisation.OrganisationId;
+}): Promise<CreateForProcessingResult> {
+ const user = await getCurrentUser();
+
+ if (!user) throw new Error("Unauthorized");
+
+ if (!userIsPro(user) && duration && duration > 300) {
+ throw new Error("upgrade_required");
+ }
+
+ const [customBucket] = await db()
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
+
+ const videoId = Video.VideoId.make(nanoId());
+
+ const date = new Date();
+ const formattedDate = `${date.getDate()} ${date.toLocaleString("default", {
+ month: "long",
+ })} ${date.getFullYear()}`;
+
+ await db()
+ .insert(videos)
+ .values({
+ id: videoId,
+ name: `Cap Upload - ${formattedDate}`,
+ ownerId: user.id,
+ orgId,
+ source: { type: "webMP4" as const },
+ bucket: customBucket?.id,
+ public: serverEnv().CAP_VIDEOS_DEFAULT_PUBLIC,
+ ...(folderId ? { folderId } : {}),
+ });
+
+ await db().insert(videoUploads).values({
+ videoId,
+ phase: "uploading",
+ processingProgress: 0,
+ });
+
+ const rawFileKey = `${user.id}/${videoId}/raw-upload.mp4`;
+
+ const bucketIdOption = Option.fromNullable(customBucket?.id).pipe(
+ Option.map((id) => S3Bucket.S3BucketId.make(id)),
+ );
+
+ const presignedPostData = await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess(bucketIdOption);
+
+ return yield* bucket.getPresignedPostUrl(rawFileKey, {
+ Fields: {
+ "Content-Type": "video/mp4",
+ "x-amz-meta-userid": user.id,
+ "x-amz-meta-duration": duration?.toString() ?? "",
+ "x-amz-meta-resolution": resolution ?? "",
+ },
+ Expires: 3600,
+ });
+ }).pipe(runPromise);
+
+ 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((err) => {
+ console.error("Dub link create failed", err);
+ });
+ }
+
+ revalidatePath("/dashboard/caps");
+ revalidatePath("/dashboard/folder");
+ revalidatePath("/dashboard/spaces");
+
+ return {
+ id: videoId,
+ rawFileKey,
+ bucketId: customBucket?.id ?? null,
+ presignedPostData,
+ };
+}
diff --git a/apps/web/actions/video/retry-processing.ts b/apps/web/actions/video/retry-processing.ts
new file mode 100644
index 000000000..18df09624
--- /dev/null
+++ b/apps/web/actions/video/retry-processing.ts
@@ -0,0 +1,56 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos, videoUploads } from "@cap/database/schema";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { start } from "workflow/api";
+import { processVideoWorkflow } from "@/workflows/process-video";
+
+export async function retryVideoProcessing({
+ videoId,
+}: {
+ videoId: Video.VideoId;
+}): Promise<{ success: boolean }> {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId));
+
+ if (!video) throw new Error("Video not found");
+ if (video.ownerId !== user.id) throw new Error("Unauthorized");
+
+ const [upload] = await db()
+ .select()
+ .from(videoUploads)
+ .where(eq(videoUploads.videoId, videoId));
+
+ if (!upload) throw new Error("No upload record found");
+ if (!upload.rawFileKey) throw new Error("No raw file key found for retry");
+
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "processing",
+ processingProgress: 0,
+ processingMessage: "Retrying video processing...",
+ processingError: null,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, videoId));
+
+ await start(processVideoWorkflow, [
+ {
+ videoId,
+ userId: user.id,
+ rawFileKey: upload.rawFileKey,
+ bucketId: video.bucket ?? null,
+ },
+ ]);
+
+ return { success: true };
+}
diff --git a/apps/web/actions/video/trigger-processing.ts b/apps/web/actions/video/trigger-processing.ts
new file mode 100644
index 000000000..5f7d6f267
--- /dev/null
+++ b/apps/web/actions/video/trigger-processing.ts
@@ -0,0 +1,52 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { videos, videoUploads } from "@cap/database/schema";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { start } from "workflow/api";
+import { processVideoWorkflow } from "@/workflows/process-video";
+
+export async function triggerVideoProcessing({
+ videoId,
+ rawFileKey,
+ bucketId,
+}: {
+ videoId: Video.VideoId;
+ rawFileKey: string;
+ bucketId: string | null;
+}): Promise<{ success: boolean }> {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId));
+
+ if (!video) throw new Error("Video not found");
+ if (video.ownerId !== user.id) throw new Error("Unauthorized");
+
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "processing",
+ processingProgress: 0,
+ processingMessage: "Starting video processing...",
+ rawFileKey,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, videoId));
+
+ await start(processVideoWorkflow, [
+ {
+ videoId,
+ userId: user.id,
+ rawFileKey,
+ bucketId,
+ },
+ ]);
+
+ return { success: true };
+}
diff --git a/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx b/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx
index a24220c15..c87f4f268 100644
--- a/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx
+++ b/apps/web/app/(org)/dashboard/caps/UploadingContext.tsx
@@ -27,6 +27,10 @@ export type UploadStatus =
capId: string;
progress: number;
thumbnailUrl: string | undefined;
+ }
+ | {
+ status: "serverProcessing";
+ capId: string;
};
interface UploadingContextType {
diff --git a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
index 035cc17d3..c9e807075 100644
--- a/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/CapCard/CapCard.tsx
@@ -571,7 +571,8 @@ export const CapCard = ({
<div className="relative inset-0 z-20 w-full h-full">
<div className="overflow-hidden relative mx-auto w-full h-full bg-black rounded-t-xl border-b border-gray-3 aspect-video z-5">
<div className="flex absolute inset-0 justify-center items-center rounded-t-xl">
- {uploadProgress.status === "failed" ? (
+ {uploadProgress.status === "failed" ||
+ uploadProgress.status === "error" ? (
<div className="flex flex-col items-center">
<div className="flex justify-center items-center mb-2 w-8 h-8 bg-red-500 rounded-full">
<FontAwesomeIcon
@@ -580,7 +581,9 @@ export const CapCard = ({
/>
</div>
<p className="text-[13px] text-center text-white">
- Upload failed
+ {uploadProgress.status === "error"
+ ? "Processing failed"
+ : "Upload failed"}
</p>
</div>
) : (
@@ -590,6 +593,18 @@ export const CapCard = ({
subTextClassName="!mt-0 md:!text-[7px] !text-[10px] mb-1"
className="md:scale-[1.5] scale-[1.2]"
progress={uploadProgress.progress}
+ status={
+ uploadProgress.status === "processing"
+ ? "processing"
+ : uploadProgress.status === "generating_thumbnail"
+ ? "generating_thumbnail"
+ : "uploading"
+ }
+ message={
+ uploadProgress.status === "processing"
+ ? uploadProgress.message
+ : undefined
+ }
/>
</div>
)}
diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
index 4044c1416..17f3661ab 100644
--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx
@@ -4,19 +4,19 @@ 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 { type QueryClient, useQueryClient } from "@tanstack/react-query";
+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 { createVideoAndGetUploadUrl } from "@/actions/video/upload";
+import { createVideoForServerProcessing } from "@/actions/video/create-for-processing";
+import { triggerVideoProcessing } from "@/actions/video/trigger-processing";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import {
type UploadStatus,
useUploadingContext,
} from "@/app/(org)/dashboard/caps/UploadingContext";
import { UpgradeModal } from "@/components/UpgradeModal";
-import { ThumbnailRequest } from "@/lib/Requests/ThumbnailRequest";
import { sendProgressUpdate } from "./sendProgressUpdate";
export const UploadCapButton = ({
@@ -50,18 +50,16 @@ export const UploadCapButton = ({
const file = e.target.files?.[0];
if (!file || !user) return;
- // This should be unreachable.
if (activeOrganization === null) {
alert("No organization active!");
return;
}
- const ok = await legacyUploadCap(
+ const ok = await uploadVideoForServerProcessing(
file,
folderId,
activeOrganization.organization.id,
setUploadStatus,
- queryClient,
);
if (ok) router.refresh();
if (inputRef.current) inputRef.current.value = "";
@@ -95,249 +93,57 @@ export const UploadCapButton = ({
);
};
-async function legacyUploadCap(
+async function uploadVideoForServerProcessing(
file: File,
folderId: Folder.FolderId | undefined,
orgId: Organisation.OrganisationId,
setUploadStatus: (state: UploadStatus | undefined) => void,
- queryClient: QueryClient,
) {
- const parser = await import("@remotion/media-parser");
- const webcodecs = await import("@remotion/webcodecs");
-
try {
setUploadStatus({ status: "parsing" });
- 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;
-
- setUploadStatus({ status: "creating" });
- const videoData = await createVideoAndGetUploadUrl({
- duration,
- resolution: metadata.dimensions
- ? `${metadata.dimensions.width}x${metadata.dimensions.height}`
- : undefined,
- videoCodec: "h264",
- audioCodec: "aac",
- isScreenshot: false,
- isUpload: true,
- folderId,
- orgId,
- });
-
- const uploadId = videoData.id;
- setUploadStatus({ status: "converting", capId: uploadId, progress: 0 });
-
- let optimizedBlob: Blob;
+ let duration: number | undefined;
+ let resolution: string | undefined;
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({
+ const parser = await import("@remotion/media-parser");
+ const metadata = await parser.parseMedia({
src: file,
- container: "mp4",
- videoCodec: "h264",
- audioCodec: "aac",
- ...(resizeOptions && { resize: resizeOptions }),
- onProgress: ({ overallProgress }) => {
- if (overallProgress !== null) {
- const progressValue = overallProgress * 100;
- setUploadStatus({
- status: "converting",
- capId: uploadId,
- progress: progressValue,
- });
- }
+ fields: {
+ durationInSeconds: true,
+ dimensions: true,
},
});
- 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 &&
- !Number.isNaN(testVideo.duration) &&
- Number.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.",
+ 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(undefined);
- return false;
}
- 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);
- });
+ setUploadStatus({ status: "creating" });
+ const videoData = await createVideoForServerProcessing({
+ duration,
+ resolution,
+ folderId,
+ orgId,
+ });
- video.addEventListener("loadstart", () => {});
- });
- };
+ const uploadId = videoData.id;
- const thumbnailBlob = await captureThumbnail();
- const thumbnailUrl = thumbnailBlob
- ? URL.createObjectURL(thumbnailBlob)
- : undefined;
+ setUploadStatus({
+ status: "uploadingVideo",
+ capId: uploadId,
+ progress: 0,
+ thumbnailUrl: undefined,
+ });
const formData = new FormData();
Object.entries(videoData.presignedPostData.fields).forEach(
@@ -345,16 +151,8 @@ async function legacyUploadCap(
formData.append(key, value as string);
},
);
- formData.append("file", optimizedBlob);
-
- setUploadStatus({
- status: "uploadingVideo",
- capId: uploadId,
- progress: 0,
- thumbnailUrl,
- });
+ formData.append("file", file);
- // Create progress tracking state outside React
const createProgressTracker = () => {
const uploadState = {
videoId: uploadId,
@@ -369,7 +167,6 @@ async function legacyUploadCap(
uploadState.total = total;
uploadState.lastUpdateTime = Date.now();
- // Clear any existing pending task
if (uploadState.pendingTask) {
clearTimeout(uploadState.pendingTask);
uploadState.pendingTask = undefined;
@@ -378,11 +175,8 @@ async function legacyUploadCap(
const shouldSendImmediately = uploaded >= total;
if (shouldSendImmediately) {
- // Don't send completion update immediately - let xhr.onload handle it
- // to avoid double progress updates
return;
} else {
- // Schedule delayed update (after 2 seconds)
uploadState.pendingTask = setTimeout(() => {
if (uploadState.videoId) {
sendProgressUpdate(
@@ -422,7 +216,7 @@ async function legacyUploadCap(
status: "uploadingVideo",
capId: uploadId,
progress: percent,
- thumbnailUrl,
+ thumbnailUrl: undefined,
});
progressTracker.scheduleProgressUpdate(event.loaded, event.total);
@@ -432,7 +226,6 @@ async function legacyUploadCap(
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
progressTracker.cleanup();
- // Guarantee final 100% progress update
const total = progressTracker.getTotal() || 1;
sendProgressUpdate(uploadId, total, total);
resolve();
@@ -453,65 +246,39 @@ async function legacyUploadCap(
throw uploadError;
}
- if (thumbnailBlob) {
- const screenshotData = await createVideoAndGetUploadUrl({
- videoId: uploadId,
- isScreenshot: true,
- isUpload: true,
- orgId,
- });
-
- const screenshotFormData = new FormData();
- Object.entries(screenshotData.presignedPostData.fields).forEach(
- ([key, value]) => {
- screenshotFormData.append(key, value as string);
- },
- );
- screenshotFormData.append("file", thumbnailBlob);
-
- setUploadStatus({
- status: "uploadingThumbnail",
- capId: uploadId,
- progress: 0,
- });
- 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;
- setUploadStatus({
- status: "uploadingThumbnail",
- capId: uploadId,
- progress: thumbnailProgress,
- });
- }
- };
-
- xhr.onload = () => {
- if (xhr.status >= 200 && xhr.status < 300) {
- resolve();
- queryClient.refetchQueries({
- queryKey: ThumbnailRequest.queryKey(uploadId),
- });
- } else {
- reject(
- new Error(`Screenshot upload failed with status ${xhr.status}`),
- );
- }
- };
- xhr.onerror = () => reject(new Error("Screenshot upload failed"));
+ setUploadStatus({
+ status: "serverProcessing",
+ capId: uploadId,
+ });
- xhr.send(screenshotFormData);
+ 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);
diff --git a/apps/web/app/api/webhooks/media-server/progress/route.ts b/apps/web/app/api/webhooks/media-server/progress/route.ts
new file mode 100644
index 000000000..5fac75e2c
--- /dev/null
+++ b/apps/web/app/api/webhooks/media-server/progress/route.ts
@@ -0,0 +1,123 @@
+import { db } from "@cap/database";
+import { videos, videoUploads } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import type { Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { type NextRequest, NextResponse } from "next/server";
+
+interface ProgressWebhookPayload {
+ jobId: string;
+ videoId: string;
+ phase:
+ | "queued"
+ | "downloading"
+ | "probing"
+ | "processing"
+ | "uploading"
+ | "generating_thumbnail"
+ | "complete"
+ | "error"
+ | "cancelled";
+ progress: number;
+ message?: string;
+ error?: string;
+ metadata?: {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ videoCodec: string;
+ audioCodec: string | null;
+ audioChannels: number | null;
+ sampleRate: number | null;
+ bitrate: number;
+ fileSize: number;
+ };
+}
+
+function mapPhaseToDbPhase(
+ phase: ProgressWebhookPayload["phase"],
+): "uploading" | "processing" | "generating_thumbnail" | "complete" | "error" {
+ switch (phase) {
+ case "queued":
+ case "downloading":
+ case "probing":
+ case "processing":
+ case "uploading":
+ return "processing";
+ case "generating_thumbnail":
+ return "generating_thumbnail";
+ case "complete":
+ return "complete";
+ case "error":
+ case "cancelled":
+ return "error";
+ default:
+ return "processing";
+ }
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const webhookSecret = serverEnv().MEDIA_SERVER_WEBHOOK_SECRET;
+ if (webhookSecret) {
+ const authHeader = request.headers.get("x-media-server-secret");
+ if (authHeader !== webhookSecret) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+ }
+
+ const payload: ProgressWebhookPayload = await request.json();
+
+ console.log(
+ `[media-server-webhook] Received progress update for video ${payload.videoId}: ${payload.phase} (${payload.progress}%)`,
+ );
+
+ const dbPhase = mapPhaseToDbPhase(payload.phase);
+
+ if (dbPhase === "complete") {
+ if (payload.metadata) {
+ await db()
+ .update(videos)
+ .set({
+ width: payload.metadata.width,
+ height: payload.metadata.height,
+ duration: payload.metadata.duration,
+ })
+ .where(eq(videos.id, payload.videoId as Video.VideoId));
+ }
+
+ await db()
+ .delete(videoUploads)
+ .where(eq(videoUploads.videoId, payload.videoId as Video.VideoId));
+ } else if (dbPhase === "error") {
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "error",
+ processingError: payload.error || payload.message || "Unknown error",
+ processingMessage: payload.message,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, payload.videoId as Video.VideoId));
+ } else {
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: dbPhase,
+ processingProgress: Math.round(payload.progress),
+ processingMessage: payload.message,
+ updatedAt: new Date(),
+ })
+ .where(eq(videoUploads.videoId, payload.videoId as Video.VideoId));
+ }
+
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("[media-server-webhook] Error processing webhook:", error);
+ return NextResponse.json(
+ { error: "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx b/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
index ce5a6c3ae..1b66691fe 100644
--- a/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
+++ b/apps/web/app/s/[videoId]/_components/ProgressCircle.tsx
@@ -12,6 +12,22 @@ type UploadProgress =
lastUpdated: Date;
progress: number;
}
+ | {
+ status: "processing";
+ lastUpdated: Date;
+ progress: number;
+ message: string | null;
+ }
+ | {
+ status: "generating_thumbnail";
+ lastUpdated: Date;
+ progress: number;
+ }
+ | {
+ status: "error";
+ lastUpdated: Date;
+ errorMessage: string | null;
+ }
| {
status: "failed";
lastUpdated: Date;
@@ -51,36 +67,84 @@ export function useUploadProgress(
if (!query.data) return null;
const lastUpdated = new Date(query.data.updatedAt);
+ const phase = query.data.phase;
+
+ if (phase === "complete") return null;
+
+ if (phase === "error") {
+ return {
+ status: "error",
+ lastUpdated,
+ errorMessage: Option.getOrNull(query.data.processingError),
+ };
+ }
+
+ if (phase === "processing") {
+ return {
+ status: "processing",
+ lastUpdated,
+ progress: query.data.processingProgress,
+ message: Option.getOrNull(query.data.processingMessage),
+ };
+ }
+
+ if (phase === "generating_thumbnail") {
+ return {
+ status: "generating_thumbnail",
+ lastUpdated,
+ progress: query.data.processingProgress,
+ };
+ }
- return query.data.total > 0 && query.data.uploaded >= query.data.total
- ? null
- : Date.now() - lastUpdated.getTime() > 5 * MINUTE
- ? {
- status: "failed",
- lastUpdated,
- }
- : {
- status: "uploading",
- lastUpdated,
- progress:
- // `0/0` for progress is `NaN`
- query.data.total === 0
- ? 0
- : (query.data.uploaded / query.data.total) * 100,
- };
+ const isUploadComplete =
+ query.data.total > 0 && query.data.uploaded >= query.data.total;
+ if (isUploadComplete) return null;
+
+ if (Date.now() - lastUpdated.getTime() > 5 * MINUTE) {
+ return {
+ status: "failed",
+ lastUpdated,
+ };
+ }
+
+ return {
+ status: "uploading",
+ lastUpdated,
+ progress:
+ query.data.total === 0
+ ? 0
+ : (query.data.uploaded / query.data.total) * 100,
+ };
}
const ProgressCircle = ({
progress,
+ status = "uploading",
+ message,
className,
progressTextClassName,
subTextClassName,
}: {
progress: number;
+ status?: "uploading" | "processing" | "generating_thumbnail";
+ message?: string | null;
className?: string;
progressTextClassName?: string;
subTextClassName?: string;
}) => {
+ const strokeColor = status === "uploading" ? "#3b82f6" : "#22c55e";
+
+ const getStatusText = () => {
+ switch (status) {
+ case "processing":
+ return message || "Processing...";
+ case "generating_thumbnail":
+ return "Generating thumbnail...";
+ default:
+ return "Uploading...";
+ }
+ };
+
return (
<div
className={clsx(
@@ -103,7 +167,7 @@ const ProgressCircle = ({
cy="50"
r="45"
fill="none"
- stroke="#3b82f6"
+ stroke={strokeColor}
strokeWidth="5"
strokeLinecap="round"
strokeDasharray={`${2 * Math.PI * 45}`}
@@ -123,11 +187,11 @@ const ProgressCircle = ({
</p>
<p
className={clsx(
- "mt-0.5 leading-tight text-[10px] text-white/80",
+ "mt-0.5 leading-tight text-[10px] text-white/80 text-center",
subTextClassName,
)}
>
- Uploading...
+ {getStatusText()}
</p>
</div>
</div>
diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.ts
new file mode 100644
index 000000000..a197c57c7
--- /dev/null
+++ b/apps/web/workflows/process-video.ts
@@ -0,0 +1,235 @@
+import { db } from "@cap/database";
+import { s3Buckets, videos, videoUploads } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import { S3Buckets } from "@cap/web-backend";
+import type { S3Bucket, Video } from "@cap/web-domain";
+import { eq } from "drizzle-orm";
+import { Option } from "effect";
+import { FatalError } from "workflow";
+import { runPromise } from "@/lib/server";
+
+interface ProcessVideoWorkflowPayload {
+ videoId: string;
+ userId: string;
+ rawFileKey: string;
+ bucketId: string | null;
+}
+
+interface VideoProcessingResult {
+ success: boolean;
+ message: string;
+ metadata?: {
+ duration: number;
+ width: number;
+ height: number;
+ fps: number;
+ };
+}
+
+export async function processVideoWorkflow(
+ payload: ProcessVideoWorkflowPayload,
+): Promise<VideoProcessingResult> {
+ "use workflow";
+
+ const { videoId, userId, rawFileKey, bucketId } = payload;
+
+ await validateAndSetProcessing(videoId, rawFileKey);
+
+ const result = await processVideoOnMediaServer(
+ videoId,
+ userId,
+ rawFileKey,
+ bucketId,
+ );
+
+ await saveMetadataAndComplete(videoId, result.metadata);
+
+ return {
+ success: true,
+ message: "Video processing completed",
+ metadata: result.metadata,
+ };
+}
+
+async function validateAndSetProcessing(
+ videoId: string,
+ rawFileKey: string,
+): Promise<void> {
+ "use step";
+
+ const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
+ if (!mediaServerUrl) {
+ throw new FatalError("MEDIA_SERVER_URL is not configured");
+ }
+
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, videoId as Video.VideoId));
+
+ if (!video) {
+ throw new FatalError("Video does not exist");
+ }
+
+ await db()
+ .update(videoUploads)
+ .set({
+ phase: "processing",
+ processingProgress: 0,
+ processingMessage: "Starting video processing...",
+ rawFileKey,
+ 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(
+ videoId: string,
+ userId: string,
+ rawFileKey: string,
+ bucketId: string | null,
+): Promise<MediaServerProcessResult> {
+ "use step";
+
+ const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
+ const webhookBaseUrl =
+ serverEnv().MEDIA_SERVER_WEBHOOK_URL || serverEnv().WEB_URL;
+
+ const [bucket] = await S3Buckets.getBucketAccess(
+ Option.fromNullable(bucketId as S3Bucket.S3BucketId | null),
+ ).pipe(runPromise);
+
+ const rawVideoUrl = await bucket
+ .getInternalSignedObjectUrl(rawFileKey)
+ .pipe(runPromise);
+
+ const outputKey = `${userId}/${videoId}/result.mp4`;
+ const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
+
+ const outputPresignedUrl = await bucket
+ .getInternalPresignedPutUrl(outputKey, {
+ ContentType: "video/mp4",
+ })
+ .pipe(runPromise);
+
+ const thumbnailPresignedUrl = await bucket
+ .getInternalPresignedPutUrl(thumbnailKey, {
+ ContentType: "image/jpeg",
+ })
+ .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(() => ({}));
+ throw new Error(
+ (errorData as { error?: string }).error ||
+ "Video processing failed to start",
+ );
+ }
+
+ const { jobId } = (await response.json()) as { jobId: string };
+
+ const result = await pollForCompletion(mediaServerUrl!, jobId, videoId);
+
+ return result;
+}
+
+async function pollForCompletion(
+ mediaServerUrl: string,
+ jobId: string,
+ videoId: 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) {
+ console.warn(
+ `[process-video] Failed to get job status: ${response.status}`,
+ );
+ 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));
+}
diff --git a/docker-compose.template.yml b/docker-compose.template.yml
index 437a3b1d0..90d15049a 100644
--- a/docker-compose.template.yml
+++ b/docker-compose.template.yml
@@ -24,6 +24,9 @@ services:
S3_PUBLIC_ENDPOINT: http://localhost:3902
S3_INTERNAL_ENDPOINT: http://minio:3902
MEDIA_SERVER_URL: http://cap-media-server:3456
+ # CHANGE THESE TO YOUR OWN VALUES
+ MEDIA_SERVER_WEBHOOK_SECRET: fe337b52749070bb7b5d2c78cff9948439ea73cbc1869ba39d350e6c24db53b1
+
ports:
- 3000:3000
diff --git a/packages/database/migrations/0009_easy_ulik.sql b/packages/database/migrations/0009_easy_ulik.sql
new file mode 100644
index 000000000..e0bceaf31
--- /dev/null
+++ b/packages/database/migrations/0009_easy_ulik.sql
@@ -0,0 +1,5 @@
+ALTER TABLE `video_uploads` ADD `phase` varchar(32) DEFAULT 'uploading' NOT NULL;--> statement-breakpoint
+ALTER TABLE `video_uploads` ADD `processing_progress` int DEFAULT 0 NOT NULL;--> statement-breakpoint
+ALTER TABLE `video_uploads` ADD `processing_message` varchar(255);--> statement-breakpoint
+ALTER TABLE `video_uploads` ADD `processing_error` text;--> statement-breakpoint
+ALTER TABLE `video_uploads` ADD `raw_file_key` varchar(512);
\ No newline at end of file
diff --git a/packages/database/migrations/meta/0009_snapshot.json b/packages/database/migrations/meta/0009_snapshot.json
new file mode 100644
index 000000000..08760fb05
--- /dev/null
+++ b/packages/database/migrations/meta/0009_snapshot.json
@@ -0,0 +1,1884 @@
+{
+ "version": "5",
+ "dialect": "mysql",
+ "id": "a09515bf-37f0-479a-9e60-1f5ffef3790c",
+ "prevId": "bfb0c13d-cfec-4ae3-b80f-4dbbb99bacbd",
+ "tables": {
+ "accounts": {
+ "name": "accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_in": {
+ "name": "expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_in": {
+ "name": "refresh_token_expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "tempColumn": {
+ "name": "tempColumn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ },
+ "provider_account_id_idx": {
+ "name": "provider_account_id_idx",
+ "columns": ["providerAccountId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "accounts_id": {
+ "name": "accounts_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "auth_api_keys": {
+ "name": "auth_api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(36)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "auth_api_keys_id": {
+ "name": "auth_api_keys_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "comments": {
+ "name": "comments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(6)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "authorId": {
+ "name": "authorId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "parentCommentId": {
+ "name": "parentCommentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "video_type_created_idx": {
+ "name": "video_type_created_idx",
+ "columns": ["videoId", "type", "createdAt", "id"],
+ "isUnique": false
+ },
+ "author_id_idx": {
+ "name": "author_id_idx",
+ "columns": ["authorId"],
+ "isUnique": false
+ },
+ "parent_comment_id_idx": {
+ "name": "parent_comment_id_idx",
+ "columns": ["parentCommentId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "comments_id": {
+ "name": "comments_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "folders": {
+ "name": "folders",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "varchar(16)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "created_by_id_idx": {
+ "name": "created_by_id_idx",
+ "columns": ["createdById"],
+ "isUnique": false
+ },
+ "parent_id_idx": {
+ "name": "parent_id_idx",
+ "columns": ["parentId"],
+ "isUnique": false
+ },
+ "space_id_idx": {
+ "name": "space_id_idx",
+ "columns": ["spaceId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "folders_id": {
+ "name": "folders_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "imported_videos": {
+ "name": "imported_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source_id": {
+ "name": "source_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "imported_videos_orgId_source_source_id_pk": {
+ "name": "imported_videos_orgId_source_source_id_pk",
+ "columns": ["orgId", "source", "source_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "notifications": {
+ "name": "notifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "recipientId": {
+ "name": "recipientId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(10)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "data": {
+ "name": "data",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "readAt": {
+ "name": "readAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "org_id_idx": {
+ "name": "org_id_idx",
+ "columns": ["orgId"],
+ "isUnique": false
+ },
+ "type_idx": {
+ "name": "type_idx",
+ "columns": ["type"],
+ "isUnique": false
+ },
+ "read_at_idx": {
+ "name": "read_at_idx",
+ "columns": ["readAt"],
+ "isUnique": false
+ },
+ "created_at_idx": {
+ "name": "created_at_idx",
+ "columns": ["createdAt"],
+ "isUnique": false
+ },
+ "recipient_read_idx": {
+ "name": "recipient_read_idx",
+ "columns": ["recipientId", "readAt"],
+ "isUnique": false
+ },
+ "recipient_created_idx": {
+ "name": "recipient_created_idx",
+ "columns": ["recipientId", "createdAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "notifications_id": {
+ "name": "notifications_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_invites": {
+ "name": "organization_invites",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedEmail": {
+ "name": "invitedEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedByUserId": {
+ "name": "invitedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "invited_email_idx": {
+ "name": "invited_email_idx",
+ "columns": ["invitedEmail"],
+ "isUnique": false
+ },
+ "invited_by_user_id_idx": {
+ "name": "invited_by_user_id_idx",
+ "columns": ["invitedByUserId"],
+ "isUnique": false
+ },
+ "status_idx": {
+ "name": "status_idx",
+ "columns": ["status"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_invites_id": {
+ "name": "organization_invites_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organization_members": {
+ "name": "organization_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "user_id_organization_id_idx": {
+ "name": "user_id_organization_id_idx",
+ "columns": ["userId", "organizationId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organization_members_id": {
+ "name": "organization_members_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tombstoneAt": {
+ "name": "tombstoneAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "allowedEmailDomain": {
+ "name": "allowedEmailDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customDomain": {
+ "name": "customDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "domainVerified": {
+ "name": "domainVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "iconUrl": {
+ "name": "iconUrl",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "workosOrganizationId": {
+ "name": "workosOrganizationId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workosConnectionId": {
+ "name": "workosConnectionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "owner_id_tombstone_idx": {
+ "name": "owner_id_tombstone_idx",
+ "columns": ["ownerId", "tombstoneAt"],
+ "isUnique": false
+ },
+ "custom_domain_idx": {
+ "name": "custom_domain_idx",
+ "columns": ["customDomain"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "organizations_id": {
+ "name": "organizations_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "s3_buckets": {
+ "name": "s3_buckets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bucketName": {
+ "name": "bucketName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accessKeyId": {
+ "name": "accessKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secretAccessKey": {
+ "name": "secretAccessKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('aws')"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "s3_buckets_id": {
+ "name": "s3_buckets_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "session_token_idx": {
+ "name": "session_token_idx",
+ "columns": ["sessionToken"],
+ "isUnique": true
+ },
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "sessions_id": {
+ "name": "sessions_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "shared_videos": {
+ "name": "shared_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedByUserId": {
+ "name": "sharedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedAt": {
+ "name": "sharedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "shared_by_user_id_idx": {
+ "name": "shared_by_user_id_idx",
+ "columns": ["sharedByUserId"],
+ "isUnique": false
+ },
+ "video_id_organization_id_idx": {
+ "name": "video_id_organization_id_idx",
+ "columns": ["videoId", "organizationId"],
+ "isUnique": false
+ },
+ "video_id_folder_id_idx": {
+ "name": "video_id_folder_id_idx",
+ "columns": ["videoId", "folderId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "shared_videos_id": {
+ "name": "shared_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "space_members": {
+ "name": "space_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": ["userId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_members_id": {
+ "name": "space_members_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {
+ "space_id_user_id_unique": {
+ "name": "space_id_user_id_unique",
+ "columns": ["spaceId", "userId"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "space_videos": {
+ "name": "space_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedById": {
+ "name": "addedById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "addedAt": {
+ "name": "addedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": ["videoId"],
+ "isUnique": false
+ },
+ "added_by_id_idx": {
+ "name": "added_by_id_idx",
+ "columns": ["addedById"],
+ "isUnique": false
+ },
+ "space_id_video_id_idx": {
+ "name": "space_id_video_id_idx",
+ "columns": ["spaceId", "videoId"],
+ "isUnique": false
+ },
+ "space_id_folder_id_idx": {
+ "name": "space_id_folder_id_idx",
+ "columns": ["spaceId", "folderId"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_videos_id": {
+ "name": "space_videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "spaces": {
+ "name": "spaces",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "primary": {
+ "name": "primary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "iconUrl": {
+ "name": "iconUrl",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "varchar(1000)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "privacy": {
+ "name": "privacy",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'Private'"
+ }
+ },
+ "indexes": {
+ "organization_id_idx": {
+ "name": "organization_id_idx",
+ "columns": ["organizationId"],
+ "isUnique": false
+ },
+ "created_by_id_idx": {
+ "name": "created_by_id_idx",
+ "columns": ["createdById"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "spaces_id": {
+ "name": "spaces_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastName": {
+ "name": "lastName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thirdPartyStripeSubscriptionId": {
+ "name": "thirdPartyStripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionStatus": {
+ "name": "stripeSubscriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionPriceId": {
+ "name": "stripeSubscriptionPriceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "preferences": {
+ "name": "preferences",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "('null')"
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "onboardingSteps": {
+ "name": "onboardingSteps",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "onboarding_completed_at": {
+ "name": "onboarding_completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customBucket": {
+ "name": "customBucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "inviteQuota": {
+ "name": "inviteQuota",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "defaultOrgId": {
+ "name": "defaultOrgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "email_idx": {
+ "name": "email_idx",
+ "columns": ["email"],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "users_id": {
+ "name": "users_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "verification_tokens": {
+ "name": "verification_tokens",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_tokens_identifier": {
+ "name": "verification_tokens_identifier",
+ "columns": ["identifier"]
+ }
+ },
+ "uniqueConstraints": {
+ "verification_tokens_token_unique": {
+ "name": "verification_tokens_token_unique",
+ "columns": ["token"]
+ }
+ },
+ "checkConstraint": {}
+ },
+ "video_uploads": {
+ "name": "video_uploads",
+ "columns": {
+ "video_id": {
+ "name": "video_id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "uploaded": {
+ "name": "uploaded",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total": {
+ "name": "total",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "phase": {
+ "name": "phase",
+ "type": "varchar(32)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'uploading'"
+ },
+ "processing_progress": {
+ "name": "processing_progress",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "processing_message": {
+ "name": "processing_message",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "processing_error": {
+ "name": "processing_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "raw_file_key": {
+ "name": "raw_file_key",
+ "type": "varchar(512)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "video_uploads_video_id": {
+ "name": "video_uploads_video_id",
+ "columns": ["video_id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ },
+ "videos": {
+ "name": "videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'My Video'"
+ },
+ "bucket": {
+ "name": "bucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration": {
+ "name": "duration",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "width": {
+ "name": "width",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "height": {
+ "name": "height",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "fps": {
+ "name": "fps",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "settings": {
+ "name": "settings",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "transcriptionStatus": {
+ "name": "transcriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('{\"type\":\"MediaConvert\"}')"
+ },
+ "folderId": {
+ "name": "folderId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "effectiveCreatedAt": {
+ "name": "effectiveCreatedAt",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "generated": {
+ "as": "COALESCE(\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%s.%fZ'),\n STR_TO_DATE(JSON_UNQUOTE(JSON_EXTRACT(`metadata`, '$.customCreatedAt')), '%Y-%m-%dT%H:%i:%sZ'),\n `createdAt`\n )",
+ "type": "stored"
+ }
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "xStreamInfo": {
+ "name": "xStreamInfo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "isScreenshot": {
+ "name": "isScreenshot",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "awsRegion": {
+ "name": "awsRegion",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awsBucket": {
+ "name": "awsBucket",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "videoStartTime": {
+ "name": "videoStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "audioStartTime": {
+ "name": "audioStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobId": {
+ "name": "jobId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobStatus": {
+ "name": "jobStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "skipProcessing": {
+ "name": "skipProcessing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": ["ownerId"],
+ "isUnique": false
+ },
+ "is_public_idx": {
+ "name": "is_public_idx",
+ "columns": ["public"],
+ "isUnique": false
+ },
+ "folder_id_idx": {
+ "name": "folder_id_idx",
+ "columns": ["folderId"],
+ "isUnique": false
+ },
+ "org_owner_folder_idx": {
+ "name": "org_owner_folder_idx",
+ "columns": ["orgId", "ownerId", "folderId"],
+ "isUnique": false
+ },
+ "org_effective_created_idx": {
+ "name": "org_effective_created_idx",
+ "columns": ["orgId", "effectiveCreatedAt"],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "videos_id": {
+ "name": "videos_id",
+ "columns": ["id"]
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraint": {}
+ }
+ },
+ "views": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "tables": {},
+ "indexes": {}
+ }
+}
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index 6fdc4535e..5d0d996d6 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -64,6 +64,13 @@
"when": 1762428905323,
"tag": "0008_fat_ender_wiggin",
"breakpoints": true
+ },
+ {
+ "idx": 9,
+ "version": "5",
+ "when": 1768139432782,
+ "tag": "0009_easy_ulik",
+ "breakpoints": true
}
]
}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 85f03f25b..0be22e1e7 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -751,6 +751,16 @@ export const videoUploads = mysqlTable("video_uploads", {
startedAt: timestamp("started_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
mode: varchar("mode", { length: 255, enum: ["singlepart", "multipart"] }),
+ phase: varchar("phase", { length: 32 })
+ .$type<
+ "uploading" | "processing" | "generating_thumbnail" | "complete" | "error"
+ >()
+ .notNull()
+ .default("uploading"),
+ processingProgress: int("processing_progress").notNull().default(0),
+ processingMessage: varchar("processing_message", { length: 255 }),
+ processingError: text("processing_error"),
+ rawFileKey: varchar("raw_file_key", { length: 512 }),
});
export const importedVideos = mysqlTable(
diff --git a/packages/env/server.ts b/packages/env/server.ts
index 353ea9c97..a6885c1ff 100644
--- a/packages/env/server.ts
+++ b/packages/env/server.ts
@@ -119,6 +119,16 @@ function createServerEnv() {
.string()
.optional()
.describe("URL of the media server for FFmpeg processing"),
+ MEDIA_SERVER_WEBHOOK_SECRET: z
+ .string()
+ .optional()
+ .describe("Secret for authenticating media server webhook callbacks"),
+ MEDIA_SERVER_WEBHOOK_URL: z
+ .string()
+ .optional()
+ .describe(
+ "Base URL for media server webhooks (use host.docker.internal for Docker setups)",
+ ),
/// Ignore
NODE_ENV: z.string(),
diff --git a/packages/web-backend/src/S3Buckets/S3BucketAccess.ts b/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
index b37292842..e15dd454b 100644
--- a/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
+++ b/packages/web-backend/src/S3Buckets/S3BucketAccess.ts
@@ -51,6 +51,18 @@ export const createS3BucketAccess = Effect.gen(function* () {
),
),
).pipe(Effect.withSpan("getSignedObjectUrl")),
+ getInternalSignedObjectUrl: (key: string) =>
+ wrapS3Promise(
+ provider.getInternal.pipe(
+ Effect.map((client) =>
+ S3Presigner.getSignedUrl(
+ client,
+ new S3.GetObjectCommand({ Bucket: provider.bucket, Key: key }),
+ { expiresIn: 3600 },
+ ),
+ ),
+ ),
+ ).pipe(Effect.withSpan("getInternalSignedObjectUrl")),
getObject: (key: string) =>
wrapS3Promise(
provider.getInternal.pipe(
@@ -203,6 +215,26 @@ export const createS3BucketAccess = Effect.gen(function* () {
),
),
),
+ getInternalPresignedPutUrl: (
+ key: string,
+ args?: Omit<S3.PutObjectRequest, "Key" | "Bucket">,
+ signingArgs?: RequestPresigningArguments,
+ ) =>
+ wrapS3Promise(
+ provider.getInternal.pipe(
+ Effect.map((client) =>
+ S3Presigner.getSignedUrl(
+ client,
+ new S3.PutObjectCommand({
+ Bucket: provider.bucket,
+ Key: key,
+ ...args,
+ }),
+ signingArgs,
+ ),
+ ),
+ ),
+ ),
getPresignedPostUrl: (
key: string,
args: Omit<PresignedPostOptions, "Bucket" | "Key">,
diff --git a/packages/web-backend/src/S3Buckets/index.ts b/packages/web-backend/src/S3Buckets/index.ts
index 0e9b1bc6e..77666bca7 100644
--- a/packages/web-backend/src/S3Buckets/index.ts
+++ b/packages/web-backend/src/S3Buckets/index.ts
@@ -95,37 +95,40 @@ export class S3Buckets extends Effect.Service<S3Buckets>()("S3Buckets", {
const cloudfrontBucketAccess = cloudfrontEnvs.pipe(
Option.map((cloudfrontEnvs) =>
- Effect.flatMap(createS3BucketAccess, (s3) =>
- Effect.succeed<typeof s3>({
- ...s3,
- getSignedObjectUrl: (key) => {
- const url = `${cloudfrontEnvs.bucketUrl}/${key}`;
- const expires = Math.floor((Date.now() + 3600 * 1000) / 1000);
-
- const policy = {
- Statement: [
- {
- Resource: url,
- Condition: {
- DateLessThan: {
- "AWS:EpochTime": Math.floor(expires),
- },
+ Effect.flatMap(createS3BucketAccess, (s3) => {
+ const getCloudFrontSignedUrl = (key: string) => {
+ const url = `${cloudfrontEnvs.bucketUrl}/${key}`;
+ const expires = Math.floor((Date.now() + 3600 * 1000) / 1000);
+
+ const policy = {
+ Statement: [
+ {
+ Resource: url,
+ Condition: {
+ DateLessThan: {
+ "AWS:EpochTime": Math.floor(expires),
},
},
- ],
- };
-
- return Effect.succeed(
- CloudFrontPresigner.getSignedUrl({
- url,
- keyPairId: cloudfrontEnvs.keypairId,
- privateKey: cloudfrontEnvs.privateKey,
- policy: JSON.stringify(policy),
- }),
- );
- },
- }),
- ),
+ },
+ ],
+ };
+
+ return Effect.succeed(
+ CloudFrontPresigner.getSignedUrl({
+ url,
+ keyPairId: cloudfrontEnvs.keypairId,
+ privateKey: cloudfrontEnvs.privateKey,
+ policy: JSON.stringify(policy),
+ }),
+ );
+ };
+
+ return Effect.succeed<typeof s3>({
+ ...s3,
+ getSignedObjectUrl: getCloudFrontSignedUrl,
+ getInternalSignedObjectUrl: getCloudFrontSignedUrl,
+ });
+ }),
),
);
diff --git a/packages/web-backend/src/Videos/index.ts b/packages/web-backend/src/Videos/index.ts
index ca26c15f7..96a18e3ac 100644
--- a/packages/web-backend/src/Videos/index.ts
+++ b/packages/web-backend/src/Videos/index.ts
@@ -276,6 +276,10 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
total: Db.videoUploads.total,
startedAt: Db.videoUploads.startedAt,
updatedAt: Db.videoUploads.updatedAt,
+ phase: Db.videoUploads.phase,
+ processingProgress: Db.videoUploads.processingProgress,
+ processingMessage: Db.videoUploads.processingMessage,
+ processingError: Db.videoUploads.processingError,
})
.from(Db.videoUploads)
.where(Dz.eq(Db.videoUploads.videoId, videoId)),
@@ -283,7 +287,18 @@ export class Videos extends Effect.Service<Videos>()("Videos", {
.pipe(Policy.withPublicPolicy(policy.canView(videoId)));
if (result == null) return Option.none();
- return Option.some(new Video.UploadProgress(result));
+ return Option.some(
+ new Video.UploadProgress({
+ uploaded: result.uploaded,
+ total: result.total,
+ startedAt: result.startedAt,
+ updatedAt: result.updatedAt,
+ phase: result.phase,
+ processingProgress: result.processingProgress,
+ processingMessage: Option.fromNullable(result.processingMessage),
+ processingError: Option.fromNullable(result.processingError),
+ }),
+ );
}),
updateUploadProgress: Effect.fn("Videos.updateUploadProgress")(function* (
diff --git a/packages/web-domain/src/Video.ts b/packages/web-domain/src/Video.ts
index 3b67fd41d..9fc0569c7 100644
--- a/packages/web-domain/src/Video.ts
+++ b/packages/web-domain/src/Video.ts
@@ -58,6 +58,15 @@ export class Video extends Schema.Class<Video>("Video")({
}
}
+export const UploadPhase = Schema.Literal(
+ "uploading",
+ "processing",
+ "generating_thumbnail",
+ "complete",
+ "error",
+);
+export type UploadPhase = typeof UploadPhase.Type;
+
export class UploadProgress extends Schema.Class<UploadProgress>(
"UploadProgress",
)({
@@ -65,6 +74,10 @@ export class UploadProgress extends Schema.Class<UploadProgress>(
total: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
startedAt: Schema.Date,
updatedAt: Schema.Date,
+ phase: UploadPhase,
+ processingProgress: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
+ processingMessage: Schema.OptionFromNullOr(Schema.String),
+ processingError: Schema.OptionFromNullOr(Schema.String),
}) {}
export const UploadProgressUpdateInput = Schema.Struct({
diff --git a/scripts/env-cli.js b/scripts/env-cli.js
index 36ad0f4b8..8ffb130fb 100644
--- a/scripts/env-cli.js
+++ b/scripts/env-cli.js
@@ -60,6 +60,9 @@ async function main() {
envs.NEXTAUTH_URL = envs.WEB_URL;
envs.WORKFLOWS_RPC_SECRET = crypto.randomBytes(32).toString("base64");
envs.MEDIA_SERVER_URL = "http://localhost:3456";
+ envs.MEDIA_SERVER_WEBHOOK_SECRET = crypto
+ .randomBytes(32)
+ .toString("base64");
if (!allEnvs.NEXTAUTH_SECRET) {
allEnvs.NEXTAUTH_SECRET = crypto.randomBytes(32).toString("base64");