Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
import { HttpApiSchema } from "@effect/platform";
import { Rpc, RpcGroup } from "@effect/rpc";
import { Context, Effect, Option, Schema } from "effect";
import { RpcAuthMiddleware } from "./Authentication.ts";
import { InternalError } from "./Errors.ts";
import { FolderId } from "./Folder.ts";
import { OrganisationId } from "./Organisation.ts";
import { PolicyDeniedError } from "./Policy.ts";
import { S3BucketId } from "./S3Bucket.ts";
import { StorageIntegrationId, UploadTarget } from "./Storage.ts";
import { UserId } from "./User.ts";
export const VideoId = Schema.String.pipe(Schema.brand("VideoId"));
export type VideoId = typeof VideoId.Type;
export const FREE_PLAN_MAX_RECORDING_SECONDS = 5 * 60;
export const FREE_PLAN_SHAREABLE_LINKS_PER_MONTH = 25;
// Quota is not retroactive: videos created before this date never count
// toward, nor get gated by, the monthly shareable-link limit.
export const SHAREABLE_LINK_LIMIT_ENFORCED_FROM = new Date(
"2026-08-19T00:00:00.000Z",
);
// Purposefully doesn't include password as this is a public class
export class Video extends Schema.Class<Video>("Video")({
id: VideoId,
ownerId: UserId,
orgId: OrganisationId,
name: Schema.String,
public: Schema.Boolean,
source: Schema.Struct({
outputKey: Schema.optional(Schema.String),
audioLevelOutputKey: Schema.optional(Schema.String),
audioLevelSourceKey: Schema.optional(Schema.String),
thumbnailKey: Schema.optional(Schema.String),
previewKey: Schema.optional(Schema.String),
type: Schema.Literal(
"MediaConvert",
"local",
"desktopMP4",
"desktopSegments",
"webMP4",
),
}),
metadata: Schema.OptionFromNullOr(
Schema.Record({ key: Schema.String, value: Schema.Any }),
),
bucketId: Schema.OptionFromNullOr(S3BucketId),
storageIntegrationId: Schema.OptionFromNullOr(StorageIntegrationId),
folderId: Schema.OptionFromNullOr(FolderId),
transcriptionStatus: Schema.OptionFromNullOr(
Schema.Literal("PROCESSING", "COMPLETE", "ERROR", "SKIPPED", "NO_AUDIO"),
),
width: Schema.OptionFromNullOr(Schema.Number),
height: Schema.OptionFromNullOr(Schema.Number),
duration: Schema.OptionFromNullOr(Schema.Number),
createdAt: Schema.Date,
updatedAt: Schema.Date,
}) {
static decodeSync = Schema.decodeSync(Video);
static getSource(self: Video) {
if (self.source.type === "MediaConvert")
return new M3U8Source({
videoId: self.id,
ownerId: self.ownerId,
subpath: "output/video_recording_000.m3u8",
});
if (self.source.type === "local")
return new M3U8Source({
videoId: self.id,
ownerId: self.ownerId,
subpath: "combined-source/stream.m3u8",
});
if (self.source.type === "desktopSegments")
return new SegmentsSource({ videoId: self.id, ownerId: self.ownerId });
if (self.source.type === "desktopMP4" || self.source.type === "webMP4")
return new Mp4Source({
videoId: self.id,
ownerId: self.ownerId,
outputKey: getAudioLevelOutputKey(self) ?? self.source.outputKey,
});
}
}
export const UploadPhase = Schema.Literal(
"uploading",
"processing",
"generating_thumbnail",
"complete",
"error",
);
export type UploadPhase = typeof UploadPhase.Type;
export class UploadProgress extends Schema.Class<UploadProgress>(
"UploadProgress",
)({
uploaded: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
total: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
startedAt: Schema.Date,
updatedAt: Schema.Date,
phase: UploadPhase,
processingProgress: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
processingMessage: Schema.OptionFromNullOr(Schema.String),
processingError: Schema.OptionFromNullOr(Schema.String),
hasRawFallback: Schema.Boolean,
automaticRetry: Schema.optional(Schema.Boolean),
}) {}
export const UploadProgressUpdateInput = Schema.Struct({
videoId: VideoId,
uploaded: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
total: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),
updatedAt: Schema.Date,
});
export const PresignedPost = Schema.Struct({
url: Schema.String,
fields: Schema.Record({ key: Schema.String, value: Schema.String }),
});
export const InstantRecordingCreateInput = Schema.Struct({
orgId: OrganisationId,
folderId: Schema.OptionFromUndefinedOr(FolderId),
durationSeconds: Schema.optional(Schema.Number),
resolution: Schema.optional(Schema.String),
width: Schema.optional(Schema.Number),
height: Schema.optional(Schema.Number),
videoCodec: Schema.optional(Schema.String),
audioCodec: Schema.optional(Schema.String),
supportsUploadProgress: Schema.optional(Schema.Boolean),
});
export const InstantRecordingCreateSuccess = Schema.Struct({
id: VideoId,
shareUrl: Schema.String,
upload: UploadTarget,
});
export class ImportSource extends Schema.Class<ImportSource>("ImportSource")({
source: Schema.Literal("loom"),
id: Schema.String,
}) {}
export function getRetainedRecordingOutputKey(
ownerId: string,
videoId: string,
key: string | undefined,
) {
if (
!key?.startsWith(`${ownerId}/${videoId}/.recording/`) ||
!key.endsWith(".mp4") ||
key.includes("..") ||
!/^[a-zA-Z0-9_./-]+$/.test(key)
) {
return undefined;
}
return key;
}
export function getAudioLevelOutputKey(video: {
id: string;
ownerId: string;
source: {
type: string;
outputKey?: string;
audioLevelSourceKey?: string;
audioLevelOutputKey?: string;
};
}) {
const { source } = video;
const originalKey =
getRetainedRecordingOutputKey(video.ownerId, video.id, source.outputKey) ??
(source.type === "webMP4"
? `${video.ownerId}/${video.id}/result.mp4`
: undefined);
const key = getRetainedRecordingOutputKey(
video.ownerId,
video.id,
source.audioLevelOutputKey,
);
if (
!["desktopMP4", "webMP4"].includes(source.type) ||
!originalKey ||
source.audioLevelSourceKey !== originalKey ||
!key?.startsWith(
`${video.ownerId}/${video.id}/.recording/outputs/audio-quality-v3/`,
)
)
return undefined;
return key;
}
export class Mp4Source extends Schema.TaggedClass<Mp4Source>()("Mp4Source", {
videoId: Schema.String,
ownerId: Schema.String,
outputKey: Schema.optional(Schema.String),
}) {
getFileKey() {
return (
getRetainedRecordingOutputKey(
this.ownerId,
this.videoId,
this.outputKey,
) ?? `${this.ownerId}/${this.videoId}/result.mp4`
);
}
}
export class M3U8Source extends Schema.TaggedClass<M3U8Source>()("M3U8Source", {
videoId: Schema.String,
ownerId: Schema.String,
subpath: Schema.String,
}) {
getPlaylistFileKey() {
return `${this.ownerId}/${this.videoId}/${this.subpath}`;
}
}
export class SegmentsSource extends Schema.TaggedClass<SegmentsSource>()(
"SegmentsSource",
{
videoId: Schema.String,
ownerId: Schema.String,
},
) {
getManifestKey() {
return `${this.ownerId}/${this.videoId}/segments/manifest.json`;
}
getVideoInitKey() {
return `${this.ownerId}/${this.videoId}/segments/video/init.mp4`;
}
getAudioInitKey() {
return `${this.ownerId}/${this.videoId}/segments/audio/init.mp4`;
}
getVideoSegmentKey(index: number) {
return `${this.ownerId}/${this.videoId}/segments/video/segment_${String(index).padStart(3, "0")}.m4s`;
}
getAudioSegmentKey(index: number) {
return `${this.ownerId}/${this.videoId}/segments/audio/segment_${String(index).padStart(3, "0")}.m4s`;
}
}
export const SegmentManifestEntry = Schema.Union(
Schema.Number,
Schema.Struct({
index: Schema.Number,
duration: Schema.Number,
}),
);
export const SegmentManifest = Schema.Struct({
version: Schema.Number,
video_init_uploaded: Schema.Boolean,
audio_init_uploaded: Schema.Boolean,
video_segments: Schema.Array(SegmentManifestEntry),
audio_segments: Schema.Array(SegmentManifestEntry),
is_complete: Schema.Boolean,
});
export type SegmentManifestType = Schema.Schema.Type<typeof SegmentManifest>;
export function normalizeSegmentEntry(
entry: Schema.Schema.Type<typeof SegmentManifestEntry>,
): { index: number; duration: number } {
return typeof entry === "number" ? { index: entry, duration: 3.0 } : entry;
}
/*
* Used to specify video passwords provided by a user,
* whether via cookies in the case of the website,
* or via query params for the API. Holds every hash the user has verified
* (the cookie remembers one per unlocked resource), so unlocking one share
* never invalidates another.
*/
export class VideoPasswordAttachment extends Context.Tag(
"VideoPasswordAttachment",
)<VideoPasswordAttachment, { passwords: ReadonlyArray<string> }>() {}
export class VerifyVideoPasswordError extends Schema.TaggedError<VerifyVideoPasswordError>()(
"VerifyVideoPasswordError",
{
id: VideoId,
cause: Schema.Literal("not-provided", "wrong-password"),
},
) {}
export const verifyPassword = (video: Video, password: Option.Option<string>) =>
verifyPasswordCandidates(
video,
Option.match(password, {
onNone: () => [],
onSome: (value) => [value],
}),
);
export const verifyPasswordCandidates = (
video: Pick<Video, "id">,
passwords: ReadonlyArray<string>,
) =>
Effect.gen(function* () {
const passwordAttachment = yield* Effect.serviceOption(
VideoPasswordAttachment,
);
if (passwords.length === 0) return;
const verified = Option.isSome(passwordAttachment)
? passwordAttachment.value.passwords
: [];
if (verified.length === 0)
return yield* new VerifyVideoPasswordError({
id: video.id,
cause: "not-provided",
});
if (!verified.some((hash) => passwords.includes(hash)))
return yield* new VerifyVideoPasswordError({
id: video.id,
cause: "wrong-password",
});
});
export class NotFoundError extends Schema.TaggedError<NotFoundError>()(
"VideoNotFoundError",
{},
HttpApiSchema.annotations({ status: 404 }),
) {}
export class VideoRpcs extends RpcGroup.make(
Rpc.make("VideoDelete", {
payload: VideoId,
error: Schema.Union(NotFoundError, InternalError, PolicyDeniedError),
}).middleware(RpcAuthMiddleware),
Rpc.make("VideoDuplicate", {
payload: VideoId,
error: Schema.Union(NotFoundError, InternalError, PolicyDeniedError),
}).middleware(RpcAuthMiddleware),
Rpc.make("GetUploadProgress", {
payload: VideoId,
success: Schema.Option(UploadProgress),
error: Schema.Union(
NotFoundError,
InternalError,
PolicyDeniedError,
VerifyVideoPasswordError,
),
}),
Rpc.make("VideoInstantCreate", {
payload: InstantRecordingCreateInput,
success: InstantRecordingCreateSuccess,
error: Schema.Union(InternalError, PolicyDeniedError),
}).middleware(RpcAuthMiddleware),
Rpc.make("VideoUploadProgressUpdate", {
payload: UploadProgressUpdateInput,
success: Schema.Boolean,
error: Schema.Union(NotFoundError, InternalError, PolicyDeniedError),
}).middleware(RpcAuthMiddleware),
Rpc.make("VideoGetDownloadInfo", {
payload: VideoId,
success: Schema.Option(
Schema.Struct({ fileName: Schema.String, downloadUrl: Schema.String }),
),
error: Schema.Union(
NotFoundError,
InternalError,
PolicyDeniedError,
VerifyVideoPasswordError,
),
}),
Rpc.make("VideosGetThumbnails", {
payload: Schema.Array(VideoId).pipe(
Schema.filter((a) => a.length <= 50 || "Maximum of 50 videos at a time"),
),
success: Schema.Array(
Schema.Exit({
success: Schema.Option(Schema.String),
failure: Schema.Union(
NotFoundError,
PolicyDeniedError,
VerifyVideoPasswordError,
),
defect: Schema.Unknown,
}),
),
error: InternalError,
}),
Rpc.make("VideosGetAnalytics", {
payload: Schema.Array(VideoId).pipe(
Schema.filter((a) => a.length <= 50 || "Maximum of 50 videos at a time"),
),
success: Schema.Array(
Schema.Exit({
success: Schema.Struct({ count: Schema.Int }),
failure: Schema.Union(
NotFoundError,
PolicyDeniedError,
VerifyVideoPasswordError,
),
defect: Schema.Unknown,
}),
),
error: InternalError,
}),
) {}