Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
import { db } from "@cap/database";
import { sendEmail } from "@cap/database/emails/config";
import { FirstShareableLink } from "@cap/database/emails/first-shareable-link";
import { nanoId } from "@cap/database/helpers";
import {
organizationMembers,
organizations,
users,
videos,
videoUploads,
} from "@cap/database/schema";
import type { VideoMetadata } from "@cap/database/types";
import { getNewVideoPublic } from "@cap/database/video-sharing-default";
import { serverEnv } from "@cap/env";
import { userIsPro } from "@cap/utils";
import { makeCurrentUserLayer, Storage, Videos } from "@cap/web-backend";
import { Organisation, Video } from "@cap/web-domain";
import { zValidator } from "@hono/zod-validator";
import { and, count, eq, lte } from "drizzle-orm";
import { Effect, Option } from "effect";
import { Hono } from "hono";
import { after } from "next/server";
import { z } from "zod";
import { readInstantCleanupReport } from "@/lib/desktop-instant-cleanup";
import { invalidateGoogleDriveStorageQuotaCache } from "@/lib/google-drive-storage-quota";
import { maybeStartLiveTranscription } from "@/lib/live-transcribe";
import { runPromise } from "@/lib/server";
import { trackServerEvent } from "@/lib/server-analytics";
import {
GOOGLE_DRIVE_UPLOAD_FEATURE,
hasDesktopFeature,
isFromDesktopSemver,
UPLOAD_PROGRESS_VERSION,
} from "@/utils/desktop";
import { stringOrNumberOptional } from "@/utils/zod";
import { withAuth } from "../../utils";
export const app = new Hono().use(withAuth);
type UserOrganizationSelection = {
id: Organisation.OrganisationId;
name: string;
createdAt: Date;
};
function mergeUserOrganizationSelections(
...rowSets: UserOrganizationSelection[][]
) {
const organizationsById = new Map<string, UserOrganizationSelection>();
for (const rows of rowSets) {
for (const row of rows) {
organizationsById.set(row.id, row);
}
}
return Array.from(organizationsById.values())
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
.map(({ createdAt, ...organization }) => organization);
}
app.get("/new-id", (c) => c.json({ id: nanoId() }));
app.get(
"/create",
zValidator(
"query",
z.object({
recordingMode: z
.union([
z.literal("hls"),
z.literal("desktopMP4"),
z.literal("desktopSegments"),
])
.optional(),
isScreenshot: z.coerce.boolean().default(false),
videoId: z.string().optional(),
createWithId: z.coerce.boolean().default(false),
name: z.string().optional(),
durationInSecs: stringOrNumberOptional,
width: stringOrNumberOptional,
height: stringOrNumberOptional,
fps: stringOrNumberOptional,
orgId: z
.string()
.optional()
.transform((v) =>
v ? Organisation.OrganisationId.make(v) : undefined,
),
}),
),
async (c) => {
try {
const {
recordingMode,
isScreenshot,
videoId,
createWithId,
name,
durationInSecs,
width,
height,
fps,
orgId,
} = c.req.valid("query");
const user = c.get("user");
if (
createWithId &&
(!videoId || !/^[0-9abcdefghjkmnpqrstvwxyz]{15}$/.test(videoId))
)
return c.json({ error: "invalid_video_id" }, { status: 400 });
const isCapPro = userIsPro(user);
if (!isCapPro && durationInSecs && durationInSecs > /* 5 min */ 5 * 60)
return c.json({ error: "upgrade_required" }, { status: 403 });
console.log("Video create request:", {
recordingMode,
isScreenshot,
videoId,
createWithId,
userId: user.id,
durationInSecs,
height,
width,
fps,
});
const date = new Date();
const formattedDate = `${date.getDate()} ${date.toLocaleString(
"default",
{ month: "long" },
)} ${date.getFullYear()}`;
if (videoId !== undefined) {
const [video] = await db()
.select()
.from(videos)
.where(eq(videos.id, Video.VideoId.make(videoId)));
if (video) {
if (video.ownerId !== user.id)
return c.json({ error: "forbidden" }, { status: 403 });
if (isScreenshot || video.isScreenshot) {
await db().transaction(async (tx) => {
if (isScreenshot && !video.isScreenshot) {
await tx
.update(videos)
.set({ isScreenshot: true })
.where(
and(eq(videos.id, video.id), eq(videos.ownerId, user.id)),
);
}
await tx
.delete(videoUploads)
.where(eq(videoUploads.videoId, video.id));
});
}
if (
video.source?.type === "desktopSegments" &&
!video.isScreenshot &&
!isScreenshot
) {
// Off the response path: this endpoint gates recording start on
// the desktop, so workflow dispatch must never delay it.
after(() =>
maybeStartLiveTranscription({
videoId: video.id,
ownerId: user.id,
orgId: video.orgId,
}),
);
}
return c.json({
id: video.id,
// All deprecated
user_id: user.id,
aws_region: "n/a",
aws_bucket: "n/a",
});
}
}
const [ownedOrganizations, memberOrganizations] = await Promise.all([
db()
.select({
id: organizations.id,
name: organizations.name,
createdAt: organizations.createdAt,
})
.from(organizations)
.where(eq(organizations.ownerId, user.id)),
db()
.select({
id: organizations.id,
name: organizations.name,
createdAt: organizations.createdAt,
})
.from(organizationMembers)
.innerJoin(
organizations,
eq(organizations.id, organizationMembers.organizationId),
)
.where(eq(organizationMembers.userId, user.id)),
]);
const userOrganizations = mergeUserOrganizationSelections(
ownedOrganizations,
memberOrganizations,
);
// Accounts can end up org-less (e.g. after declining a team invite or
// being removed from their last org); provision a personal org like
// signup does instead of failing every upload.
if (userOrganizations.length === 0) {
const organizationId = Organisation.OrganisationId.make(nanoId());
await db().transaction(async (tx) => {
await tx.insert(organizations).values({
id: organizationId,
ownerId: user.id,
name: "My Organization",
});
await tx.insert(organizationMembers).values({
id: nanoId(),
organizationId,
userId: user.id,
role: "owner",
});
await tx
.update(users)
.set({
activeOrganizationId: organizationId,
defaultOrgId: organizationId,
})
.where(eq(users.id, user.id));
});
userOrganizations.push({ id: organizationId, name: "My Organization" });
}
const userOrgIds = userOrganizations.map((org) => org.id);
let videoOrgId: Organisation.OrganisationId;
// Desktop persists orgId in settings and keeps sending it after the
// user leaves the org, so an unknown orgId falls back to the
// default/first org below instead of hard-failing every upload.
if (orgId && userOrgIds.includes(orgId)) {
videoOrgId = orgId;
} else if (user.defaultOrgId) {
// User's defaultOrgId is no longer valid, switch to first available org
if (!userOrgIds.includes(user.defaultOrgId)) {
if (!userOrganizations[0])
return c.json({ error: "no_valid_org" }, { status: 403 });
videoOrgId = userOrganizations[0].id;
// Update user's defaultOrgId to the new valid org
await db()
.update(users)
.set({
defaultOrgId: videoOrgId,
})
.where(eq(users.id, user.id));
} else videoOrgId = user.defaultOrgId;
} else {
// No orgId provided and no defaultOrgId, use first available org
if (!userOrganizations[0])
return c.json({ error: "no_valid_org" }, { status: 403 });
videoOrgId = userOrganizations[0].id;
}
const idToUse = Video.VideoId.make(
createWithId && videoId ? videoId : nanoId(),
);
const videoName =
name ??
`Cap ${isScreenshot ? "Screenshot" : "Recording"} - ${formattedDate}`;
const metadata: VideoMetadata | undefined = name
? { sourceName: name }
: undefined;
const clientSupportsGoogleDriveUpload = hasDesktopFeature(
c.req,
GOOGLE_DRIVE_UPLOAD_FEATURE,
);
const organizationWritable =
await Storage.getOrganizationWritableAccess(videoOrgId).pipe(
runPromise,
);
if (
!clientSupportsGoogleDriveUpload &&
Option.isSome(organizationWritable) &&
organizationWritable.value.access.provider === "googleDrive"
) {
return c.json(
{ error: "google_drive_upload_unsupported" },
{ status: 426 },
);
}
const writable = await (clientSupportsGoogleDriveUpload
? Storage.getWritableAccessForUser(user.id, videoOrgId)
: Storage.getS3WritableAccessForUser(user.id, videoOrgId)
).pipe(runPromise);
const clientSupportsUploadProgress = isFromDesktopSemver(
c.req,
UPLOAD_PROGRESS_VERSION,
);
await db().transaction(async (tx) => {
await tx.insert(videos).values({
id: idToUse,
name: videoName,
ownerId: user.id,
orgId: videoOrgId,
source:
recordingMode === "hls"
? { type: "local" as const }
: recordingMode === "desktopMP4"
? { type: "desktopMP4" as const }
: recordingMode === "desktopSegments"
? { type: "desktopSegments" as const }
: undefined,
isScreenshot,
bucket: Option.getOrNull(writable.bucketId),
storageIntegrationId: Option.getOrNull(writable.storageIntegrationId),
public: await getNewVideoPublic(videoOrgId),
duration: durationInSecs,
width,
height,
fps,
...(metadata ? { metadata } : {}),
});
if (clientSupportsUploadProgress && !isScreenshot)
await tx.insert(videoUploads).values({
videoId: idToUse,
mode: "singlepart",
});
});
if (recordingMode === "desktopSegments" && !isScreenshot) {
// Off the response path: this endpoint gates recording start on the
// desktop, so workflow dispatch must never delay it.
after(() =>
maybeStartLiveTranscription({
videoId: idToUse,
ownerId: user.id,
orgId: videoOrgId,
}),
);
}
try {
const videoCount = await db()
.select({ count: count() })
.from(videos)
.where(eq(videos.ownerId, user.id));
if (videoCount?.[0] && videoCount[0].count === 1 && user.email) {
console.log(
"[SendFirstShareableLinkEmail] Sending first shareable link email with 5-minute delay",
);
const videoUrl = `${serverEnv().WEB_URL}/s/${idToUse}`;
await sendEmail({
email: user.email,
subject: "You created your first Cap! 🥳",
react: FirstShareableLink({
email: user.email,
url: videoUrl,
videoName: videoName,
}),
marketing: true,
scheduledAt: "in 5 min",
});
console.log(
"[SendFirstShareableLinkEmail] First shareable link email scheduled to be sent in 5 minutes",
);
}
} catch (error) {
console.error(
"Error checking for first video or sending email:",
error,
);
}
return c.json({
id: idToUse,
// All deprecated
user_id: user.id,
aws_region: "n/a",
aws_bucket: "n/a",
});
} catch (error) {
console.error("Error in video create endpoint:", error);
return c.json({ error: "Internal server error" }, { status: 500 });
}
},
);
app.delete(
"/delete",
zValidator("query", z.object({ videoId: z.string() })),
async (c) => {
const videoId = Video.VideoId.make(c.req.valid("query").videoId);
const user = c.get("user");
try {
const [result] = await db()
.select({ video: videos })
.from(videos)
.where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)));
if (!result)
return c.json(
{ error: true, message: "Video not found" },
{ status: 404 },
);
const deleted = await Effect.gen(function* () {
const videoService = yield* Videos;
yield* videoService.delete(videoId);
return true;
}).pipe(
Effect.provide(makeCurrentUserLayer(user)),
Effect.catchTags({
VideoNotFoundError: () => Effect.succeed(false),
PolicyDenied: () => Effect.succeed(false),
}),
runPromise,
);
if (!deleted)
return c.json(
{ error: true, message: "Video not found" },
{ status: 404 },
);
await invalidateGoogleDriveStorageQuotaCache(
result.video.storageIntegrationId,
);
const cleanup = readInstantCleanupReport(
c.req.query("reason"),
c.req.query("cause"),
hasDesktopFeature(c.req, "gpui"),
);
if (cleanup)
trackServerEvent(user.id, "desktop_instant_cleanup", {
...cleanup,
sourceType: result.video.source?.type ?? null,
});
return c.json(true);
} catch (error) {
console.error("Error in video delete endpoint:", error);
return c.json({ error: "Internal server error" }, { status: 500 });
}
},
);
app.post(
"/progress",
zValidator(
"json",
z.object({
videoId: z.string(),
uploaded: z.number(),
total: z.number(),
// We get this from the client so we can avoid race conditions.
// Eg. If this value is older than the value in the DB, we ignore it.
updatedAt: z.string().pipe(z.coerce.date()),
}),
),
async (c) => {
const {
videoId: videoIdRaw,
uploaded: uploadedRaw,
total,
updatedAt,
} = c.req.valid("json");
const user = c.get("user");
const videoId = Video.VideoId.make(videoIdRaw);
// Prevent it maths breaking
const uploaded = Math.min(uploadedRaw, total);
try {
const [video] = await db()
.select({
id: videos.id,
storageIntegrationId: videos.storageIntegrationId,
upload: videoUploads,
})
.from(videos)
.where(and(eq(videos.id, videoId), eq(videos.ownerId, user.id)))
.leftJoin(videoUploads, eq(videos.id, videoUploads.videoId));
if (!video)
return c.json(
{ error: true, message: "Video not found" },
{ status: 404 },
);
if (video.upload) {
if (uploaded === total && video.upload.mode !== "multipart") {
await db()
.delete(videoUploads)
.where(eq(videoUploads.videoId, videoId));
} else {
await db()
.update(videoUploads)
.set({
uploaded,
total,
updatedAt,
})
.where(
and(
eq(videoUploads.videoId, videoId),
lte(videoUploads.updatedAt, updatedAt),
),
);
}
} else if (uploaded < total) {
await db().insert(videoUploads).values({
videoId,
uploaded,
total,
updatedAt,
});
}
if (uploaded === total) {
await invalidateGoogleDriveStorageQuotaCache(
video.storageIntegrationId,
);
}
return c.json(true);
} catch (error) {
console.error("Error in progress update endpoint:", error);
return c.json({ error: "Internal server error" }, { status: 500 });
}
},
);