Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(workflows): propagate storage integration across video jobs

Richie McIlroyaf94f6c5abb0
diff --git a/apps/web/lib/transcribe.ts b/apps/web/lib/transcribe.ts
index 0b07f04ab..606ef72f7 100644
--- a/apps/web/lib/transcribe.ts
+++ b/apps/web/lib/transcribe.ts
@@ -1,10 +1,5 @@
import { db } from "@cap/database";
-import {
- organizations,
- s3Buckets,
- videos,
- videoUploads,
-} from "@cap/database/schema";
+import { organizations, videos, videoUploads } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
@@ -39,12 +34,10 @@ export async function transcribeVideo(
const query = await db()
.select({
video: videos,
- bucket: s3Buckets,
settings: videos.settings,
orgSettings: organizations.settings,
})
.from(videos)
- .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
.leftJoin(organizations, eq(videos.orgId, organizations.id))
.where(eq(videos.id, videoId));
diff --git a/apps/web/workflows/generate-ai.ts b/apps/web/workflows/generate-ai.ts
index 44813794c..73dc01fb5 100644
--- a/apps/web/workflows/generate-ai.ts
+++ b/apps/web/workflows/generate-ai.ts
@@ -1,14 +1,15 @@
import { db } from "@cap/database";
-import { s3Buckets, videos } from "@cap/database/schema";
+import { videos } from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { serverEnv } from "@cap/env";
-import { S3Buckets } from "@cap/web-backend";
-import type { S3Bucket, Video } from "@cap/web-domain";
+import { Storage } from "@cap/web-backend";
+import type { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { Effect, Option } from "effect";
import { FatalError } from "workflow";
import { GROQ_MODEL, getGroqClient } from "@/lib/groq-client";
import { runPromise } from "@/lib/server";
+import { decodeStorageVideo } from "@/lib/video-storage";
interface GenerateAiWorkflowPayload {
videoId: string;
@@ -17,7 +18,6 @@ interface GenerateAiWorkflowPayload {
interface VideoData {
video: typeof videos.$inferSelect;
- bucketId: S3Bucket.S3BucketId | null;
metadata: VideoMetadata;
}
@@ -46,7 +46,7 @@ export async function generateAiWorkflow(payload: GenerateAiWorkflowPayload) {
const videoData = await validateAndSetProcessing(videoId);
- const transcript = await fetchTranscript(videoId, userId, videoData.bucketId);
+ const transcript = await fetchTranscript(videoId, userId, videoData.video);
if (!transcript) {
await markSkipped(videoId, videoData.metadata);
@@ -72,16 +72,15 @@ async function validateAndSetProcessing(videoId: string): Promise<VideoData> {
}
const query = await db()
- .select({ video: videos, bucket: s3Buckets })
+ .select({ video: videos })
.from(videos)
- .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
.where(eq(videos.id, videoId as Video.VideoId));
if (query.length === 0 || !query[0]?.video) {
throw new FatalError("Video does not exist");
}
- const { video, bucket } = query[0];
+ const { video } = query[0];
const metadata = (video.metadata as VideoMetadata) || {};
if (video.transcriptionStatus !== "COMPLETE") {
@@ -104,7 +103,6 @@ async function validateAndSetProcessing(videoId: string): Promise<VideoData> {
return {
video,
- bucketId: (bucket?.id ?? null) as S3Bucket.S3BucketId | null,
metadata,
};
}
@@ -112,13 +110,13 @@ async function validateAndSetProcessing(videoId: string): Promise<VideoData> {
async function fetchTranscript(
videoId: string,
userId: string,
- bucketId: S3Bucket.S3BucketId | null,
+ video: typeof videos.$inferSelect,
): Promise<TranscriptData | null> {
"use step";
const vtt = await Effect.gen(function* () {
- const [bucket] = yield* S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId),
+ const [bucket] = yield* Storage.getAccessForVideo(
+ decodeStorageVideo(video),
);
return yield* bucket.getObject(`${userId}/${videoId}/transcription.vtt`);
}).pipe(runPromise);
diff --git a/apps/web/workflows/import-loom-video.ts b/apps/web/workflows/import-loom-video.ts
index 86418d528..8332f95a1 100644
--- a/apps/web/workflows/import-loom-video.ts
+++ b/apps/web/workflows/import-loom-video.ts
@@ -2,10 +2,10 @@ import { randomUUID } from "node:crypto";
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 { Storage } from "@cap/web-backend";
+import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
-import { Effect, Option } from "effect";
+import { Effect } from "effect";
import { FatalError } from "workflow";
import { runPromise } from "@/lib/server";
@@ -25,6 +25,10 @@ function isStreamingUrl(url: string): boolean {
return path.endsWith(".m3u8") || path.endsWith(".mpd");
}
+function isGoogleDriveResumableUrl(url: string): boolean {
+ return url.includes("googleapis.com/upload/drive/");
+}
+
async function fetchLoomCdnUrl(
videoId: string,
endpoint: string,
@@ -172,7 +176,7 @@ async function downloadLoomToS3(
): Promise<LoomProcessingInput> {
"use step";
- const { videoId, loomVideoId, rawFileKey, bucketId } = payload;
+ const { videoId, loomVideoId, rawFileKey } = payload;
await db()
.update(videoUploads)
@@ -204,12 +208,25 @@ async function downloadLoomToS3(
};
}
- 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);
+ const [video] = yield* Effect.promise(() =>
+ db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, Video.VideoId.make(videoId))),
+ );
+ if (!video) {
+ return yield* Effect.fail(new FatalError("Video does not exist"));
+ }
+ const videoDomain = Video.Video.decodeSync({
+ ...video,
+ bucketId: video.bucket,
+ storageIntegrationId: video.storageIntegrationId,
+ createdAt: video.createdAt.toISOString(),
+ updatedAt: video.updatedAt.toISOString(),
+ metadata: video.metadata,
+ });
+ const [bucket] = yield* Storage.getAccessForVideo(videoDomain);
return yield* bucket.getInternalPresignedPutUrl(rawFileKey, {
ContentType: "video/mp4",
});
@@ -223,13 +240,19 @@ async function downloadLoomToS3(
);
}
+ const uploadHeaders: Record<string, string> = {
+ "Content-Type": "video/mp4",
+ "Content-Length": videoBuffer.length.toString(),
+ };
+ if (isGoogleDriveResumableUrl(presignedPutUrl) && videoBuffer.length > 0) {
+ uploadHeaders["Content-Range"] =
+ `bytes 0-${videoBuffer.length - 1}/${videoBuffer.length}`;
+ }
+
const uploadResponse = await fetch(presignedPutUrl, {
method: "PUT",
body: new Uint8Array(videoBuffer),
- headers: {
- "Content-Type": "video/mp4",
- "Content-Length": videoBuffer.length.toString(),
- },
+ headers: uploadHeaders,
});
if (!uploadResponse.ok) {
@@ -330,7 +353,7 @@ async function processVideoOnMediaServer(
): Promise<MediaServerProcessResult> {
"use step";
- const { videoId, userId, rawFileKey, bucketId } = payload;
+ const { videoId, userId, rawFileKey } = payload;
const mediaServerUrl = serverEnv().MEDIA_SERVER_URL;
if (!mediaServerUrl) {
@@ -340,13 +363,26 @@ async function processVideoOnMediaServer(
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 [video] = yield* Effect.promise(() =>
+ db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, Video.VideoId.make(videoId))),
+ );
+ if (!video) {
+ return yield* Effect.fail(new FatalError("Video does not exist"));
+ }
+ const videoDomain = Video.Video.decodeSync({
+ ...video,
+ bucketId: video.bucket,
+ storageIntegrationId: video.storageIntegrationId,
+ createdAt: video.createdAt.toISOString(),
+ updatedAt: video.updatedAt.toISOString(),
+ metadata: video.metadata,
+ });
+ const [bucket] = yield* Storage.getAccessForVideo(videoDomain);
const outputKey = `${userId}/${videoId}/result.mp4`;
const thumbnailKey = `${userId}/${videoId}/screenshot/screen-capture.jpg`;
diff --git a/apps/web/workflows/process-video.ts b/apps/web/workflows/process-video.ts
index 08f1526d8..189c5b036 100644
--- a/apps/web/workflows/process-video.ts
+++ b/apps/web/workflows/process-video.ts
@@ -1,10 +1,9 @@
import { db } from "@cap/database";
import { 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 { Storage } from "@cap/web-backend";
+import { Video } from "@cap/web-domain";
import { eq } from "drizzle-orm";
-import { Option } from "effect";
import { FatalError } from "workflow";
import { runPromise } from "@/lib/server";
@@ -48,7 +47,7 @@ export async function processVideoWorkflow(
);
await saveMetadataAndComplete(videoId, result.metadata);
- await cleanupRawUpload(rawFileKey, bucketId);
+ await cleanupRawUpload(videoId, rawFileKey);
return {
success: true,
@@ -212,7 +211,7 @@ async function processVideoOnMediaServer(
videoId: string,
userId: string,
rawFileKey: string,
- bucketId: string | null,
+ _bucketId: string | null,
): Promise<MediaServerProcessResult> {
"use step";
@@ -223,9 +222,26 @@ async function processVideoOnMediaServer(
throw new FatalError("MEDIA_SERVER_URL is not configured");
}
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId as S3Bucket.S3BucketId | null),
- ).pipe(runPromise);
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, Video.VideoId.make(videoId)));
+
+ if (!video) {
+ throw new FatalError("Video does not exist");
+ }
+
+ const videoDomain = Video.Video.decodeSync({
+ ...video,
+ bucketId: video.bucket,
+ storageIntegrationId: video.storageIntegrationId,
+ createdAt: video.createdAt.toISOString(),
+ updatedAt: video.updatedAt.toISOString(),
+ metadata: video.metadata,
+ });
+
+ const [bucket] =
+ await Storage.getAccessForVideo(videoDomain).pipe(runPromise);
const rawVideoUrl = await bucket
.getInternalSignedObjectUrl(rawFileKey)
@@ -345,15 +361,30 @@ async function saveMetadataAndComplete(
}
async function cleanupRawUpload(
+ videoId: string,
rawFileKey: string,
- bucketId: string | null,
): Promise<void> {
"use step";
try {
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId as S3Bucket.S3BucketId | null),
- ).pipe(runPromise);
+ const [video] = await db()
+ .select()
+ .from(videos)
+ .where(eq(videos.id, Video.VideoId.make(videoId)));
+
+ if (!video) return;
+
+ const videoDomain = Video.Video.decodeSync({
+ ...video,
+ bucketId: video.bucket,
+ storageIntegrationId: video.storageIntegrationId,
+ createdAt: video.createdAt.toISOString(),
+ updatedAt: video.updatedAt.toISOString(),
+ metadata: video.metadata,
+ });
+
+ const [bucket] =
+ await Storage.getAccessForVideo(videoDomain).pipe(runPromise);
await bucket.deleteObject(rawFileKey).pipe(runPromise);
} catch (error) {
diff --git a/apps/web/workflows/transcribe.ts b/apps/web/workflows/transcribe.ts
index 57d55072f..a08ca3b22 100644
--- a/apps/web/workflows/transcribe.ts
+++ b/apps/web/workflows/transcribe.ts
@@ -2,7 +2,6 @@ import { promises as fs } from "node:fs";
import { db } from "@cap/database";
import {
organizations,
- s3Buckets,
users,
videos,
videoUploads,
@@ -10,11 +9,10 @@ import {
import type { VideoMetadata } from "@cap/database/types";
import { serverEnv } from "@cap/env";
import { userIsPro } from "@cap/utils";
-import { S3Buckets } from "@cap/web-backend";
-import type { S3Bucket, Video } from "@cap/web-domain";
+import { Storage } from "@cap/web-backend";
+import type { Video } from "@cap/web-domain";
import { createClient } from "@deepgram/sdk";
import { eq } from "drizzle-orm";
-import { Option } from "effect";
import { FatalError } from "workflow";
import {
ENHANCED_AUDIO_CONTENT_TYPE,
@@ -31,6 +29,7 @@ import {
} from "@/lib/media-client";
import { runPromise } from "@/lib/server";
import { type DeepgramResult, formatToWebVTT } from "@/lib/transcribe-utils";
+import { decodeStorageVideo } from "@/lib/video-storage";
interface TranscribeWorkflowPayload {
videoId: string;
@@ -40,7 +39,6 @@ interface TranscribeWorkflowPayload {
interface VideoData {
video: typeof videos.$inferSelect;
- bucketId: S3Bucket.S3BucketId | null;
transcriptionDisabled: boolean;
isOwnerPro: boolean;
}
@@ -59,7 +57,7 @@ export async function transcribeVideoWorkflow(
return { success: true, message: "Transcription disabled - skipped" };
}
- const audioUrl = await extractAudio(videoId, userId, videoData.bucketId);
+ const audioUrl = await extractAudio(videoId, userId, videoData.video);
if (!audioUrl) {
await markNoAudio(videoId);
@@ -69,27 +67,11 @@ export async function transcribeVideoWorkflow(
};
}
- // const enhancementConfigured = isAudioEnhancementConfigured();
- // const shouldEnhanceAudio = videoData.isOwnerPro && enhancementConfigured;
+ const [transcription] = await Promise.all([transcribeWithDeepgram(audioUrl)]);
- // console.log(
- // `[transcribe] Audio enhancement check: isOwnerPro=${videoData.isOwnerPro}, configured=${enhancementConfigured}, shouldEnhance=${shouldEnhanceAudio}`,
- // );
+ await saveTranscription(videoId, userId, videoData.video, transcription);
- // if (shouldEnhanceAudio) {
- // await markEnhancedAudioProcessing(videoId);
- // }
-
- const [transcription] = await Promise.all([
- transcribeWithDeepgram(audioUrl),
- // shouldEnhanceAudio
- // ? enhanceAndSaveAudio(videoId, userId, audioUrl, videoData.bucketId)
- // : Promise.resolve(),
- ]);
-
- await saveTranscription(videoId, userId, videoData.bucketId, transcription);
-
- await cleanupTempAudio(videoId, userId, videoData.bucketId);
+ await cleanupTempAudio(videoId, userId, videoData.video);
if (aiGenerationEnabled) {
await queueAiGeneration(videoId, userId);
@@ -108,13 +90,11 @@ async function validateVideo(videoId: string): Promise<VideoData> {
const query = await db()
.select({
video: videos,
- bucket: s3Buckets,
settings: videos.settings,
orgSettings: organizations.settings,
owner: users,
})
.from(videos)
- .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
.leftJoin(organizations, eq(videos.orgId, organizations.id))
.innerJoin(users, eq(videos.ownerId, users.id))
.where(eq(videos.id, videoId as Video.VideoId));
@@ -146,7 +126,6 @@ async function validateVideo(videoId: string): Promise<VideoData> {
return {
video: result.video,
- bucketId: (result.bucket?.id ?? null) as S3Bucket.S3BucketId | null,
transcriptionDisabled,
isOwnerPro,
};
@@ -173,15 +152,15 @@ async function markNoAudio(videoId: string): Promise<void> {
async function extractAudio(
videoId: string,
userId: string,
- bucketId: S3Bucket.S3BucketId | null,
+ video: typeof videos.$inferSelect,
): Promise<string | null> {
"use step";
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId),
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
).pipe(runPromise);
- const videoUrl = await resolveVideoSourceUrl(videoId, userId, bucketId);
+ const videoUrl = await resolveVideoSourceUrl(videoId, userId, video);
const useMediaServer = isMediaServerConfigured();
console.log(
@@ -257,10 +236,10 @@ async function extractAudio(
async function resolveVideoSourceUrl(
videoId: string,
userId: string,
- bucketId: S3Bucket.S3BucketId | null,
+ video: typeof videos.$inferSelect,
): Promise<string> {
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId),
+ const [resolvedBucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
).pipe(runPromise);
const upload = await db()
@@ -278,7 +257,9 @@ async function resolveVideoSourceUrl(
);
for (const key of candidateKeys) {
- const url = await bucket.getInternalSignedObjectUrl(key).pipe(runPromise);
+ const url = await resolvedBucket
+ .getInternalSignedObjectUrl(key)
+ .pipe(runPromise);
const response = await fetch(url, {
method: "GET",
headers: { range: "bytes=0-0" },
@@ -328,13 +309,13 @@ async function transcribeWithDeepgram(audioUrl: string): Promise<string> {
async function saveTranscription(
videoId: string,
userId: string,
- bucketId: S3Bucket.S3BucketId | null,
+ video: typeof videos.$inferSelect,
transcription: string,
): Promise<void> {
"use step";
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId),
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
).pipe(runPromise);
await bucket
@@ -352,15 +333,15 @@ async function saveTranscription(
async function cleanupTempAudio(
videoId: string,
userId: string,
- bucketId: S3Bucket.S3BucketId | null,
+ video: typeof videos.$inferSelect,
): Promise<void> {
"use step";
const audioKey = `${userId}/${videoId}/audio-temp.mp3`;
try {
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId),
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
).pipe(runPromise);
await bucket.deleteObject(audioKey).pipe(runPromise);
@@ -406,7 +387,7 @@ async function _enhanceAndSaveAudio(
videoId: string,
userId: string,
audioUrl: string,
- bucketId: S3Bucket.S3BucketId | null,
+ video: typeof videos.$inferSelect,
): Promise<void> {
"use step";
@@ -418,8 +399,8 @@ async function _enhanceAndSaveAudio(
`[transcribe] Audio enhanced, saving to S3 (${enhancedBuffer.length} bytes)`,
);
- const [bucket] = await S3Buckets.getBucketAccess(
- Option.fromNullable(bucketId),
+ const [bucket] = await Storage.getAccessForVideo(
+ decodeStorageVideo(video),
).pipe(runPromise);
const enhancedAudioKey = `${userId}/${videoId}/enhanced-audio.${ENHANCED_AUDIO_EXTENSION}`;
@@ -430,12 +411,12 @@ async function _enhanceAndSaveAudio(
})
.pipe(runPromise);
- const [video] = await db()
+ const [videoRecord] = await db()
.select({ metadata: videos.metadata })
.from(videos)
.where(eq(videos.id, videoId as Video.VideoId));
- const currentMetadata = (video?.metadata as VideoMetadata) || {};
+ const currentMetadata = (videoRecord?.metadata as VideoMetadata) || {};
await db()
.update(videos)