Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Custom s3 bucket backend (#90)

Brendan Allan525e5aabe93a
diff --git a/apps/web/app/api/desktop/video/create/route.ts b/apps/web/app/api/desktop/video/create/route.ts
index 9501df19d..2827bdc87 100644
--- a/apps/web/app/api/desktop/video/create/route.ts
+++ b/apps/web/app/api/desktop/video/create/route.ts
@@ -1,10 +1,12 @@
-import { type NextRequest } from "next/server";
+import type { NextRequest } from "next/server";
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { getCurrentUser } from "@cap/database/auth/session";
import { nanoId } from "@cap/database/helpers";
import { cookies } from "next/headers";
import { dub } from "@/utils/dub";
+import { eq } from "drizzle-orm";
+import { getS3Bucket, getS3Config } from "@/utils/s3";
const allowedOrigins = [
process.env.NEXT_PUBLIC_URL,
@@ -49,16 +51,11 @@ export async function GET(req: NextRequest) {
});
}
- const user = await getCurrentUser();
- const awsRegion = process.env.NEXT_PUBLIC_CAP_AWS_REGION;
- const awsBucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET;
const params = req.nextUrl.searchParams;
const origin = params.get("origin") || null;
const originalOrigin = req.nextUrl.origin;
- const recordingMode: "hls" | "desktopMP4" | null = params.get(
- "recordingMode"
- ) as any;
- const isScreenshot = params.get("isScreenshot") === "true";
+
+ const user = await getCurrentUser();
if (!user) {
console.log("User not authenticated, returning 401");
@@ -78,6 +75,19 @@ export async function GET(req: NextRequest) {
});
}
+ const recordingMode: "hls" | "desktopMP4" | null = params.get(
+ "recordingMode"
+ ) as any;
+ const isScreenshot = params.get("isScreenshot") === "true";
+
+ const [bucket] = await db
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
+
+ const s3Config = getS3Config(bucket);
+ const bucketName = getS3Bucket(bucket);
+
const id = nanoId();
const date = new Date();
const formattedDate = `${date.getDate()} ${date.toLocaleString("default", {
@@ -88,8 +98,8 @@ export async function GET(req: NextRequest) {
id: id,
name: `Cap ${isScreenshot ? "Screenshot" : "Recording"} - ${formattedDate}`,
ownerId: user.id,
- awsRegion: awsRegion,
- awsBucket: awsBucket,
+ awsRegion: s3Config.region,
+ awsBucket: bucketName,
source:
recordingMode === "hls"
? { type: "local" }
@@ -97,6 +107,7 @@ export async function GET(req: NextRequest) {
? { type: "desktopMP4" }
: undefined,
isScreenshot: isScreenshot,
+ bucket: bucket?.id,
});
if (
@@ -104,7 +115,7 @@ export async function GET(req: NextRequest) {
process.env.NEXT_PUBLIC_ENVIRONMENT === "production"
) {
await dub.links.create({
- url: process.env.NEXT_PUBLIC_URL + "/s/" + id,
+ url: `${process.env.NEXT_PUBLIC_URL}/s/${id}`,
domain: "cap.link",
key: id,
});
@@ -114,8 +125,8 @@ export async function GET(req: NextRequest) {
JSON.stringify({
id: id,
user_id: user.id,
- aws_region: awsRegion,
- aws_bucket: awsBucket,
+ aws_region: s3Config.region,
+ aws_bucket: bucketName,
}),
{
status: 200,
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index 427884ce9..9b5e04605 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -1,6 +1,6 @@
import { type NextRequest } from "next/server";
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import {
S3Client,
@@ -15,6 +15,7 @@ import {
generateMasterPlaylist,
} from "@/utils/video/ffmpeg/helpers";
import { getHeaders } from "@/utils/helpers";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
export const revalidate = 3599;
@@ -41,16 +42,17 @@ export async function GET(request: NextRequest) {
error: true,
message: "userId or videoId not supplied",
}),
- {
- status: 401,
- headers: getHeaders(origin),
- }
+ { status: 401, headers: getHeaders(origin) }
);
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db
+ .select({ video: videos, bucket: s3Buckets })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
- if (query.length === 0) {
+ if (!query[0]) {
return new Response(
JSON.stringify({ error: true, message: "Video does not exist" }),
{
@@ -60,7 +62,7 @@ export async function GET(request: NextRequest) {
);
}
- const video = query[0];
+ const { video, bucket } = query[0];
if (video.public === false) {
const user = await getCurrentUser();
@@ -76,24 +78,18 @@ export async function GET(request: NextRequest) {
}
}
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ const Bucket = getS3Bucket(bucket);
const videoPrefix = `${userId}/${videoId}/video/`;
const audioPrefix = `${userId}/${videoId}/audio/`;
try {
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const s3Client = createS3Client(bucket);
if (video.source.type === "local") {
const playlistUrl = await getSignedUrl(
s3Client,
new GetObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: `${userId}/${videoId}/combined-source/stream.m3u8`,
}),
{ expiresIn: 3600 }
@@ -108,7 +104,7 @@ export async function GET(request: NextRequest) {
lines[index] = await getSignedUrl(
s3Client,
new GetObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: `${userId}/${videoId}/combined-source/${line}`,
}),
{ expiresIn: 3600 }
@@ -127,7 +123,7 @@ export async function GET(request: NextRequest) {
const playlistUrl = await getSignedUrl(
s3Client,
new GetObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: `${userId}/${videoId}/result.mp4`,
}),
{ expiresIn: 3600 }
@@ -158,23 +154,20 @@ export async function GET(request: NextRequest) {
default:
return new Response(
JSON.stringify({ error: true, message: "Invalid video type" }),
- {
- status: 401,
- headers: getHeaders(origin),
- }
+ { status: 401, headers: getHeaders(origin) }
);
}
if (prefix === null) {
const videoSegmentCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: videoPrefix,
MaxKeys: 1,
});
let audioSegment;
const audioSegmentCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: audioPrefix,
MaxKeys: 1,
});
@@ -195,7 +188,7 @@ export async function GET(request: NextRequest) {
const [videoMetadata] = await Promise.all([
s3Client.send(
new HeadObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: videoSegment.Contents?.[0]?.Key ?? "",
})
),
@@ -204,7 +197,7 @@ export async function GET(request: NextRequest) {
if (audioSegment?.KeyCount && audioSegment?.KeyCount > 0) {
audioMetadata = await s3Client.send(
new HeadObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: audioSegment.Contents?.[0]?.Key ?? "",
})
);
@@ -213,19 +206,9 @@ export async function GET(request: NextRequest) {
const generatedPlaylist = await generateMasterPlaylist(
videoMetadata?.Metadata?.resolution ?? "",
videoMetadata?.Metadata?.bandwidth ?? "",
- process.env.NEXT_PUBLIC_URL +
- "/api/playlist?userId=" +
- userId +
- "&videoId=" +
- videoId +
- "&videoType=video",
+ `${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${userId}&videoId=${videoId}&videoType=video`,
audioMetadata
- ? process.env.NEXT_PUBLIC_URL +
- "/api/playlist?userId=" +
- userId +
- "&videoId=" +
- videoId +
- "&videoType=audio"
+ ? `${process.env.NEXT_PUBLIC_URL}/api/playlist?userId=${userId}&videoId=${videoId}&videoType=audio`
: null,
video.xStreamInfo ?? ""
);
@@ -237,7 +220,7 @@ export async function GET(request: NextRequest) {
}
objectsCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: prefix,
MaxKeys: thumbnail ? 1 : undefined,
});
@@ -248,17 +231,11 @@ export async function GET(request: NextRequest) {
(objects.Contents || []).map(async (object) => {
const url = await getSignedUrl(
s3Client,
- new GetObjectCommand({
- Bucket: bucket,
- Key: object.Key,
- }),
+ new GetObjectCommand({ Bucket, Key: object.Key }),
{ expiresIn: 3600 }
);
const metadata = await s3Client.send(
- new HeadObjectCommand({
- Bucket: bucket,
- Key: object.Key,
- })
+ new HeadObjectCommand({ Bucket, Key: object.Key })
);
return {
diff --git a/apps/web/app/api/screenshot/route.ts b/apps/web/app/api/screenshot/route.ts
index aa6d02ab5..167a6ab8d 100644
--- a/apps/web/app/api/screenshot/route.ts
+++ b/apps/web/app/api/screenshot/route.ts
@@ -1,13 +1,11 @@
import { type NextRequest } from "next/server";
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
-import {
- S3Client,
- ListObjectsV2Command,
-} from "@aws-sdk/client-s3";
+import { S3Client, ListObjectsV2Command } from "@aws-sdk/client-s3";
import { getCurrentUser } from "@cap/database/auth/session";
import { getHeaders } from "@/utils/helpers";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
export const revalidate = 3599;
@@ -32,26 +30,24 @@ export async function GET(request: NextRequest) {
error: true,
message: "userId or videoId not supplied",
}),
- {
- status: 401,
- headers: getHeaders(origin),
- }
+ { status: 401, headers: getHeaders(origin) }
);
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db
+ .select({ video: videos, bucket: s3Buckets })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
if (query.length === 0) {
return new Response(
JSON.stringify({ error: true, message: "Video does not exist" }),
- {
- status: 401,
- headers: getHeaders(origin),
- }
+ { status: 401, headers: getHeaders(origin) }
);
}
- const video = query[0];
+ const { video, bucket } = query[0];
if (video.public === false) {
const user = await getCurrentUser();
@@ -59,28 +55,19 @@ export async function GET(request: NextRequest) {
if (!user || user.id !== video.ownerId) {
return new Response(
JSON.stringify({ error: true, message: "Video is not public" }),
- {
- status: 401,
- headers: getHeaders(origin),
- }
+ { status: 401, headers: getHeaders(origin) }
);
}
}
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ const Bucket = getS3Bucket(bucket);
const screenshotPrefix = `${userId}/${videoId}/`;
try {
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const s3Client = createS3Client(bucket);
const objectsCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: screenshotPrefix,
MaxKeys: 1,
});
@@ -94,30 +81,24 @@ export async function GET(request: NextRequest) {
if (!screenshot) {
return new Response(
JSON.stringify({ error: true, message: "Screenshot not found" }),
- {
- status: 404,
- headers: getHeaders(origin),
- }
+ { status: 404, headers: getHeaders(origin) }
);
}
const screenshotUrl = `https://v.cap.so/${screenshot.Key}`;
- return new Response(
- JSON.stringify({ url: screenshotUrl }),
- {
- status: 200,
- headers: getHeaders(origin),
- }
- );
+ return new Response(JSON.stringify({ url: screenshotUrl }), {
+ status: 200,
+ headers: getHeaders(origin),
+ });
} catch (error) {
console.error("Error generating screenshot URL", error);
return new Response(
- JSON.stringify({ error: error, message: "Error generating screenshot URL" }),
- {
- status: 500,
- headers: getHeaders(origin),
- }
+ JSON.stringify({
+ error: error,
+ message: "Error generating screenshot URL",
+ }),
+ { status: 500, headers: getHeaders(origin) }
);
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/app/api/thumbnail/route.ts b/apps/web/app/api/thumbnail/route.ts
index 1c9a70b31..bbfb3ac05 100644
--- a/apps/web/app/api/thumbnail/route.ts
+++ b/apps/web/app/api/thumbnail/route.ts
@@ -1,6 +1,10 @@
-import { type NextRequest } from "next/server";
-import { S3Client, ListObjectsV2Command } from "@aws-sdk/client-s3";
+import type { NextRequest } from "next/server";
+import { ListObjectsV2Command } from "@aws-sdk/client-s3";
import { getHeaders } from "@/utils/helpers";
+import { db } from "@cap/database";
+import { eq } from "drizzle-orm";
+import { s3Buckets, videos } from "@cap/database/schema";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
export const revalidate = 3500;
@@ -23,27 +27,41 @@ export async function GET(request: NextRequest) {
);
}
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const query = await db
+ .select({
+ video: videos,
+ bucket: s3Buckets,
+ })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ if (query.length === 0) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Video does not exist" }),
+ {
+ status: 401,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+
+ const { video, bucket } = query[0];
+ const Bucket = getS3Bucket(bucket);
+
+ const s3Client = createS3Client(bucket);
const prefix = `${userId}/${videoId}/`;
try {
const listCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: prefix,
});
const listResponse = await s3Client.send(listCommand);
const contents = listResponse.Contents || [];
- let thumbnailKey = contents.find(item => item.Key?.endsWith('.png'))?.Key;
+ let thumbnailKey = contents.find((item) => item.Key?.endsWith(".png"))?.Key;
if (!thumbnailKey) {
thumbnailKey = `${prefix}screenshot/screen-capture.jpg`;
@@ -51,17 +69,17 @@ export async function GET(request: NextRequest) {
const thumbnailUrl = `https://v.cap.so/${thumbnailKey}`;
- return new Response(
- JSON.stringify({ screen: thumbnailUrl }),
- {
- status: 200,
- headers: getHeaders(origin),
- }
- );
+ return new Response(JSON.stringify({ screen: thumbnailUrl }), {
+ status: 200,
+ headers: getHeaders(origin),
+ });
} catch (error) {
console.error("Error generating thumbnail URL:", error);
return new Response(
- JSON.stringify({ error: true, message: "Error generating thumbnail URL" }),
+ JSON.stringify({
+ error: true,
+ message: "Error generating thumbnail URL",
+ }),
{
status: 500,
headers: getHeaders(origin),
diff --git a/apps/web/app/api/upload/mux/create/route.ts b/apps/web/app/api/upload/mux/create/route.ts
index 92fbd98d3..a82cef0f1 100644
--- a/apps/web/app/api/upload/mux/create/route.ts
+++ b/apps/web/app/api/upload/mux/create/route.ts
@@ -1,12 +1,13 @@
import { type NextRequest } from "next/server";
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { S3Client, ListObjectsV2Command } from "@aws-sdk/client-s3";
import {
MediaConvertClient,
CreateJobCommand,
} from "@aws-sdk/client-mediaconvert";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
const allowedOrigins = [
process.env.NEXT_PUBLIC_URL,
"http://localhost:3001",
@@ -63,7 +64,14 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db
+ .select({
+ video: videos,
+ bucket: s3Buckets,
+ })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
if (query.length === 0) {
return new Response(
@@ -81,7 +89,7 @@ export async function GET(request: NextRequest) {
);
}
- const video = query[0];
+ const { video, bucket } = query[0];
if (video.jobId !== null || video.ownerId !== userId) {
return new Response(JSON.stringify({ assetId: video.jobId }), {
@@ -96,26 +104,20 @@ export async function GET(request: NextRequest) {
});
}
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ const Bucket = getS3Bucket(bucket);
const videoPrefix = `${userId}/${videoId}/video/`;
const audioPrefix = `${userId}/${videoId}/audio/`;
try {
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const s3Client = createS3Client(bucket);
const videoSegmentCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: videoPrefix,
});
const audioSegmentCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: audioPrefix,
});
diff --git a/apps/web/app/api/upload/new/route.ts b/apps/web/app/api/upload/new/route.ts
index 873410b65..887d0a1b1 100644
--- a/apps/web/app/api/upload/new/route.ts
+++ b/apps/web/app/api/upload/new/route.ts
@@ -4,8 +4,6 @@ import { uploadToS3 } from "@/utils/video/upload/helpers";
export async function POST(request: NextRequest) {
const user = await getCurrentUser();
- const awsRegion = process.env.NEXT_PUBLIC_CAP_AWS_REGION;
- const awsBucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET;
const formData = await request.formData();
const filename = formData.get("filename");
const videoId = formData.get("videoId");
@@ -15,6 +13,9 @@ export async function POST(request: NextRequest) {
const videoCodec = formData.get("videoCodec");
const audioCodec = formData.get("audioCodec");
+ const awsRegion = process.env.NEXT_PUBLIC_CAP_AWS_REGION;
+ const awsBucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET;
+
if (!user || !awsRegion || !awsBucket || !filename || !blobData) {
console.error("Missing required data in /api/upload/new/route.ts");
diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.ts
index 5a28db671..a14816a7c 100644
--- a/apps/web/app/api/upload/signed/route.ts
+++ b/apps/web/app/api/upload/signed/route.ts
@@ -1,30 +1,20 @@
-import { S3Client } from "@aws-sdk/client-s3";
-import { createPresignedPost, PresignedPost } from "@aws-sdk/s3-presigned-post";
-import { NextRequest } from "next/server";
-
-const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
-});
+import { createS3Client, getS3Bucket } from "@/utils/s3";
+import {
+ createPresignedPost,
+ type PresignedPost,
+} from "@aws-sdk/s3-presigned-post";
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { s3Buckets } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+import type { NextRequest } from "next/server";
export async function POST(request: NextRequest) {
try {
- const {
- userId,
- fileKey,
- duration,
- bandwidth,
- resolution,
- videoCodec,
- audioCodec,
- awsBucket,
- awsRegion,
- } = await request.json();
+ const { fileKey, duration, bandwidth, resolution, videoCodec, audioCodec } =
+ await request.json();
- if (!userId || !fileKey || !awsBucket || !awsRegion) {
+ if (!fileKey) {
console.error("Missing required fields in /api/upload/signed/route.ts");
return new Response(
@@ -38,6 +28,32 @@ export async function POST(request: NextRequest) {
);
}
+ const user = await getCurrentUser();
+
+ if (!user) {
+ return new Response(JSON.stringify({ error: true }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ const [bucket] = await db
+ .select()
+ .from(s3Buckets)
+ .where(eq(s3Buckets.ownerId, user.id));
+ if (!bucket) {
+ return new Response(JSON.stringify({ error: true }), {
+ status: 401,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ const s3Client = createS3Client(bucket);
+
const contentType = fileKey.endsWith(".aac")
? "audio/aac"
: fileKey.endsWith(".webm")
@@ -52,7 +68,7 @@ export async function POST(request: NextRequest) {
const Fields = {
"Content-Type": contentType,
- "x-amz-meta-userid": userId,
+ "x-amz-meta-userid": user.id,
"x-amz-meta-duration": duration ?? "",
"x-amz-meta-bandwidth": bandwidth ?? "",
"x-amz-meta-resolution": resolution ?? "",
@@ -62,12 +78,7 @@ export async function POST(request: NextRequest) {
const presignedPostData: PresignedPost = await createPresignedPost(
s3Client,
- {
- Bucket: awsBucket,
- Key: fileKey,
- Fields,
- Expires: 1800,
- }
+ { Bucket: getS3Bucket(bucket), Key: fileKey, Fields, Expires: 1800 }
);
console.log("Presigned URL created successfully");
diff --git a/apps/web/app/api/video/delete/route.ts b/apps/web/app/api/video/delete/route.ts
index bd70d269c..e63b268f6 100644
--- a/apps/web/app/api/video/delete/route.ts
+++ b/apps/web/app/api/video/delete/route.ts
@@ -1,6 +1,6 @@
import { type NextRequest } from "next/server";
import { getCurrentUser } from "@cap/database/auth/session";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { db } from "@cap/database";
import { and, eq } from "drizzle-orm";
import {
@@ -8,6 +8,8 @@ import {
ListObjectsV2Command,
S3Client,
} from "@aws-sdk/client-s3";
+import { getHeaders } from "@/utils/helpers";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
export async function DELETE(request: NextRequest) {
const user = await getCurrentUser();
@@ -26,23 +28,35 @@ export async function DELETE(request: NextRequest) {
});
}
+ const query = await db
+ .select({ video: videos, bucket: s3Buckets })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Video does not exist" }),
+ {
+ status: 401,
+ headers: getHeaders(origin),
+ }
+ );
+ }
+
+ const { bucket } = query[0];
+
await db
.delete(videos)
.where(and(eq(videos.id, videoId), eq(videos.ownerId, userId)));
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const s3Client = createS3Client(bucket);
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ const Bucket = getS3Bucket(bucket);
const prefix = `${userId}/${videoId}/`;
const listObjectsCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: prefix,
});
@@ -50,7 +64,7 @@ export async function DELETE(request: NextRequest) {
if (listedObjects.Contents?.length) {
const deleteObjectsCommand = new DeleteObjectsCommand({
- Bucket: bucket,
+ Bucket,
Delete: {
Objects: listedObjects.Contents.map((content) => ({
Key: content.Key,
diff --git a/apps/web/app/api/video/og/route.tsx b/apps/web/app/api/video/og/route.tsx
index 24e146bb6..2c7c256bb 100644
--- a/apps/web/app/api/video/og/route.tsx
+++ b/apps/web/app/api/video/og/route.tsx
@@ -1,16 +1,24 @@
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
export const runtime = "edge";
export async function GET(req: NextRequest) {
const videoId = req.nextUrl.searchParams.get("videoId") as string;
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db
+ .select({
+ video: videos,
+ bucket: s3Buckets,
+ })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
type FileKey = {
type: "screen";
@@ -21,7 +29,7 @@ export async function GET(req: NextRequest) {
screen: string | null;
};
- if (query.length === 0 || query?.[0]?.public === false) {
+ if (query.length === 0 || query?.[0]?.video.public === false) {
return new ImageResponse(
(
<div
@@ -45,17 +53,11 @@ export async function GET(req: NextRequest) {
);
}
- const video = query[0];
+ const { video, bucket } = query[0];
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const s3Client = createS3Client(bucket);
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET;
+ const Bucket = getS3Bucket(bucket);
const fileKeys: FileKey[] = [
{
type: "screen",
@@ -72,7 +74,7 @@ export async function GET(req: NextRequest) {
try {
const url = await getSignedUrl(
s3Client,
- new GetObjectCommand({ Bucket: bucket, Key: key }),
+ new GetObjectCommand({ Bucket, Key: key }),
{ expiresIn: 3600 }
);
responseObject[type] = url;
diff --git a/apps/web/app/api/video/transcribe/route.ts b/apps/web/app/api/video/transcribe/route.ts
index b0acf0798..0b7c7658f 100644
--- a/apps/web/app/api/video/transcribe/route.ts
+++ b/apps/web/app/api/video/transcribe/route.ts
@@ -1,4 +1,4 @@
-import { NextRequest } from "next/server";
+import type { NextRequest } from "next/server";
import {
S3Client,
ListObjectsV2Command,
@@ -10,8 +10,9 @@ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { createClient } from "@deepgram/sdk";
import { getHeaders } from "@/utils/helpers";
import { db } from "@cap/database";
-import { videos } from "@cap/database/schema";
+import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
export const maxDuration = 120;
@@ -62,7 +63,14 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db
+ .select({
+ video: videos,
+ bucket: s3Buckets,
+ })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
if (query.length === 0) {
return new Response(
@@ -74,7 +82,7 @@ export async function GET(request: NextRequest) {
);
}
- const video = query[0];
+ const { video, bucket } = query[0];
if (
video.transcriptionStatus === "COMPLETE" ||
@@ -84,10 +92,7 @@ export async function GET(request: NextRequest) {
JSON.stringify({
message: "Transcription already completed or in progress",
}),
- {
- status: 200,
- headers: getHeaders(origin),
- }
+ { status: 200, headers: getHeaders(origin) }
);
}
@@ -96,20 +101,14 @@ export async function GET(request: NextRequest) {
.set({ transcriptionStatus: "PROCESSING" })
.where(eq(videos.id, videoId));
- const bucket = process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ const Bucket = getS3Bucket(bucket);
const filePrefix = `${userId}/${videoId}/combined-source/`;
- const s3Client = new S3Client({
- region: process.env.NEXT_PUBLIC_CAP_AWS_REGION || "",
- credentials: {
- accessKeyId: process.env.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: process.env.CAP_AWS_SECRET_KEY || "",
- },
- });
+ const s3Client = createS3Client(bucket);
try {
const audioSegmentCommand = new ListObjectsV2Command({
- Bucket: bucket,
+ Bucket,
Prefix: filePrefix,
});
@@ -120,7 +119,7 @@ export async function GET(request: NextRequest) {
const presignedUrl = await getSignedUrl(
s3Client,
new GetObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: object.Key,
})
);
@@ -132,7 +131,7 @@ export async function GET(request: NextRequest) {
const uploadUrl = await getSignedUrl(
s3Client,
new PutObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: `${userId}/${videoId}/generated/all-audio.mp3`,
})
);
@@ -159,7 +158,7 @@ export async function GET(request: NextRequest) {
const uploadedFileUrl = await getSignedUrl(
s3Client,
new GetObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: `${userId}/${videoId}/generated/all-audio.mp3`,
})
);
@@ -171,7 +170,7 @@ export async function GET(request: NextRequest) {
}
const uploadCommand = new PutObjectCommand({
- Bucket: bucket,
+ Bucket,
Key: `${userId}/${videoId}/transcription.vtt`,
Body: transcription,
ContentType: "text/vtt",
@@ -215,13 +214,13 @@ function formatToWebVTT(result: any): string {
let captionIndex = 1;
result.results.utterances.forEach((utterance: any) => {
- let words = utterance.words;
+ const words = utterance.words;
let group = [];
let start = formatTimestamp(words[0].start);
let wordCount = 0;
for (let i = 0; i < words.length; i++) {
- let word = words[i];
+ const word = words[i];
group.push(word.word);
wordCount++;
@@ -231,8 +230,8 @@ function formatToWebVTT(result: any): string {
(words[i + 1] && words[i + 1].start - word.end > 0.5) ||
wordCount === 8
) {
- let end = formatTimestamp(word.end);
- let groupText = group.join(" ");
+ const end = formatTimestamp(word.end);
+ const groupText = group.join(" ");
output += `${captionIndex}\n${start} --> ${end}\n${groupText}\n\n`;
captionIndex++;
diff --git a/apps/web/app/record/Record.tsx b/apps/web/app/record/Record.tsx
deleted file mode 100644
index ff987108d..000000000
--- a/apps/web/app/record/Record.tsx
+++ /dev/null
@@ -1,750 +0,0 @@
-"use client";
-
-import {
- keepPreviousData,
- QueryClient,
- QueryClientProvider,
- queryOptions,
- useQuery,
-} from "@tanstack/react-query";
-import {
- useState,
- useEffect,
- useRef,
- useMemo,
- useCallback,
- type ComponentProps,
- type RefObject,
-} from "react";
-import { isUserOnProPlan } from "@cap/utils";
-import { LogoBadge } from "@cap/ui";
-import type { users } from "@cap/database/schema";
-import { Mic, Video, Monitor, ArrowLeft } from "lucide-react";
-import { type HandleClasses, Rnd } from "react-rnd";
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- LogoSpinner,
-} from "@cap/ui";
-
-import { ActionButton } from "./_components/ActionButton";
-import { useRecorder } from "./useRecorder";
-import { flushSync } from "react-dom";
-
-const client = new QueryClient({
- defaultOptions: {
- queries: {
- staleTime: 0,
- refetchOnMount: false,
- refetchOnWindowFocus: false,
- refetchOnReconnect: false,
- gcTime: 0,
- },
- },
-});
-
-export function Record({ user }: { user: typeof users.$inferSelect }) {
- return (
- <QueryClientProvider client={client}>
- <Component user={user} />
- </QueryClientProvider>
- );
-}
-
-const CENTERED_THRESHOLD = 15;
-
-// million-ignore
-const Component = ({ user }: { user: typeof users.$inferSelect }) => {
- const devices = useQuery(devicesQuery).data;
- const [audioDeviceId, setAudioDeviceId] = useState<string>();
- const [webcamDeviceId, setWebcamDeviceId] = useState<string>();
- const audioDevice = devices.audio.find((d) => d.deviceId === audioDeviceId);
- const webcamDevice = devices.video.find((d) => d.deviceId === webcamDeviceId);
-
- const screenPreviewRef = useRef<HTMLVideoElement>(null);
- const webcamPreviewRef = useRef<HTMLVideoElement>(null);
- const videoContainerRef = useRef<HTMLDivElement>(null);
-
- const showScreen = useRef(false);
- const screen = useQuery({
- queryKey: ["screen"],
- placeholderData: keepPreviousData,
- queryFn: async () => {
- if (screen.data)
- for (const track of screen.data.stream.getTracks()) {
- track.stop();
- }
-
- if (!showScreen.current) return null;
-
- const result = await getScreenStream();
- if (!result) return null;
-
- for (const track of result.stream.getTracks()) {
- track.onended = () => recorder.stop();
- }
-
- return result;
- },
- });
-
- const webcamStream = useQuery({
- placeholderData: keepPreviousData,
- queryKey: [
- "webcamStream",
- {
- deviceId: webcamDeviceId,
- microphoneId: audioDeviceId,
- skip: screen.data === null,
- },
- ] as const,
- queryFn: async ({ queryKey: [_, { deviceId, microphoneId, skip }] }) => {
- if (webcamStream.data)
- for (const track of webcamStream.data.getTracks()) {
- track.stop();
- }
-
- if (skip) return null;
-
- const stream = await getWebcamStream({ deviceId, microphoneId });
- if (!stream) return null;
-
- return stream;
- },
- });
-
- useEffect(() => {
- if (screenPreviewRef.current)
- screenPreviewRef.current.srcObject = screen.data?.stream ?? null;
- if (webcamPreviewRef.current)
- webcamPreviewRef.current.srcObject = webcamStream.data ?? null;
- }, [screen.data?.stream, webcamStream.data]);
-
- const videoElement = screen.data?.videoElement;
- const aspectRatio = useMemo(() => {
- if (videoElement) return videoElement.videoWidth / videoElement.videoHeight;
- return 16 / 9;
- }, [videoElement]);
-
- const webcamRnd = usePreviewRnd(
- webcamPreviewRef,
- videoContainerRef,
- WEBCAM_DEFAULT_STYLE
- );
- const screenRnd = usePreviewRnd(
- screenPreviewRef,
- videoContainerRef,
- SCREEN_DEFAULT_STYLE
- );
-
- const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
-
- const recorder = useRecorder(user.id);
-
- const stopScreenCapture = () => {
- showScreen.current = false;
-
- screen.refetch({ cancelRefetch: false });
- };
-
- async function startScreenCapture() {
- showScreen.current = true;
-
- await screen.refetch({ cancelRefetch: false });
-
- // need to make sure screen size has rendered before setting webcam styles
- flushSync(() => {
- screenRnd.setStyle({
- x: 0,
- y: 0,
- width: "100%",
- height: "100%",
- });
- });
-
- webcamRnd.setStyle(
- getWebcamDefaultStyles(videoContainerRef.current!, "small")
- );
- }
-
- const [storedState] = useState(() => ({
- audioDevice: localStorage.getItem("selectedAudioDevice"),
- videoDevice: localStorage.getItem("selectedVideoDevice"),
- screenStream: localStorage.getItem("screenStream"),
- }));
-
- // callback ref used to ensure that 1. videoContainerRef exists and 2. that it only fires once
- const onVideoContainerMounted = useCallback((ref: HTMLDivElement) => {
- (videoContainerRef as any).current = ref;
-
- if (storedState.audioDevice) setAudioDeviceId(storedState.audioDevice);
- if (storedState.videoDevice) setWebcamDeviceId(storedState.videoDevice);
-
- webcamRnd.setStyle(
- getWebcamDefaultStyles(
- videoContainerRef.current!,
- screen.data === null ? "large" : "small"
- )
- );
-
- if (storedState.screenStream === "true") startScreenCapture();
- }, []);
-
- useLocalStoragePersist("selectedAudioDevice", audioDeviceId);
- useLocalStoragePersist("selectedVideoDevice", webcamDeviceId);
- useLocalStoragePersist("screenStream", screen.data ? "true" : undefined);
-
- if (recorder.isLoading) {
- return (
- <div className="w-full h-screen flex items-center justify-center">
- <LogoSpinner className="w-10 h-auto animate-spin" />
- </div>
- );
- }
-
- return (
- <div className="w-full h-full min-h-screen h mx-auto flex items-center justify-center">
- <div className="max-w-[1280px] wrapper p-8 space-y-6">
- {isSafari && (
- <div className="bg-red-500 py-3 rounded-xl">
- <div className="wrapper">
- <p className="text-white text-lg font-medium">
- Currently experiencing some intermitent problems with Safari
- browser. Fix is in progress.
- </p>
- </div>
- </div>
- )}
- <div className="top-bar grid grid-cols-12 justify-between">
- <div className="col-span-4 flex items-center justify-start">
- <a href="/dashboard" className="flex items-center">
- <ArrowLeft className="w-7 h-7 text-gray-600" />
- <LogoBadge className="w-8 h-auto ml-2" />
- </a>
- </div>
- <div className="col-span-4 flex items-center justify-center">
- {isUserOnProPlan({
- subscriptionStatus: user?.stripeSubscriptionStatus as string,
- }) ? (
- <p className="text-sm text-gray-600">No recording limit</p>
- ) : (
- <div>
- <p className="text-sm text-gray-600">5 min recording limit</p>
- <a
- href="/pricing"
- className="text-sm text-primary font-medium hover:underline"
- >
- Upgrade to Cap Pro
- </a>
- </div>
- )}
- </div>
- <div className="col-span-4 flex items-center justify-end">
- <Button
- className="min-w-[175px]"
- {...(recorder.state.status === "recording" && {
- variant: "destructive",
- })}
- onClick={() => {
- if (recorder.state.status === "recording") recorder.stop();
- else if (recorder.state.status === "idle")
- recorder.start(
- webcamDevice,
- webcamStream.data ?? null,
- audioDevice,
- videoContainerRef.current!,
- screenPreviewRef.current ?? undefined,
- webcamPreviewRef.current ?? undefined
- );
- }}
- spinner={
- recorder.state.status === "starting" ||
- recorder.state.status === "stopping"
- }
- >
- {recorder.state.status === "idle" ? (
- "Start Recording"
- ) : recorder.state.status === "starting" ? (
- "Starting..."
- ) : recorder.state.status === "recording" ? (
- <>
- Stop - <RecordingTimeText seconds={recorder.state.seconds} />
- </>
- ) : (
- recorder.state.message
- )}
- </Button>
- </div>
- </div>
- <div className="h-full flex-grow">
- <div className="w-full h-full top-0 left-0 h-full flex flex-col items-center justify-center">
- <div
- ref={onVideoContainerMounted}
- style={{
- aspectRatio: aspectRatio,
- maxWidth: "100%",
- }}
- className="video-container bg-black relative w-full mx-auto border-2 border-gray-200 rounded-xl overflow-hidden shadow-xl"
- >
- {!screen.data && !webcamStream.data && (
- <div
- className="absolute top-1/2 left-1/2 -translate-y-1/2 -translate-x-1/2 w-full h-full flex items-center justify-center"
- style={{ zIndex: 999 }}
- >
- <div className="wrapper w-full text-center space-y-2">
- <p className="text-2xl text-white">
- Select a screen or window source to get started.
- </p>
- <p className="text-xl text-white">
- Once selected, click the "Start Recording" button to
- begin.
- </p>
- </div>
- </div>
- )}
- {(screenRnd.isCenteredHorizontally ||
- webcamRnd.isCenteredHorizontally) && (
- <div
- className="crosshair absolute top-0 left-1/2 transform -translate-x-1/2 w-0.5 h-full bg-red-500"
- style={{ zIndex: 999 }}
- />
- )}
- {(screenRnd.isCenteredVertically ||
- webcamRnd.isCenteredVertically) && (
- <div
- className="crosshair absolute top-1/2 left-0 transform -translate-y-1/2 w-full h-0.5 bg-red-500"
- style={{ zIndex: 999 }}
- />
- )}
- {screen.data && (
- <Rnd {...screenRnd.props} className="absolute rnd group">
- <div className="w-full h-full group-hover:outline outline-2 outline-primary rounded-xl">
- <video
- id="screenPreview"
- ref={screenPreviewRef}
- autoPlay
- muted
- className="w-full h-full"
- />
- </div>
- </Rnd>
- )}
- {webcamStream && webcamDevice !== undefined && (
- <Rnd
- {...webcamRnd.props}
- default={webcamRnd.styles}
- id="rndPreview"
- className="absolute webcam-rnd rnd group hover:outline outline-2 outline-primary"
- lockAspectRatio={true}
- >
- <div className="w-full h-full rounded-full overflow-hidden group-hover:outline outline-2 outline-primary">
- <video
- id="webcamPreview"
- ref={webcamPreviewRef}
- autoPlay
- muted
- className="w-full h-full object-cover"
- />
- </div>
- </Rnd>
- )}
- </div>
- </div>
- </div>
- <div>
- <div className="bottom-bar space-y-4 mb-4 w-full">
- <div className="space-x-3 flex items-center">
- <div className="w-full">
- <p className="text-left text-sm font-semibold">
- Screen / Window
- </p>
- <ActionButton
- handler={async () => {
- if (screen.data) stopScreenCapture();
- else startScreenCapture();
- }}
- icon={<Monitor className="w-5 h-5" />}
- label={screen.data ? "Hide display" : "Select display"}
- active={true}
- />
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger className="w-full">
- <p className="text-left text-sm font-semibold">Webcam</p>
- <ActionButton
- width="full"
- icon={<Video className="w-5 h-5" />}
- label={webcamDevice?.label ?? "None"}
- active={true}
- recordingOption={true}
- optionName="Video"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-56">
- {devices.video.map((device) => (
- <DropdownMenuItem
- key={device.deviceId}
- onSelect={() => {
- setWebcamDeviceId(device.deviceId);
- webcamRnd.setStyle(
- getWebcamDefaultStyles(
- videoContainerRef.current!,
- "small"
- )
- );
- }}
- >
- {device.label}
- </DropdownMenuItem>
- ))}
- <DropdownMenuItem
- onSelect={() => {
- setWebcamDeviceId(undefined);
- }}
- >
- None
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- <DropdownMenu>
- <DropdownMenuTrigger className="w-full">
- <p className="text-left text-sm font-semibold">Microphone</p>
- <ActionButton
- width="full"
- icon={<Mic className="w-5 h-5" />}
- label={audioDevice?.label ?? "None"}
- active={true}
- recordingOption={true}
- optionName="Audio"
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-56">
- {devices.audio.map((device) => (
- <DropdownMenuItem
- key={device.deviceId}
- onSelect={() => {
- setAudioDeviceId(device.deviceId);
- webcamRnd.setStyle(
- getWebcamDefaultStyles(
- videoContainerRef.current!,
- "small"
- )
- );
- }}
- >
- {device.label}
- </DropdownMenuItem>
- ))}
- <DropdownMenuItem
- onSelect={() => {
- setAudioDeviceId(undefined);
- }}
- >
- None
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-const resizeHandleClasses: HandleClasses = {
- bottomRight: "resize-handle",
- bottomLeft: "resize-handle",
- bottom: "resize-handle",
- right: "resize-handle",
- left: "resize-handle",
- top: "resize-handle",
- topLeft: "resize-handle",
- topRight: "resize-handle",
-};
-
-function usePreviewRnd(
- previewRef: RefObject<HTMLVideoElement>,
- containerRef: RefObject<HTMLDivElement>,
- defaultStyles: {
- x: number;
- y: number;
- width: number | string;
- height: number | string;
- }
-) {
- const [isDragging, setIsDragging] = useState(false);
- const [styles, setStyle] = useState(defaultStyles);
- const [isCenteredVertically, setIsCenteredVertically] = useState(false);
- const [isCenteredHorizontally, setIsCenteredHorizontally] = useState(false);
-
- const props = useMemo(
- () =>
- ({
- position: {
- x: styles.x,
- y: styles.y,
- },
- size: {
- width: styles.width,
- height: styles.height,
- },
- bounds: "parent",
- resizeHandleStyles: rndHandleStyles,
- resizeHandleClasses,
- // default: styles,
- onDrag: () => {
- setIsDragging(true);
- const videoContainer = containerRef.current;
- const preview = previewRef.current;
-
- if (!videoContainer || !preview) return;
-
- const isCentered = elementIsCentered(preview, videoContainer);
-
- setIsCenteredVertically(isCentered.vertically);
- setIsCenteredHorizontally(isCentered.horizontally);
- },
- onDragStop: (_e, d) => {
- setIsDragging(false);
-
- const videoContainer = containerRef.current;
- const preview = previewRef.current;
-
- if (!videoContainer || !preview) return;
-
- const isCentered = elementIsCentered(preview, videoContainer);
-
- const videoContainerWidth = videoContainer.clientWidth;
- const videoContainerHeight = videoContainer.clientHeight;
-
- setIsCenteredHorizontally(isCentered.horizontally);
- setIsCenteredVertically(isCentered.vertically);
-
- setStyle((prevSettings) => ({
- ...prevSettings,
- x: isCentered.horizontally
- ? (videoContainerWidth - (prevSettings.width as number)) / 2
- : d.x,
- y: isCentered.vertically
- ? (videoContainerHeight - (prevSettings.height as number)) / 2
- : d.y,
- }));
- },
- onResizeStop: (_e, _direction, ref, _delta, position) => {
- setStyle({
- width: ref.offsetWidth,
- height: ref.offsetHeight,
- x: position.x,
- y: position.y,
- });
- },
- } satisfies ComponentProps<typeof Rnd>),
- [styles, previewRef.current, containerRef.current]
- );
-
- return {
- props,
- setStyle,
- isCenteredVertically: isCenteredVertically && isDragging,
- isCenteredHorizontally: isCenteredHorizontally && isDragging,
- };
-}
-
-function elementIsCentered(element: HTMLElement, container: HTMLElement) {
- const containerRect = container.getBoundingClientRect();
- const previewRect = element.getBoundingClientRect();
-
- const containerCenterX = containerRect.left + containerRect.width / 2;
- const containerCenterY = containerRect.top + containerRect.height / 2;
-
- const previewCenterX = previewRect.left + previewRect.width / 2;
- const previewCenterY = previewRect.top + previewRect.height / 2;
-
- return {
- vertically:
- Math.abs(previewCenterY - containerCenterY) <= CENTERED_THRESHOLD,
- horizontally:
- Math.abs(previewCenterX - containerCenterX) <= CENTERED_THRESHOLD,
- };
-}
-
-async function getScreenStream() {
- try {
- const displayMediaOptions = {
- audio: false,
- surfaceSwitching: "exclude",
- selfBrowserSurface: "exclude",
- systemAudio: "exclude",
- };
-
- const stream = await navigator.mediaDevices.getDisplayMedia(
- displayMediaOptions
- );
-
- const videoElement = document.createElement("video");
- videoElement.srcObject = stream;
-
- return await new Promise<{
- videoElement: HTMLVideoElement;
- stream: MediaStream;
- }>((resolve) => {
- videoElement.onloadedmetadata = () => {
- resolve({ videoElement, stream });
- };
- });
- } catch (error) {
- console.error("Error capturing screen:", error);
- }
-}
-
-async function getWebcamStream(args: {
- deviceId?: string;
- microphoneId?: string;
-}) {
- try {
- const constraints: MediaStreamConstraints = {
- video: args.deviceId
- ? {
- deviceId: args.deviceId,
- width: { ideal: 1920 },
- height: { ideal: 1080 },
- }
- : { width: { ideal: 1920 }, height: { ideal: 1080 } },
- audio: args.microphoneId ? { deviceId: args.microphoneId } : false,
- };
-
- const stream = await navigator.mediaDevices.getUserMedia(constraints);
-
- return stream;
- } catch (error) {
- console.error("Error getting webcam stream:", error);
- }
-}
-
-function getWebcamDefaultStyles(
- { clientWidth, clientHeight }: HTMLDivElement,
- placement: "small" | "large"
-) {
- if (placement === "large") {
- return {
- x: (clientWidth - clientWidth / 2) / 2,
- y: (clientHeight - clientWidth / 2) / 2,
- width: clientWidth / 2,
- height: clientWidth / 2,
- };
- }
-
- const webcamWidth = 180;
-
- return {
- x: 16,
- y: clientHeight - 16 - webcamWidth,
- width: webcamWidth,
- height: webcamWidth,
- };
-}
-
-const devicesQuery = queryOptions({
- queryKey: ["devices"],
- queryFn: async () => {
- try {
- await navigator.mediaDevices.getUserMedia({
- audio: true,
- video: {
- width: { ideal: 1920 },
- height: { ideal: 1080 },
- },
- });
- const devices = await navigator.mediaDevices.enumerateDevices();
-
- return {
- audio: devices.filter((device) => device.kind === "audioinput"),
- video: devices.filter((device) => device.kind === "videoinput"),
- };
- } catch (error) {
- console.error("Error accessing media devices:", error);
- }
-
- return { audio: [], video: [] };
- },
- initialData: { audio: [], video: [] },
-});
-
-const WEBCAM_DEFAULT_STYLE = {
- x: 16,
- y: 16,
- width: 180,
- height: 180,
-};
-
-const SCREEN_DEFAULT_STYLE = {
- x: 0,
- y: 0,
- width: "100%",
- height: "100%",
-};
-
-const rndHandleStyles = {
- topLeft: {
- width: "16px",
- height: "16px",
- borderRadius: "50%",
- backgroundColor: "white",
- border: "2px solid #ddd",
- zIndex: 999,
- boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
- },
- topRight: {
- width: "16px",
- height: "16px",
- borderRadius: "50%",
- backgroundColor: "white",
- border: "2px solid #ddd",
- zIndex: 999,
- boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
- },
- bottomLeft: {
- width: "16px",
- height: "16px",
- borderRadius: "50%",
- backgroundColor: "white",
- border: "2px solid #ddd",
- zIndex: 999,
- boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
- },
- bottomRight: {
- width: "16px",
- height: "16px",
- borderRadius: "50%",
- backgroundColor: "white",
- border: "2px solid #ddd",
- zIndex: 999,
- boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
- },
-};
-
-function RecordingTimeText({ seconds }: { seconds: number }) {
- const time = useRecordingTimeFormat(seconds);
-
- return <>{time}</>;
-}
-
-function useRecordingTimeFormat(seconds: number) {
- return useMemo(() => {
- const minutes = Math.floor(seconds / 60);
- const formattedSeconds =
- seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
- return `${minutes}:${formattedSeconds}`;
- }, [seconds]);
-}
-
-function useLocalStoragePersist(key: string, value?: string) {
- useEffect(() => {
- if (value) localStorage.setItem(key, value);
- else localStorage.removeItem(key);
- }, [key, value]);
-}
diff --git a/apps/web/app/record/_components/ActionButton.tsx b/apps/web/app/record/_components/ActionButton.tsx
deleted file mode 100644
index 23fd81d02..000000000
--- a/apps/web/app/record/_components/ActionButton.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-"use client";
-
-import { ReactNode } from "react";
-
-export const ActionButton = ({
- handler,
- icon,
- label,
- width,
- active,
- recordingOption = false,
- optionName,
-}: {
- handler?: () => void;
- icon?: ReactNode;
- label?: string;
- width?: string;
- active?: boolean;
- recordingOption?: boolean;
- optionName?: string;
-}) => {
- const truncatedLabel =
- label && label.length > 18 ? label.substring(0, 18) + "..." : label;
-
- const commonProps = {
- className: `${
- active === true
- ? "bg-white hover:bg-gray-100"
- : "bg-gray-200 hover:bg-white"
- } border-gray-300 w-full h-[50px] py-2 px-4 text-[14px] border-2 flex items-center justify-between rounded-[15px] flex-grow transition-all shadow-sm shadow-[0px 0px 180px rgba(255, 255, 255, 0.18)]`,
- };
-
- const Element = handler ? "button" : "div";
-
- return (
- <div className="flex-grow">
- <Element {...(handler && { onClick: handler })} {...commonProps}>
- <div className="flex items-center">
- <span>{icon}</span>
- {truncatedLabel && (
- <span
- className={`ml-2 truncate ${width !== "full" && "max-w-[100px]"}`}
- >
- {truncatedLabel === "None" ? `No ${optionName}` : truncatedLabel}
- </span>
- )}
- </div>
- {recordingOption && (
- <div>
- <span
- className={`${
- label === "None"
- ? "bg-red-600 text-white"
- : "bg-tertiary text-primary "
- } h-5 w-8 font-medium text-xs rounded-full flex items-center justify-center`}
- >
- {label === "None" ? "Off" : "On"}
- </span>
- </div>
- )}
- </Element>
- </div>
- );
-};
diff --git a/apps/web/app/record/page.tsx b/apps/web/app/record/page.tsx
deleted file mode 100644
index a2ba99694..000000000
--- a/apps/web/app/record/page.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { redirect } from "next/navigation";
-import { Record } from "./Record";
-import { getCurrentUser } from "@cap/database/auth/session";
-
-export const revalidate = 0;
-
-export default async function RecordPage() {
- const user = await getCurrentUser();
-
- if (!user) {
- redirect("/login");
- }
-
- return <Record user={user} />;
-}
diff --git a/apps/web/app/record/useRecorder.ts b/apps/web/app/record/useRecorder.ts
deleted file mode 100644
index aa3ff76be..000000000
--- a/apps/web/app/record/useRecorder.ts
+++ /dev/null
@@ -1,776 +0,0 @@
-"use client";
-
-import { getLatestVideoId, saveLatestVideoId } from "@cap/utils";
-import { FFmpeg } from "@ffmpeg/ffmpeg";
-import type { FileData } from "@ffmpeg/ffmpeg/dist/esm/types";
-import { fetchFile } from "@ffmpeg/util";
-import { useStore } from "@tanstack/react-store";
-import { Store } from "@tanstack/store";
-import { useEffect, useMemo, useRef, useState } from "react";
-import toast from "react-hot-toast";
-
-const STOPPING_MESSAGES = ["Processing video", "Almost done", "Finishing up"];
-const FFMPEG_REINIT_INTERVAL = 25;
-
-async function uploadSegment({
- file,
- filename,
- videoId,
- duration,
-}: {
- file: Uint8Array | string;
- filename: string;
- videoId: string;
- duration?: string;
-}) {
- const formData = new FormData();
- formData.append("filename", filename);
- formData.append("videoId", videoId);
-
- let mimeType = "video/mp2t";
- if (filename.endsWith(".aac")) {
- mimeType = "audio/aac";
- } else if (filename.endsWith(".jpg")) {
- mimeType = "image/jpeg";
- }
- formData.append("blobData", new Blob([file], { type: mimeType }));
-
- if (duration) formData.append("duration", String(duration));
- if (filename.includes("video")) formData.append("framerate", "30");
-
- await fetch(`${process.env.NEXT_PUBLIC_URL}/api/upload/new`, {
- method: "POST",
- body: formData,
- });
-}
-
-function getSegmentIndexString(segmentIndex: number) {
- return String(segmentIndex).padStart(3, "0");
-}
-
-async function muxSegment({
- data,
- mimeType,
- start,
- end,
- segmentTime,
- segmentIndex,
- ffmpeg,
- hasAudio,
- userId,
- reinitializeFFmpeg,
- segmentCount,
-}: {
- data: Blob[];
- mimeType: string;
- start: number;
- end: number;
- segmentTime: number;
- segmentIndex: number;
- ffmpeg: FFmpeg;
- hasAudio: boolean;
- userId: string;
- reinitializeFFmpeg: () => Promise<FFmpeg>;
- segmentCount: number;
-}) {
- console.log("Muxing segment");
-
- if (segmentCount >= FFMPEG_REINIT_INTERVAL) {
- console.log("Reinitializing FFmpeg");
- ffmpeg = await reinitializeFFmpeg();
- console.log("FFmpeg reinitialized");
- }
-
- const segmentIndexString = getSegmentIndexString(segmentIndex);
- const videoSegment = new Blob(data, { type: "video/webm" });
-
- const inputFile = `temp_segment_${segmentIndexString}${
- mimeType.includes("mp4") ? ".mp4" : ".webm"
- }`;
- const outputFile = `segment_${segmentIndexString}.ts`;
-
- if (videoSegment) {
- const videoFile = await fetchFile(URL.createObjectURL(videoSegment));
-
- await ffmpeg.writeFile(inputFile, videoFile);
-
- const tempVideoCommand = [
- ["-ss", start.toFixed(2)],
- ["-to", end.toFixed(2)],
- ["-i", inputFile],
- ["-c:v", "libx264"],
- ["-preset", "ultrafast"],
- ["-crf", "0"],
- ["-pix_fmt", "yuv420p"],
- ["-r", "30"],
- ["-c:a", "aac"],
- ].flat();
- tempVideoCommand.push(outputFile);
-
- try {
- await ffmpeg.exec(tempVideoCommand);
- } catch (error) {
- console.error("Error executing tempVideoCommand with FFmpeg:", error);
- throw error;
- }
-
- let videoData: FileData;
- try {
- videoData = await ffmpeg.readFile(outputFile);
- console.log("file list: ", await ffmpeg.listDir("/"));
- } catch (error) {
- console.error("Error reading video file with FFmpeg:", error);
- throw error;
- }
-
- const videoId = getLatestVideoId();
-
- if (segmentIndex === 0) {
- console.log("Generating screenshot...");
- const video = document.createElement("video");
- video.src = URL.createObjectURL(videoSegment);
- video.muted = true;
- video.autoplay = true;
- video.playsInline = true;
-
- video.addEventListener("loadeddata", async () => {
- const canvas = document.createElement("canvas");
- canvas.width = video.videoWidth;
- canvas.height = video.videoHeight;
-
- const context = canvas.getContext("2d");
- context?.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
-
- canvas.toBlob(
- async (screenshotBlob) => {
- if (screenshotBlob) {
- const screenshotFile = await fetchFile(
- URL.createObjectURL(screenshotBlob)
- );
-
- const screenshotFilename = "screenshot/screen-capture.jpg";
- await uploadSegment({
- file: screenshotFile,
- filename: screenshotFilename,
- videoId,
- });
- }
- },
- "image/jpeg",
- 0.5
- );
- video.remove();
- canvas.remove();
- });
-
- video.play().catch((error) => {
- console.error("Video play failed:", error);
- });
- }
-
- const presignedPostData = await getPresignedPostData(userId, videoId, {
- type: "segment",
- name: outputFile,
- duration: segmentTime,
- });
-
- const formData = new FormData();
-
- Object.entries(presignedPostData.fields).forEach(([key, value]) => {
- formData.append(key, value);
- });
-
- let mimeType = "video/mp2t";
- if (outputFile.endsWith(".aac")) mimeType = "audio/aac";
- else if (outputFile.endsWith(".jpg")) mimeType = "image/jpeg";
-
- formData.append("file", new Blob([videoData], { type: mimeType }));
-
- try {
- await fetch(presignedPostData.url, {
- method: "POST",
- body: formData,
- mode: "no-cors",
- });
- } catch {
- console.log("error uploading segment");
- }
-
- console.log("herelast: ", await ffmpeg.listDir("/"));
-
- try {
- await ffmpeg.deleteFile(inputFile);
- } catch (error) {
- console.error("Error deleting temp input file:", error);
- }
-
- try {
- await ffmpeg.deleteFile(outputFile);
- } catch (error) {
- console.error("Error deleting video input file:", error);
- }
- }
-}
-
-async function createRecorder(
- videoDevice: MediaDeviceInfo | undefined,
- videoStream: MediaStream | null,
- audioDevice: MediaDeviceInfo | undefined,
- ffmpeg: FFmpeg,
- userId: string,
- videoContainer: HTMLElement,
- screenPreview?: HTMLVideoElement,
- webcamPreview?: HTMLVideoElement
-) {
- let ffmpegInstance = ffmpeg;
- let segmentCount = 0;
-
- const reinitializeFFmpeg = async () => {
- console.log("Reinitializing FFmpeg");
- ffmpegInstance = new FFmpeg();
- await ffmpegInstance.load();
- console.log("FFmpeg reinitialized");
- return ffmpegInstance;
- };
-
- const res = await fetch(
- `${process.env.NEXT_PUBLIC_URL}/api/desktop/video/create?recordingMode=hls`,
- {
- method: "GET",
- credentials: "include",
- cache: "no-store",
- }
- );
-
- if (res.status === 401) {
- toast.error("Unauthorized - please sign in again.");
- throw "Unauthorized";
- }
-
- const videoCreateData = await res.json();
-
- if (
- !videoCreateData.id ||
- !videoCreateData.user_id ||
- !videoCreateData.aws_region ||
- !videoCreateData.aws_bucket
- ) {
- toast.error("No data received - please try again later.");
- throw "No data received";
- }
-
- saveLatestVideoId(videoCreateData.id);
-
- const combinedStream = new MediaStream();
- const canvas = document.createElement("canvas");
- const ctx = canvas.getContext("2d", { willReadFrequently: true });
-
- let screenX: number,
- screenY: number,
- screenWidth: number,
- screenHeight: number;
- let webcamX: number,
- webcamY: number,
- webcamWidth: number,
- webcamHeight: number;
- let newWebcamWidth: number,
- newWebcamHeight: number,
- offsetX: number,
- offsetY: number;
-
- // Set canvas dimensions to video container dimensions
- canvas.width = videoContainer.clientWidth;
- canvas.height = videoContainer.clientHeight;
-
- // Calculate coordinates and dimensions once
- if (screenPreview && videoContainer) {
- const screenRect = screenPreview.getBoundingClientRect();
- const containerRect = videoContainer.getBoundingClientRect();
-
- screenX =
- (screenRect.left - containerRect.left) *
- (canvas.width / containerRect.width);
- screenY =
- (screenRect.top - containerRect.top) *
- (canvas.height / containerRect.height);
- screenWidth = screenRect.width * (canvas.width / containerRect.width);
- screenHeight = screenRect.height * (canvas.height / containerRect.height);
- }
-
- if (webcamPreview && videoContainer && videoDevice) {
- const webcamRect = webcamPreview.getBoundingClientRect();
- const containerRect = videoContainer.getBoundingClientRect();
-
- webcamX =
- (webcamRect.left - containerRect.left) *
- (canvas.width / containerRect.width);
- webcamY =
- (webcamRect.top - containerRect.top) *
- (canvas.height / containerRect.height);
- webcamWidth = webcamRect.width * (canvas.width / containerRect.width);
- webcamHeight = webcamRect.height * (canvas.height / containerRect.height);
-
- const videoAspectRatio =
- webcamPreview.videoWidth / webcamPreview.videoHeight;
- newWebcamWidth = webcamWidth * 2;
- newWebcamHeight = newWebcamWidth / videoAspectRatio;
- offsetX = (newWebcamWidth - webcamWidth) / 2;
- offsetY = (newWebcamHeight - webcamHeight) / 2;
- }
-
- const drawCanvas = () => {
- if (ctx && screenPreview && videoContainer) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(screenPreview, screenX, screenY, screenWidth, screenHeight);
-
- if (webcamPreview && videoContainer && videoDevice) {
- ctx.save();
- ctx.beginPath();
- ctx.arc(
- webcamX + webcamWidth / 2,
- webcamY + webcamHeight / 2,
- webcamWidth / 2,
- 0,
- 2 * Math.PI
- );
- ctx.clip();
- ctx.drawImage(
- webcamPreview,
- webcamX - offsetX,
- webcamY - offsetY,
- newWebcamWidth,
- newWebcamHeight
- );
- ctx.restore();
- }
- }
- };
-
- const startDrawing = () => {
- const drawLoop = () => {
- drawCanvas();
- animationFrameId = requestAnimationFrame(drawLoop);
- };
- drawLoop();
- return animationFrameId;
- };
-
- const intervalDrawing = () => setInterval(drawCanvas, 1000 / 30); // 30 fps
-
- // Start drawing on canvas using requestAnimationFrame
- let animationFrameId = 0;
- animationFrameId = startDrawing();
- let animationIntervalId: number | NodeJS.Timeout | null = null;
-
- // Fallback to setInterval if the tab is not active
- document.addEventListener("visibilitychange", () => {
- if (document.hidden) {
- cancelAnimationFrame(animationFrameId);
- animationIntervalId = intervalDrawing();
- } else {
- if (animationIntervalId) {
- clearInterval(animationIntervalId);
- animationIntervalId = null;
- }
- animationFrameId = startDrawing();
- }
- });
-
- const canvasStream = canvas.captureStream(30);
- if (canvasStream.getVideoTracks().length === 0) {
- throw "Canvas stream has no video tracks";
- }
-
- for (const track of canvasStream.getVideoTracks()) {
- combinedStream.addTrack(track);
- }
-
- if (videoStream && videoDevice) {
- for (const track of videoStream.getAudioTracks()) {
- combinedStream.addTrack(track);
- }
- }
-
- const mimeTypes = [
- "video/webm;codecs=h264",
- "video/webm;codecs=vp9",
- "video/webm;codecs=vp8",
- "video/webm",
- "video/mp4",
- ];
-
- let selectedMimeType = "";
- for (const mimeType of mimeTypes) {
- if (MediaRecorder.isTypeSupported(mimeType)) {
- selectedMimeType = mimeType;
- break;
- }
- }
-
- if (!selectedMimeType) {
- toast.error("Sorry, your browser does not support screen recording :(");
- throw "No supported MIME type found for screen recording";
- }
-
- const videoRecorderOptions = {
- mimeType: selectedMimeType,
- };
-
- if (!MediaRecorder.isTypeSupported(videoRecorderOptions.mimeType)) {
- throw "Video MIME type not supported";
- }
-
- const videoRecorder = new MediaRecorder(combinedStream, videoRecorderOptions);
-
- const chunks: Blob[] = [];
- let segmentStartTime = Date.now();
- const recordingStartTime = Date.now();
-
- // public stuff for UI to use
- const store = new Store<RecorderStore>({
- status: "recording",
- seconds: 0,
- });
-
- const startTime = Date.now();
- const secondsInterval = setInterval(() => {
- const seconds = Math.floor((Date.now() - startTime) / 1000);
- store.setState(() => ({ status: "recording", seconds }));
- }, 1000);
-
- let totalSegments = 0;
- let onReadyToStopRecording!: () => void;
- const readyToStopRecording = new Promise<void>((resolve) => {
- onReadyToStopRecording = resolve;
- });
-
- const muxQueue = new AsyncTaskQueue();
-
- const segments: Array<Segment> = [];
-
- videoRecorder.ondataavailable = async (event) => {
- if (event.data.size > 0) {
- chunks.push(event.data);
- const segmentEndTime = Date.now();
- const segmentDuration = (segmentEndTime - segmentStartTime) / 1000.0;
-
- const videoDuration = (Date.now() - recordingStartTime) / 1000.0;
-
- console.log("Video duration:", videoDuration);
- console.log("Segment duration:", segmentDuration);
- console.log("Start:", Math.max(videoDuration - segmentDuration, 0));
-
- const final =
- videoRecorder.state !== "recording" ||
- store.state.status === "stopping";
- console.log("Final segment? ", final);
-
- muxQueue.enqueue(async () => {
- try {
- segments.push({
- name: `segment_${getSegmentIndexString(totalSegments)}.ts`,
- duration: segmentDuration,
- });
-
- if (segmentCount >= FFMPEG_REINIT_INTERVAL) {
- await reinitializeFFmpeg();
- segmentCount = 0;
- }
-
- await muxSegment({
- data: chunks,
- mimeType: videoRecorderOptions.mimeType,
- start: Math.max(videoDuration - segmentDuration, 0),
- end: videoDuration,
- segmentTime: segmentDuration,
- segmentIndex: totalSegments,
- hasAudio: videoStream !== null && audioDevice !== undefined,
- ffmpeg: ffmpegInstance,
- userId,
- reinitializeFFmpeg,
- segmentCount,
- });
-
- totalSegments++;
- segmentCount++;
-
- if (final) onReadyToStopRecording();
- } catch (error) {
- console.error("Error in muxSegment:", error);
- onReadyToStopRecording();
- }
- });
-
- segmentStartTime = segmentEndTime;
- }
- };
-
- videoRecorder.start(3000);
-
- return {
- store,
- videoRecorder,
- stop: async () => {
- if (store.state.status !== "recording") return;
-
- let messageIndex = 0;
-
- const nextMessage = () => {
- store.setState(() => ({
- status: "stopping",
- message: STOPPING_MESSAGES[messageIndex % STOPPING_MESSAGES.length],
- }));
- messageIndex++;
- };
-
- nextMessage();
-
- const messageInterval = setInterval(nextMessage, 2000);
- clearInterval(secondsInterval);
-
- console.log("---Stopping recording function fired here---");
-
- try {
- videoRecorder.stop();
- console.log("Video recorder stopped");
-
- await readyToStopRecording;
-
- await muxQueue.waitForQueueEmpty();
-
- console.log("All segments muxed");
-
- const videoId = getLatestVideoId();
-
- const playlist = createPlaylist(segments);
-
- const presignedPostData = await getPresignedPostData(userId, videoId, {
- type: "playlist",
- });
-
- const formData = new FormData();
-
- Object.entries(presignedPostData.fields).forEach(([key, value]) => {
- formData.append(key, value);
- });
-
- formData.append(
- "file",
- new Blob([playlist], { type: "application/x-mpegURL" })
- );
-
- try {
- await fetch(presignedPostData.url, {
- method: "POST",
- body: formData,
- mode: "no-cors",
- });
- } catch {
- console.log("error uploading playlist");
- }
-
- console.log("---Opening link here---");
-
- const url =
- process.env.NEXT_PUBLIC_ENVIRONMENT === "development"
- ? `${process.env.NEXT_PUBLIC_URL}/s/${videoId}`
- : `https://cap.link/${videoId}`;
-
- const audio = new Audio("/recording-end.mp3");
- await audio.play();
- console.log({ url });
- window.open(url, "_blank");
- } finally {
- clearInterval(messageInterval);
- }
- },
- };
-}
-
-export function useRecorder(userId: string) {
- const [ffmpeg] = useState(() => new FFmpeg());
- const [isLoading, setIsLoading] = useState(true);
- const [recorder, setRecorder] = useState<Recorder | null>(null);
- const recorderRef = useRef(recorder);
- recorderRef.current = recorder;
-
- useEffect(() => {
- const loadFFmpeg = async () => {
- setIsLoading(true);
-
- console.log("Loading FFmpeg");
-
- await ffmpeg.load.call(ffmpeg);
- setIsLoading(false);
-
- console.log("FFmpeg loaded");
- };
-
- loadFFmpeg();
- }, [ffmpeg]);
-
- const store = useMemo(() => {
- recorder;
- return new Store<FullStore>({ status: "idle" });
- }, [recorder]);
-
- const state = useStore(
- (recorder?.store as Store<FullStore> | undefined) ?? store
- );
-
- return {
- state,
- isLoading,
- start(
- videoDevice: MediaDeviceInfo | undefined,
- videoStream: MediaStream | null,
- audioDevice: MediaDeviceInfo | undefined,
- videoContainer: HTMLElement,
- screenPreview?: HTMLVideoElement,
- webcamPreview?: HTMLVideoElement
- ) {
- if (!screen) {
- toast.error(
- "No screen capture source selected, plesae select a screen source."
- );
- return;
- }
-
- store.setState(() => ({ status: "starting" }));
-
- createRecorder(
- videoDevice,
- videoStream,
- audioDevice,
- ffmpeg,
- userId,
- videoContainer,
- screenPreview,
- webcamPreview
- )
- .then((recorder) => {
- setRecorder(recorder);
- })
- .catch((e) => {
- console.error(e);
- store.setState(() => ({ status: "idle" }));
- });
- },
- stop() {
- recorderRef.current?.stop().finally(() => {
- setRecorder(null);
- });
- },
- };
-}
-
-export type Recorder = Awaited<ReturnType<typeof createRecorder>>;
-export type RecorderStore =
- | { status: "recording"; seconds: number }
- | { status: "stopping"; message: string };
-type FullStore = RecorderStore | { status: "idle" } | { status: "starting" };
-
-class AsyncTaskQueue {
- private queue: (() => Promise<void>)[];
- private activeTasks: number;
- private resolveEmptyPromise: (() => void) | null;
-
- constructor() {
- this.queue = [];
- this.activeTasks = 0;
- this.resolveEmptyPromise = null;
- }
-
- public enqueue(task: () => Promise<void>) {
- this.queue.push(task);
- this.processQueue(); // Call processQueue whenever a new task is enqueued
- }
-
- private async processQueue() {
- if (this.activeTasks >= 1 || this.queue.length === 0) {
- return; // Don't start processing if there are already active tasks or the queue is empty
- }
-
- const task = this.queue.shift();
- if (task) {
- this.activeTasks++;
- try {
- await task();
- } finally {
- this.activeTasks--;
- if (this.activeTasks === 0 && this.resolveEmptyPromise) {
- this.resolveEmptyPromise();
- this.resolveEmptyPromise = null;
- }
- this.processQueue();
- }
- }
- }
-
- public waitForQueueEmpty(): Promise<void> {
- if (this.activeTasks === 0 && this.queue.length === 0) {
- return Promise.resolve();
- }
- return new Promise((resolve) => {
- this.resolveEmptyPromise = resolve;
- });
- }
-}
-
-type Segment = { name: string; duration: number };
-
-function createPlaylist(segments: Array<Segment>) {
- let playlist = `#EXTM3U
-#EXT-X-VERSION:6
-#EXT-X-TARGETDURATION:3
-#EXT-X-MEDIA-SEQUENCE:0
-#EXT-X-PLAYLIST-TYPE:VOD
-#EXT-X-INDEPENDENT-SEGMENTS
-`;
-
- for (const segment of segments) {
- playlist += `#EXTINF:${segment.duration},\n${segment.name}\n`;
- }
-
- playlist += "#EXT-X-ENDLIST";
-
- return playlist;
-}
-
-async function getPresignedPostData(
- userId: string,
- videoId: string,
- args:
- | { type: "segment"; name: string; duration: number }
- | { type: "playlist" }
-) {
- const fileKeyBase = `${userId}/${videoId}/combined-source`;
-
- let fileKey: string;
-
- if (args.type === "segment") fileKey = `${fileKeyBase}/${args.name}`;
- else fileKey = `${fileKeyBase}/stream.m3u8`;
-
- const body: Record<string, any> = {
- userId,
- fileKey,
- awsBucket: process.env.NEXT_PUBLIC_CAP_AWS_BUCKET,
- awsRegion: process.env.NEXT_PUBLIC_CAP_AWS_REGION,
- };
-
- if (args.type === "segment") {
- body["segment"] = args.duration.toFixed(1);
- }
-
- const signedUrlResp = await fetch("/api/upload/signed", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- });
-
- const signedUrlJson: { fields: object; url: string } = (
- await signedUrlResp.json()
- ).presignedPostData;
-
- return signedUrlJson;
-}
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index 095d594a1..ca0dad84c 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -9,6 +9,7 @@
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
+ "noUncheckedIndexedAccess": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
diff --git a/apps/web/utils/s3.ts b/apps/web/utils/s3.ts
new file mode 100644
index 000000000..80c571fbf
--- /dev/null
+++ b/apps/web/utils/s3.ts
@@ -0,0 +1,32 @@
+import { S3Client } from "@aws-sdk/client-s3";
+import type { s3Buckets } from "@cap/database/schema";
+import type { InferSelectModel } from "drizzle-orm";
+
+type S3Config = {
+ endpoint?: string | null;
+ region?: string;
+ accessKeyId?: string;
+ secretAccessKey?: string;
+} | null;
+
+export function createS3Client(config?: S3Config) {
+ return new S3Client(getS3Config(config));
+}
+
+export function getS3Config(config?: S3Config) {
+ return {
+ endpoint: config?.endpoint ?? process.env.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
+ region: config?.region ?? process.env.NEXT_PUBLIC_CAP_AWS_REGION,
+ credentials: {
+ accessKeyId: config?.accessKeyId ?? process.env.CAP_AWS_ACCESS_KEY ?? "",
+ secretAccessKey:
+ config?.secretAccessKey ?? process.env.CAP_AWS_SECRET_KEY ?? "",
+ },
+ };
+}
+
+export function getS3Bucket(
+ bucket?: InferSelectModel<typeof s3Buckets> | null
+) {
+ return bucket?.bucketName ?? (process.env.NEXT_PUBLIC_CAP_AWS_BUCKET || "");
+}
diff --git a/packages/database/schema.ts b/packages/database/schema.ts
index 88dd567db..41ae6311c 100644
--- a/packages/database/schema.ts
+++ b/packages/database/schema.ts
@@ -11,7 +11,6 @@ import {
uniqueIndex,
varchar,
float,
- mysqlEnum,
} from "drizzle-orm/mysql-core";
import { relations } from "drizzle-orm/relations";
import { nanoIdLength } from "./helpers";
@@ -22,6 +21,12 @@ const nanoId = customType<{ data: string; notNull: true }>({
},
});
+const nanoIdNullable = customType<{ data: string; notNull: false }>({
+ dataType() {
+ return `varchar(${nanoIdLength})`;
+ },
+});
+
export const users = mysqlTable(
"users",
{
@@ -45,6 +50,7 @@ export const users = mysqlTable(
created_at: timestamp("created_at").notNull().defaultNow(),
updated_at: timestamp("updated_at").notNull().defaultNow().onUpdateNow(),
onboarding_completed_at: timestamp("onboarding_completed_at"),
+ customBucket: nanoId("customBucket"),
},
(table) => ({
emailIndex: uniqueIndex("email_idx").on(table.email),
@@ -145,6 +151,7 @@ export const videos = mysqlTable(
name: varchar("name", { length: 255 }).notNull().default("My Video"),
awsRegion: varchar("awsRegion", { length: 255 }),
awsBucket: varchar("awsBucket", { length: 255 }),
+ bucket: nanoIdNullable("bucket"),
metadata: json("metadata"),
public: boolean("public").notNull().default(true),
videoStartTime: varchar("videoStartTime", { length: 255 }),
@@ -158,11 +165,11 @@ export const videos = mysqlTable(
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow().onUpdateNow(),
source: json("source")
- .$type<
- { type: "MediaConvert" } | { type: "local" } | { type: "desktopMP4" }
- >()
- .notNull()
- .default({ type: "MediaConvert" }),
+ .$type<
+ { type: "MediaConvert" } | { type: "local" } | { type: "desktopMP4" }
+ >()
+ .notNull()
+ .default({ type: "MediaConvert" }),
},
(table) => ({
idIndex: index("id_idx").on(table.id),
@@ -215,6 +222,16 @@ export const comments = mysqlTable(
})
);
+export const s3Buckets = mysqlTable("s3_buckets", {
+ id: nanoId("id").notNull().primaryKey().unique(),
+ ownerId: nanoId("ownerId").notNull(),
+ region: varchar("region", { length: 255 }).notNull(),
+ endpoint: text("endpoint"),
+ bucketName: varchar("bucketName", { length: 255 }).notNull(),
+ accessKeyId: varchar("accessKeyId", { length: 255 }).notNull(),
+ secretAccessKey: varchar("secretAccessKey", { length: 255 }).notNull(),
+});
+
export const commentsRelations = relations(comments, ({ one }) => ({
author: one(users, {
fields: [comments.authorId],
@@ -231,12 +248,13 @@ export const commentsRelations = relations(comments, ({ one }) => ({
}));
// Define Relationships
-export const usersRelations = relations(users, ({ many }) => ({
+export const usersRelations = relations(users, ({ many, one }) => ({
accounts: many(accounts),
sessions: many(sessions),
spaceMembers: many(spaceMembers),
videos: many(videos),
sharedVideos: many(sharedVideos),
+ customBucket: one(s3Buckets),
}));
export const accountsRelations = relations(accounts, ({ one }) => ({
diff --git a/packages/utils/package.json b/packages/utils/package.json
index 1626d4324..afd517664 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -12,16 +12,17 @@
"build": "tsc"
},
"devDependencies": {
- "tsconfig": "workspace:*",
- "typescript": "^5.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
- "react-router-dom": "^6.18.0"
+ "react-router-dom": "^6.18.0",
+ "tsconfig": "workspace:*",
+ "typescript": "^5.3.2"
},
"dependencies": {
- "tailwind-merge": "^2.1.0",
+ "@aws-sdk/client-s3": "^3.485.0",
"clsx": "^2.0.0",
- "stripe": "^14.24.0"
+ "stripe": "^14.24.0",
+ "tailwind-merge": "^2.1.0"
},
"engines": {
"node": "20"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 69c51e1c1..e9532301d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -903,6 +903,9 @@ importers:
packages/utils:
dependencies:
+ '@aws-sdk/client-s3':
+ specifier: ^3.485.0
+ version: 3.658.1
clsx:
specifier: ^2.0.0
version: 2.1.1
@@ -16479,7 +16482,7 @@ snapshots:
doctrine: 2.1.0
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
hasown: 2.0.2
is-core-module: 2.15.1
is-glob: 4.0.3