Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add developer SDK API routes

Richie McIlroyae7de3950ca3
diff --git a/apps/web/app/api/developer/sdk/v1/[...route]/route.ts b/apps/web/app/api/developer/sdk/v1/[...route]/route.ts
new file mode 100644
index 000000000..3d90bd4d6
--- /dev/null
+++ b/apps/web/app/api/developer/sdk/v1/[...route]/route.ts
@@ -0,0 +1,15 @@
+import { Hono } from "hono";
+import { handle } from "hono/vercel";
+import { developerSdkCors } from "../../../../utils";
+import * as upload from "./upload";
+import * as videoCreate from "./video-create";
+
+const app = new Hono()
+ .basePath("/api/developer/sdk/v1")
+ .use(developerSdkCors)
+ .route("/videos", videoCreate.app)
+ .route("/upload/multipart", upload.app);
+
+export const GET = handle(app);
+export const POST = handle(app);
+export const OPTIONS = handle(app);
diff --git a/apps/web/app/api/developer/sdk/v1/[...route]/upload.ts b/apps/web/app/api/developer/sdk/v1/[...route]/upload.ts
new file mode 100644
index 000000000..d5039077b
--- /dev/null
+++ b/apps/web/app/api/developer/sdk/v1/[...route]/upload.ts
@@ -0,0 +1,294 @@
+import { db } from "@cap/database";
+import { nanoId } from "@cap/database/helpers";
+import {
+ developerCreditAccounts,
+ developerCreditTransactions,
+ developerVideos,
+} from "@cap/database/schema";
+import { provideOptionalAuth, S3Buckets } from "@cap/web-backend";
+import { zValidator } from "@hono/zod-validator";
+import { and, eq, sql } from "drizzle-orm";
+import { Effect } from "effect";
+import { Hono } from "hono";
+import { z } from "zod";
+import { runPromise } from "@/lib/server";
+import { withDeveloperPublicAuth } from "../../../../utils";
+
+const MICRO_CREDITS_PER_MINUTE = 5_000;
+
+export const app = new Hono<{
+ Variables: {
+ developerAppId: string;
+ developerKeyType: "public";
+ };
+}>().use(withDeveloperPublicAuth);
+
+app.post(
+ "/initiate",
+ zValidator(
+ "json",
+ z.object({
+ videoId: z.string(),
+ contentType: z.string().optional(),
+ }),
+ ),
+ async (c) => {
+ const appId = c.get("developerAppId");
+ const { videoId, contentType } = c.req.valid("json");
+
+ const [video] = await db()
+ .select()
+ .from(developerVideos)
+ .where(eq(developerVideos.id, videoId))
+ .limit(1);
+
+ if (!video || video.appId !== appId) {
+ return c.json({ error: "Video not found" }, 404);
+ }
+
+ if (!video.s3Key) {
+ return c.json({ error: "Video has no S3 key" }, 400);
+ }
+
+ const s3Key = video.s3Key;
+
+ try {
+ const uploadId = await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess();
+ const { UploadId } = yield* bucket.multipart.create(s3Key, {
+ ContentType: contentType ?? "video/mp4",
+ CacheControl: "max-age=31536000",
+ });
+ if (!UploadId) throw new Error("No UploadId returned");
+ return UploadId;
+ }).pipe(provideOptionalAuth, runPromise);
+
+ return c.json({ uploadId });
+ } catch (error) {
+ console.error("Error initiating multipart upload:", error);
+ return c.json({ error: "Failed to initiate upload" }, 500);
+ }
+ },
+);
+
+app.post(
+ "/presign-part",
+ zValidator(
+ "json",
+ z.object({
+ videoId: z.string(),
+ uploadId: z.string(),
+ partNumber: z.number(),
+ }),
+ ),
+ async (c) => {
+ const appId = c.get("developerAppId");
+ const { videoId, uploadId, partNumber } = c.req.valid("json");
+
+ const [video] = await db()
+ .select()
+ .from(developerVideos)
+ .where(eq(developerVideos.id, videoId))
+ .limit(1);
+
+ if (!video || video.appId !== appId) {
+ return c.json({ error: "Video not found" }, 404);
+ }
+
+ if (!video.s3Key) {
+ return c.json({ error: "Video has no S3 key" }, 400);
+ }
+
+ const s3Key = video.s3Key;
+
+ try {
+ const presignedUrl = await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess();
+ return yield* bucket.multipart.getPresignedUploadPartUrl(
+ s3Key,
+ uploadId,
+ partNumber,
+ );
+ }).pipe(provideOptionalAuth, runPromise);
+
+ return c.json({ presignedUrl });
+ } catch (error) {
+ console.error("Error creating presigned URL:", error);
+ return c.json({ error: "Failed to create presigned URL" }, 500);
+ }
+ },
+);
+
+app.post(
+ "/complete",
+ zValidator(
+ "json",
+ z.object({
+ videoId: z.string(),
+ uploadId: z.string(),
+ parts: z.array(
+ z.object({
+ partNumber: z.number(),
+ etag: z.string(),
+ size: z.number(),
+ }),
+ ),
+ durationInSecs: z.number().optional(),
+ width: z.number().optional(),
+ height: z.number().optional(),
+ fps: z.number().optional(),
+ }),
+ ),
+ async (c) => {
+ const appId = c.get("developerAppId");
+ const { videoId, uploadId, parts, durationInSecs, width, height, fps } =
+ c.req.valid("json");
+
+ const [video] = await db()
+ .select()
+ .from(developerVideos)
+ .where(eq(developerVideos.id, videoId))
+ .limit(1);
+
+ if (!video || video.appId !== appId) {
+ return c.json({ error: "Video not found" }, 404);
+ }
+
+ if (!video.s3Key) {
+ return c.json({ error: "Video has no S3 key" }, 400);
+ }
+
+ const s3Key = video.s3Key;
+
+ try {
+ await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess();
+
+ const sortedParts = [...parts].sort(
+ (a, b) => a.partNumber - b.partNumber,
+ );
+ const formattedParts = sortedParts.map((part) => ({
+ PartNumber: part.partNumber,
+ ETag: part.etag,
+ }));
+
+ yield* bucket.multipart.complete(s3Key, uploadId, {
+ MultipartUpload: { Parts: formattedParts },
+ });
+ }).pipe(provideOptionalAuth, runPromise);
+
+ const updates: Record<string, unknown> = {};
+ if (durationInSecs !== undefined) updates.duration = durationInSecs;
+ if (width !== undefined) updates.width = width;
+ if (height !== undefined) updates.height = height;
+ if (fps !== undefined) updates.fps = fps;
+
+ if (Object.keys(updates).length > 0) {
+ await db()
+ .update(developerVideos)
+ .set(updates)
+ .where(eq(developerVideos.id, videoId));
+ }
+
+ if (durationInSecs && durationInSecs > 0) {
+ const durationMinutes = durationInSecs / 60;
+ const microCreditsToDebit = Math.floor(
+ durationMinutes * MICRO_CREDITS_PER_MINUTE,
+ );
+
+ const [account] = await db()
+ .select()
+ .from(developerCreditAccounts)
+ .where(eq(developerCreditAccounts.appId, appId))
+ .limit(1);
+
+ if (account && microCreditsToDebit > 0) {
+ await db().transaction(async (tx) => {
+ await tx
+ .update(developerCreditAccounts)
+ .set({
+ balanceMicroCredits: sql`${developerCreditAccounts.balanceMicroCredits} - ${microCreditsToDebit}`,
+ })
+ .where(
+ and(
+ eq(developerCreditAccounts.id, account.id),
+ sql`${developerCreditAccounts.balanceMicroCredits} >= ${microCreditsToDebit}`,
+ ),
+ );
+
+ const [updated] = await tx
+ .select({
+ balanceMicroCredits:
+ developerCreditAccounts.balanceMicroCredits,
+ })
+ .from(developerCreditAccounts)
+ .where(eq(developerCreditAccounts.id, account.id))
+ .limit(1);
+
+ await tx.insert(developerCreditTransactions).values({
+ id: nanoId(),
+ accountId: account.id,
+ type: "video_create",
+ amountMicroCredits: -microCreditsToDebit,
+ balanceAfterMicroCredits: updated.balanceMicroCredits,
+ referenceId: videoId,
+ referenceType: "developer_video",
+ metadata: { durationSeconds: durationInSecs },
+ });
+ });
+ }
+ }
+
+ return c.json({ success: true });
+ } catch (error) {
+ console.error("Error completing multipart upload:", error);
+ return c.json({ error: "Failed to complete upload" }, 500);
+ }
+ },
+);
+
+app.post(
+ "/abort",
+ zValidator(
+ "json",
+ z.object({
+ videoId: z.string(),
+ uploadId: z.string(),
+ }),
+ ),
+ async (c) => {
+ const appId = c.get("developerAppId");
+ const { videoId, uploadId } = c.req.valid("json");
+
+ const [video] = await db()
+ .select()
+ .from(developerVideos)
+ .where(eq(developerVideos.id, videoId))
+ .limit(1);
+
+ if (!video || video.appId !== appId) {
+ return c.json({ error: "Video not found" }, 404);
+ }
+
+ if (!video.s3Key) {
+ return c.json({ error: "Video has no S3 key" }, 400);
+ }
+
+ const s3Key = video.s3Key;
+
+ try {
+ await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess();
+ const multipart = bucket.multipart as typeof bucket.multipart & {
+ abort: (key: string, uploadId: string) => Effect.Effect<void>;
+ };
+ yield* multipart.abort(s3Key, uploadId);
+ }).pipe(provideOptionalAuth, runPromise);
+
+ return c.json({ success: true });
+ } catch (error) {
+ console.error("Error aborting multipart upload:", error);
+ return c.json({ error: "Failed to abort upload" }, 500);
+ }
+ },
+);
diff --git a/apps/web/app/api/developer/sdk/v1/[...route]/video-create.ts b/apps/web/app/api/developer/sdk/v1/[...route]/video-create.ts
new file mode 100644
index 000000000..f155928f9
--- /dev/null
+++ b/apps/web/app/api/developer/sdk/v1/[...route]/video-create.ts
@@ -0,0 +1,67 @@
+import { db } from "@cap/database";
+import { nanoId } from "@cap/database/helpers";
+import { developerCreditAccounts, developerVideos } from "@cap/database/schema";
+import { buildEnv } from "@cap/env";
+import { zValidator } from "@hono/zod-validator";
+import { eq } from "drizzle-orm";
+import { Hono } from "hono";
+import { z } from "zod";
+import { withDeveloperPublicAuth } from "../../../../utils";
+
+const MIN_BALANCE_MICRO_CREDITS = 5_000;
+
+export const app = new Hono<{
+ Variables: {
+ developerAppId: string;
+ developerKeyType: "public";
+ };
+}>().use(withDeveloperPublicAuth);
+
+app.post(
+ "/create",
+ zValidator(
+ "json",
+ z.object({
+ name: z.string().optional(),
+ userId: z.string().optional(),
+ metadata: z.record(z.unknown()).optional(),
+ }),
+ ),
+ async (c) => {
+ const appId = c.get("developerAppId");
+ const body = c.req.valid("json");
+
+ const [account] = await db()
+ .select()
+ .from(developerCreditAccounts)
+ .where(eq(developerCreditAccounts.appId, appId))
+ .limit(1);
+
+ if (!account || account.balanceMicroCredits < MIN_BALANCE_MICRO_CREDITS) {
+ return c.json({ error: "Insufficient credits" }, 402);
+ }
+
+ const videoId = nanoId();
+ const s3Key = `developer/${appId}/${videoId}/result.mp4`;
+
+ await db()
+ .insert(developerVideos)
+ .values({
+ id: videoId,
+ appId,
+ externalUserId: body.userId,
+ name: body.name ?? "Untitled",
+ s3Key,
+ metadata: body.metadata,
+ });
+
+ const webUrl = buildEnv.NEXT_PUBLIC_WEB_URL;
+
+ return c.json({
+ videoId,
+ s3Key,
+ shareUrl: `${webUrl}/dev/${videoId}`,
+ embedUrl: `${webUrl}/embed/${videoId}?sdk=1`,
+ });
+ },
+);