Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): teach web recorder uploads about Drive targets

Richie McIlroy9983a6b9adc4
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/instant-mp4-uploader.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/instant-mp4-uploader.ts
index b9c931c6c..a25aeeedb 100644
--- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/instant-mp4-uploader.ts
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/instant-mp4-uploader.ts
@@ -6,6 +6,7 @@ const MAX_PART_UPLOAD_ATTEMPTS = 3;
const MAX_PARALLEL_PART_UPLOADS = 3;
const MAX_PENDING_UPLOAD_BYTES = 128 * 1024 * 1024;
const FINAL_BLOB_PART_SIZE_BYTES = 16 * 1024 * 1024;
+const DRIVE_PART_SIZE_BYTES = 16 * 1024 * 1024;
const PART_UPLOAD_STALL_TIMEOUT_MS = 30_000;
const PART_UPLOAD_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
@@ -95,20 +96,23 @@ export const initiateMultipartUpload = async ({
contentType: string;
subpath: string;
}) => {
- const result = await postJson<{ uploadId: string }>(
- "/api/upload/multipart/initiate",
- {
- videoId,
- contentType: normalizeMultipartContentType(contentType),
- subpath,
- },
- );
+ const result = await postJson<{
+ uploadId: string;
+ provider?: "s3" | "googleDrive";
+ }>("/api/upload/multipart/initiate", {
+ videoId,
+ contentType: normalizeMultipartContentType(contentType),
+ subpath,
+ });
if (!result.uploadId) {
throw new Error("Multipart initiate response missing uploadId");
}
- return result.uploadId;
+ return {
+ uploadId: result.uploadId,
+ provider: result.provider ?? "s3",
+ };
};
const presignMultipartPart = async (
@@ -116,17 +120,25 @@ const presignMultipartPart = async (
uploadId: string,
partNumber: number,
subpath: string,
-): Promise<string> => {
- const result = await postJson<{ presignedUrl: string }>(
- "/api/upload/multipart/presign-part",
- { videoId, uploadId, partNumber, subpath },
- );
+): Promise<{ url: string; provider: "s3" | "googleDrive" }> => {
+ const result = await postJson<{
+ presignedUrl: string;
+ provider?: "s3" | "googleDrive";
+ }>("/api/upload/multipart/presign-part", {
+ videoId,
+ uploadId,
+ partNumber,
+ subpath,
+ });
if (!result.presignedUrl) {
throw new Error(`Missing presigned URL for part ${partNumber}`);
}
- return result.presignedUrl;
+ return {
+ url: result.presignedUrl,
+ provider: result.provider ?? "s3",
+ };
};
const completeMultipartUpload = async (
@@ -181,6 +193,7 @@ interface FinalizeOptions extends MultipartCompletePayload {
export class InstantRecordingUploader {
private readonly videoId: VideoId;
private readonly uploadId: string;
+ private readonly provider: "s3" | "googleDrive";
private readonly mimeType: string;
private readonly subpath: string;
private readonly setUploadStatus: SetUploadStatus;
@@ -195,7 +208,7 @@ export class InstantRecordingUploader {
private uploadedBytes = 0;
private pendingUploadBytes = 0;
private readonly pendingUploadTasks = new Set<Promise<void>>();
- private availableUploadSlots = MAX_PARALLEL_PART_UPLOADS;
+ private availableUploadSlots: number;
private readonly uploadSlotWaiters: Array<() => void> = [];
private readonly parts: UploadedPartPayload[] = [];
private nextPartNumber = 1;
@@ -211,10 +224,13 @@ export class InstantRecordingUploader {
>();
private readonly stallTimeouts = new Set<number>();
private processingStarted = true;
+ private queuedBytes = 0;
+ private readonly partOffsets = new Map<number, number>();
constructor(options: {
videoId: VideoId;
uploadId: string;
+ provider?: "s3" | "googleDrive";
mimeType: string;
subpath: string;
setUploadStatus: SetUploadStatus;
@@ -225,6 +241,7 @@ export class InstantRecordingUploader {
}) {
this.videoId = options.videoId;
this.uploadId = options.uploadId;
+ this.provider = options.provider ?? "s3";
this.mimeType = options.mimeType;
this.subpath = options.subpath;
this.setUploadStatus = options.setUploadStatus;
@@ -232,6 +249,8 @@ export class InstantRecordingUploader {
this.onChunkStateChange = options.onChunkStateChange;
this.onOverflow = options.onOverflow;
this.onFatalError = options.onFatalError;
+ this.availableUploadSlots =
+ this.provider === "googleDrive" ? 1 : MAX_PARALLEL_PART_UPLOADS;
}
private markFatalError(error: Error) {
@@ -340,6 +359,11 @@ export class InstantRecordingUploader {
}
private flushBuffer(force = false) {
+ if (this.provider === "googleDrive") {
+ this.flushDriveBuffer(force);
+ return;
+ }
+
if (this.bufferedBytes === 0) return;
if (!force && this.bufferedBytes < MIN_PART_SIZE_BYTES) return;
@@ -350,6 +374,59 @@ export class InstantRecordingUploader {
this.enqueueUpload(chunk);
}
+ private flushDriveBuffer(force = false) {
+ while (this.bufferedBytes > 0) {
+ if (!force && this.bufferedBytes < DRIVE_PART_SIZE_BYTES) return;
+
+ const partSize =
+ force && this.bufferedBytes <= DRIVE_PART_SIZE_BYTES
+ ? this.bufferedBytes
+ : DRIVE_PART_SIZE_BYTES;
+ const { part, remainingChunks, remainingBytes } =
+ this.takeBufferedPart(partSize);
+
+ this.bufferedChunks = remainingChunks;
+ this.bufferedBytes = remainingBytes;
+ this.enqueueUpload(part);
+
+ if (partSize < DRIVE_PART_SIZE_BYTES) return;
+ }
+ }
+
+ private takeBufferedPart(size: number) {
+ const partChunks: Blob[] = [];
+ const remainingChunks: Blob[] = [];
+ let remainingPartBytes = size;
+ let consumedBuffer = true;
+
+ for (const chunk of this.bufferedChunks) {
+ if (!consumedBuffer) {
+ remainingChunks.push(chunk);
+ continue;
+ }
+
+ if (chunk.size <= remainingPartBytes) {
+ partChunks.push(chunk);
+ remainingPartBytes -= chunk.size;
+ if (remainingPartBytes === 0) consumedBuffer = false;
+ continue;
+ }
+
+ partChunks.push(chunk.slice(0, remainingPartBytes, this.mimeType));
+ remainingChunks.push(
+ chunk.slice(remainingPartBytes, chunk.size, this.mimeType),
+ );
+ consumedBuffer = false;
+ remainingPartBytes = 0;
+ }
+
+ return {
+ part: new Blob(partChunks, { type: this.mimeType }),
+ remainingChunks,
+ remainingBytes: this.bufferedBytes - size,
+ };
+ }
+
private createFinalBlobPart(finalBlob: Blob, start: number, end: number) {
return finalBlob.slice(start, end, this.mimeType);
}
@@ -364,6 +441,8 @@ export class InstantRecordingUploader {
}
const partNumber = this.nextPartNumber++;
+ this.partOffsets.set(partNumber, this.queuedBytes);
+ this.queuedBytes += part.size;
this.pendingUploadBytes += part.size;
this.registerChunk(partNumber, part.size);
const uploadTask = this.runPartUpload(partNumber, part);
@@ -432,7 +511,7 @@ export class InstantRecordingUploader {
}
this.availableUploadSlots = Math.min(
- MAX_PARALLEL_PART_UPLOADS,
+ this.provider === "googleDrive" ? 1 : MAX_PARALLEL_PART_UPLOADS,
this.availableUploadSlots + 1,
);
}
@@ -541,7 +620,7 @@ export class InstantRecordingUploader {
}
private async uploadPart(partNumber: number, part: Blob) {
- const presignedUrl = await presignMultipartPart(
+ const upload = await presignMultipartPart(
this.videoId,
this.uploadId,
partNumber,
@@ -549,7 +628,8 @@ export class InstantRecordingUploader {
);
const etag = await this.uploadBlobWithProgress({
- url: presignedUrl,
+ url: upload.url,
+ provider: upload.provider,
partNumber,
part,
});
@@ -562,10 +642,12 @@ export class InstantRecordingUploader {
private uploadBlobWithProgress({
url,
+ provider,
partNumber,
part,
}: {
url: string;
+ provider: "s3" | "googleDrive";
partNumber: number;
part: Blob;
}): Promise<string> {
@@ -579,6 +661,16 @@ export class InstantRecordingUploader {
xhr.open("PUT", url);
xhr.responseType = "text";
xhr.timeout = PART_UPLOAD_REQUEST_TIMEOUT_MS;
+ if (provider === "googleDrive") {
+ const start = this.partOffsets.get(partNumber) ?? 0;
+ const end = start + part.size - 1;
+ const total =
+ this.finalTotalBytes !== null && end + 1 >= this.finalTotalBytes
+ ? this.finalTotalBytes.toString()
+ : "*";
+ xhr.setRequestHeader("Content-Range", `bytes ${start}-${end}/${total}`);
+ xhr.setRequestHeader("Content-Type", this.mimeType);
+ }
this.activeRequests.set(partNumber, xhr);
this.updateChunkState(partNumber, {
@@ -628,9 +720,14 @@ export class InstantRecordingUploader {
xhr.onload = () => {
clearStallTimeout();
clearRequest();
- if (xhr.status >= 200 && xhr.status < 300) {
+ if (
+ (xhr.status >= 200 && xhr.status < 300) ||
+ (provider === "googleDrive" && xhr.status === 308)
+ ) {
const etagHeader = xhr.getResponseHeader("ETag");
- const etag = etagHeader?.replace(/"/g, "");
+ const etag =
+ etagHeader?.replace(/"/g, "") ||
+ (provider === "googleDrive" ? `drive-${partNumber}` : "");
if (!etag) {
this.updateChunkState(partNumber, { status: "error" });
reject(new Error(`Missing ETag for part ${partNumber}`));
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-upload.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-upload.ts
index f449cccea..e7cafe194 100644
--- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-upload.ts
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-upload.ts
@@ -1,10 +1,11 @@
+import { uploadWithTarget } from "@/utils/upload-target";
import type { UploadStatus } from "../../UploadingContext";
import { sendProgressUpdate } from "../sendProgressUpdate";
-import type { PresignedPost, VideoId } from "./web-recorder-types";
+import type { UploadTarget, VideoId } from "./web-recorder-types";
export const uploadRecording = (
blob: Blob,
- upload: PresignedPost,
+ upload: UploadTarget,
currentVideoId: VideoId,
thumbnailPreviewUrl: string | undefined,
setUploadStatus: (status: UploadStatus | undefined) => void,
@@ -20,48 +21,25 @@ export const uploadRecording = (
? blob
: new File([blob], "result.mp4", { type: "video/mp4" });
- const formData = new FormData();
- Object.entries(upload.fields).forEach(([key, value]) => {
- formData.append(key, value);
- });
- formData.append("file", fileBlob, "result.mp4");
-
- const xhr = new XMLHttpRequest();
- xhr.open("POST", upload.url);
-
- xhr.upload.onprogress = (event) => {
- if (event.lengthComputable) {
- const percent = (event.loaded / event.total) * 100;
+ uploadWithTarget({
+ target: upload,
+ body: fileBlob,
+ fileName: "result.mp4",
+ onProgress: ({ loaded, total }) => {
+ const percent = (loaded / total) * 100;
setUploadStatus({
status: "uploadingVideo",
capId: currentVideoId,
progress: percent,
thumbnailUrl: thumbnailPreviewUrl,
});
- sendProgressUpdate(currentVideoId, event.loaded, event.total);
- }
- };
-
- xhr.onload = async () => {
- if (xhr.status >= 200 && xhr.status < 300) {
+ void sendProgressUpdate(currentVideoId, loaded, total);
+ },
+ }).then(
+ async () => {
await sendProgressUpdate(currentVideoId, blob.size, blob.size);
resolve();
- } else {
- const errorText = xhr.responseText || xhr.statusText || "Unknown error";
- console.error("Upload failed:", {
- status: xhr.status,
- statusText: xhr.statusText,
- responseText: errorText,
- });
- reject(
- new Error(`Upload failed with status ${xhr.status}: ${errorText}`),
- );
- }
- };
-
- xhr.onerror = () => {
- reject(new Error("Upload failed due to network error"));
- };
-
- xhr.send(formData);
+ },
+ (error) => reject(error),
+ );
});
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts
index 01d05d7f7..2016cc8d0 100644
--- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts
@@ -9,6 +9,7 @@ import { toast } from "sonner";
import { createVideoAndGetUploadUrl } from "@/actions/video/upload";
import { useEffectMutation, useRpcClient } from "@/lib/EffectRuntime";
import { ThumbnailRequest } from "@/lib/Requests/ThumbnailRequest";
+import { uploadWithTarget } from "@/utils/upload-target";
import { useUploadingContext } from "../../UploadingContext";
import { sendProgressUpdate } from "../sendProgressUpdate";
import {
@@ -44,10 +45,10 @@ import {
} from "./web-recorder-constants";
import type {
ChunkUploadState,
- PresignedPost,
RecorderPhase,
RecordingFailureDownload,
RecoveredRecordingDownload,
+ UploadTarget,
VideoId,
} from "./web-recorder-types";
import {
@@ -81,7 +82,7 @@ type InstantChunkingMode = "manual" | "timeslice";
type InstantVideoCreation = {
id: VideoId;
shareUrl: string;
- upload: PresignedPost;
+ upload: UploadTarget;
};
const unwrapExitOrThrow = <T, E>(exit: Exit.Exit<T, E>) => {
@@ -236,7 +237,7 @@ export const useWebRecorder = ({
const videoCreationRef = useRef<{
id: VideoId;
shareUrl: string;
- upload: PresignedPost;
+ upload: UploadTarget;
} | null>(null);
const pendingInstantVideoIdRef = useRef<VideoId | null>(null);
const dataRequestIntervalRef = useRef<number | null>(null);
@@ -999,14 +1000,15 @@ export const useWebRecorder = ({
pendingInstantVideoIdRef.current = creation.id;
const rawSubpath = `raw-upload.${pipeline.fileExtension}`;
- const uploadId = await initiateMultipartUpload({
+ const uploadSession = await initiateMultipartUpload({
videoId: creationResult.id,
contentType: pipeline.mimeType,
subpath: rawSubpath,
});
instantUploaderRef.current = new InstantRecordingUploader({
videoId: creationResult.id,
- uploadId,
+ uploadId: uploadSession.uploadId,
+ provider: uploadSession.provider,
mimeType: pipeline.mimeType,
subpath: rawSubpath,
setUploadStatus,
@@ -1220,14 +1222,15 @@ export const useWebRecorder = ({
const rawSubpath = `raw-upload.${pipeline.fileExtension}`;
if (!uploader) {
- const uploadId = await initiateMultipartUpload({
+ const uploadSession = await initiateMultipartUpload({
videoId: creationResult.id,
contentType: pipeline.mimeType,
subpath: rawSubpath,
});
uploader = new InstantRecordingUploader({
videoId: creationResult.id,
- uploadId,
+ uploadId: uploadSession.uploadId,
+ provider: uploadSession.provider,
mimeType: pipeline.mimeType,
subpath: rawSubpath,
setUploadStatus,
@@ -1303,56 +1306,24 @@ export const useWebRecorder = ({
orgId: Organisation.OrganisationId.make(orgId),
});
- const screenshotFormData = new FormData();
- Object.entries(screenshotData.presignedPostData.fields).forEach(
- ([key, value]) => {
- screenshotFormData.append(key, value as string);
- },
- );
- screenshotFormData.append(
- "file",
- thumbnailBlob,
- "screen-capture.jpg",
- );
-
setUploadStatus({
status: "uploadingThumbnail",
capId: creationResult.id,
progress: 90,
});
- await new Promise<void>((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- xhr.open("POST", screenshotData.presignedPostData.url);
-
- xhr.upload.onprogress = (event) => {
- if (event.lengthComputable) {
- const percent = 90 + (event.loaded / event.total) * 10;
- setUploadStatus({
- status: "uploadingThumbnail",
- capId: creationResult.id,
- progress: percent,
- });
- }
- };
-
- xhr.onload = () => {
- if (xhr.status >= 200 && xhr.status < 300) {
- resolve();
- } else {
- reject(
- new Error(
- `Screenshot upload failed with status ${xhr.status}`,
- ),
- );
- }
- };
-
- xhr.onerror = () => {
- reject(new Error("Screenshot upload failed"));
- };
-
- xhr.send(screenshotFormData);
+ await uploadWithTarget({
+ target: screenshotData.uploadTarget,
+ body: thumbnailBlob,
+ fileName: "screen-capture.jpg",
+ onProgress: ({ loaded, total }) => {
+ const percent = 90 + (loaded / total) * 10;
+ setUploadStatus({
+ status: "uploadingThumbnail",
+ capId: creationResult.id,
+ progress: percent,
+ });
+ },
});
queryClient.refetchQueries({
diff --git a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/web-recorder-types.ts b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/web-recorder-types.ts
index 078bc5a23..6a1368c82 100644
--- a/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/web-recorder-types.ts
+++ b/apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/web-recorder-types.ts
@@ -11,14 +11,16 @@ export type RecorderPhase =
export type RecorderErrorEvent = Event & { error?: DOMException };
type VideoNamespace = typeof import("@cap/web-domain").Video;
+type StorageNamespace = typeof import("@cap/web-domain").Storage;
export type PresignedPost = VideoNamespace["PresignedPost"]["Type"];
+export type UploadTarget = StorageNamespace["UploadTarget"]["Type"];
export type VideoId = VideoNamespace["VideoId"]["Type"];
export type ChunkUploadState = {
partNumber: number;
sizeBytes: number;
uploadedBytes: number;
- progress: number; // 0-1 ratio for the chunk itself
+ progress: number;
status: "queued" | "uploading" | "complete" | "error";
};