Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: use Cap titles for Google Drive files

Richie McIlroy65c784ed3782
diff --git a/apps/web/__tests__/unit/google-drive-storage.test.ts b/apps/web/__tests__/unit/google-drive-storage.test.ts
new file mode 100644
index 000000000..6f2abd908
--- /dev/null
+++ b/apps/web/__tests__/unit/google-drive-storage.test.ts
@@ -0,0 +1,1022 @@
+import { Storage, User, Video } from "@cap/web-domain";
+import { Effect, Layer, Option } from "effect";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({
+ GOOGLE_CLIENT_ID: "client-id",
+ GOOGLE_CLIENT_SECRET: "client-secret",
+ WEB_URL: "https://cap.test",
+ }),
+}));
+
+import { S3Buckets } from "../../../../packages/web-backend/src/S3Buckets";
+import { Storage as StorageService } from "../../../../packages/web-backend/src/Storage";
+import {
+ copyGoogleDriveFile,
+ createGoogleDriveResumableUpload,
+ GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ type GoogleDriveTokenStore,
+ syncGoogleDriveVideoNames,
+} from "../../../../packages/web-backend/src/Storage/GoogleDrive";
+import { getGoogleDriveVideoNames } from "../../../../packages/web-backend/src/Storage/google-drive-names";
+import {
+ type GoogleDriveIntegrationConfig,
+ type StorageObjectInput,
+ StorageRepo,
+} from "../../../../packages/web-backend/src/Storage/StorageRepo";
+
+const integrationId = Storage.StorageIntegrationId.make("integration-1");
+const otherIntegrationId = Storage.StorageIntegrationId.make("integration-2");
+const integrationOwnerId = User.UserId.make("integration-owner");
+const videoOwnerId = User.UserId.make("video-owner");
+const videoId = Video.VideoId.make("video-1");
+const resultKey = `${videoOwnerId}/${videoId}/result.mp4`;
+
+type StoredObject = {
+ id: Storage.StorageObjectId;
+ integrationId: Storage.StorageIntegrationId;
+ ownerId: User.UserId;
+ videoId: Video.VideoId | null;
+ objectKey: string;
+ objectKeyHash: string;
+ providerObjectId: string;
+ uploadSessionUrl: string | null;
+ uploadStatus: "pending" | "complete" | "error";
+ contentType: string | null;
+ contentLength: number | null;
+ metadata: Storage.StorageObjectMetadata | null;
+ createdAt: Date;
+ updatedAt: Date;
+};
+
+type VideoForNameSync = {
+ id: Video.VideoId;
+ name: string;
+ ownerId: User.UserId;
+ storageIntegrationId: Storage.StorageIntegrationId | null;
+};
+
+type RepoHarness = {
+ repo: StorageRepo;
+ objects: Map<string, StoredObject>;
+ reservations: StorageObjectInput[];
+ upserts: StorageObjectInput[];
+ fileNameUpdates: Array<{ object: StoredObject; fileName: string }>;
+ putObject: (input: StorageObjectInput) => StoredObject;
+ setVideo: (video: VideoForNameSync) => void;
+ setFileNameUpdateResult: (
+ result: (object: StoredObject, fileName: string) => boolean,
+ ) => void;
+};
+
+const objectMapKey = (
+ storageIntegrationId: Storage.StorageIntegrationId,
+ key: string,
+) => `${storageIntegrationId}:${key}`;
+
+const makeRepoHarness = (videos: VideoForNameSync[] = []): RepoHarness => {
+ const objects = new Map<string, StoredObject>();
+ const reservations: StorageObjectInput[] = [];
+ const upserts: StorageObjectInput[] = [];
+ const fileNameUpdates: Array<{ object: StoredObject; fileName: string }> = [];
+ const videoMap = new Map(videos.map((video) => [video.id, video]));
+ let objectSequence = 0;
+ let fileNameUpdateResult: (
+ object: StoredObject,
+ fileName: string,
+ ) => boolean = () => true;
+
+ const putObject = (input: StorageObjectInput) => {
+ const key = objectMapKey(input.integrationId, input.objectKey);
+ const existing = objects.get(key);
+ const next: StoredObject = {
+ id:
+ existing?.id ??
+ Storage.StorageObjectId.make(`storage-object-${++objectSequence}`),
+ integrationId: input.integrationId,
+ ownerId: existing?.ownerId ?? input.ownerId,
+ videoId: existing?.videoId ?? input.videoId,
+ objectKey: input.objectKey,
+ objectKeyHash: existing?.objectKeyHash ?? `hash:${input.objectKey}`,
+ providerObjectId: input.providerObjectId,
+ uploadSessionUrl: input.uploadSessionUrl ?? null,
+ uploadStatus: input.uploadStatus ?? "pending",
+ contentType: input.contentType ?? null,
+ contentLength: input.contentLength ?? null,
+ metadata:
+ existing && input.preserveMetadata
+ ? existing.metadata
+ : (input.metadata ?? null),
+ createdAt: existing?.createdAt ?? new Date("2026-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),
+ };
+ objects.set(key, next);
+ return next;
+ };
+
+ const repo = {
+ getIntegrationById: (id: Storage.StorageIntegrationId) =>
+ Effect.succeed(
+ id === integrationId
+ ? Option.some({ id, ownerId: integrationOwnerId })
+ : Option.none(),
+ ),
+ getGoogleDriveConfig: () => Effect.succeed(makeConfig()),
+ getGoogleDriveAccessTokenCache: () =>
+ Effect.succeed(
+ Option.some({
+ accessToken: "access-token",
+ expiresAt: new Date("2100-01-01T00:00:00.000Z"),
+ }),
+ ),
+ getGoogleDriveAccessTokenCacheById: () =>
+ Effect.succeed(
+ Option.some({
+ accessToken: "access-token",
+ expiresAt: new Date("2100-01-01T00:00:00.000Z"),
+ }),
+ ),
+ claimGoogleDriveTokenRefreshLease: () => Effect.succeed(true),
+ saveGoogleDriveAccessTokenCache: () => Effect.succeed(true),
+ releaseGoogleDriveTokenRefreshLease: () => Effect.void,
+ getObjectByKey: (
+ storageIntegrationId: Storage.StorageIntegrationId,
+ key: string,
+ ) =>
+ Effect.succeed(
+ Option.fromNullable(
+ objects.get(objectMapKey(storageIntegrationId, key)),
+ ),
+ ),
+ getVideoForNameSync: (id: Video.VideoId) =>
+ Effect.succeed(Option.fromNullable(videoMap.get(id))),
+ reserveObject: (input: StorageObjectInput) =>
+ Effect.sync(() => {
+ reservations.push(input);
+ const key = objectMapKey(input.integrationId, input.objectKey);
+ return objects.get(key) ?? putObject(input);
+ }),
+ upsertObject: (input: StorageObjectInput) =>
+ Effect.sync(() => {
+ upserts.push(input);
+ putObject(input);
+ }),
+ markObjectComplete: (
+ storageIntegrationId: Storage.StorageIntegrationId,
+ key: string,
+ contentLength?: number | null,
+ ) =>
+ Effect.sync(() => {
+ const object = objects.get(objectMapKey(storageIntegrationId, key));
+ if (!object) return;
+ object.uploadStatus = "complete";
+ if (contentLength !== undefined) object.contentLength = contentLength;
+ }),
+ deleteObjectByKey: (
+ storageIntegrationId: Storage.StorageIntegrationId,
+ key: string,
+ ) =>
+ Effect.sync(() => {
+ objects.delete(objectMapKey(storageIntegrationId, key));
+ }),
+ updateObjectFileName: (object: StoredObject, fileName: string) =>
+ Effect.sync(() => {
+ fileNameUpdates.push({ object, fileName });
+ const current = objects.get(
+ objectMapKey(object.integrationId, object.objectKey),
+ );
+ if (current) {
+ current.metadata = { ...(current.metadata ?? {}), fileName };
+ }
+ return fileNameUpdateResult(object, fileName);
+ }),
+ } as unknown as StorageRepo;
+
+ return {
+ repo,
+ objects,
+ reservations,
+ upserts,
+ fileNameUpdates,
+ putObject,
+ setVideo: (video) => {
+ videoMap.set(video.id, video);
+ },
+ setFileNameUpdateResult: (result) => {
+ fileNameUpdateResult = result;
+ },
+ };
+};
+
+let tokenSequence = 0;
+
+const makeTokenStore = (): GoogleDriveTokenStore => {
+ const token = {
+ accessToken: "access-token",
+ expiresAt: new Date("2100-01-01T00:00:00.000Z"),
+ };
+ return {
+ cacheKey: `google-drive-test-${++tokenSequence}`,
+ getInitialAccessTokenCache: () => Effect.succeed(Option.some(token)),
+ getAccessTokenCache: () => Effect.succeed(Option.some(token)),
+ claimRefreshLease: () => Effect.succeed(true),
+ saveAccessTokenCache: () => Effect.succeed(true),
+ releaseRefreshLease: () => Effect.void,
+ };
+};
+
+const makeConfig = (
+ folderLayout: GoogleDriveIntegrationConfig["folderLayout"] = "video",
+): GoogleDriveIntegrationConfig => ({
+ refreshToken: "refresh-token",
+ folderId: "root-folder",
+ folderLayout,
+});
+
+const jsonResponse = (body: unknown, init: ResponseInit = {}): Response =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ ...init,
+ });
+
+const response = (status: number, headers?: HeadersInit) =>
+ new Response(status === 204 ? null : "", { status, headers });
+
+const requestBody = (init?: RequestInit) =>
+ typeof init?.body === "string" && init.body.startsWith("{")
+ ? (JSON.parse(init.body) as Record<string, unknown>)
+ : null;
+
+const storedObjectInput = (
+ key: string,
+ providerObjectId: string,
+ options: {
+ status?: StoredObject["uploadStatus"];
+ contentType?: string;
+ contentLength?: number | null;
+ fileName?: string;
+ ownerId?: User.UserId;
+ uploadSessionUrl?: string | null;
+ } = {},
+): StorageObjectInput => ({
+ integrationId,
+ ownerId: options.ownerId ?? integrationOwnerId,
+ videoId,
+ objectKey: key,
+ providerObjectId,
+ uploadSessionUrl: options.uploadSessionUrl,
+ uploadStatus: options.status ?? "complete",
+ contentType: options.contentType ?? "video/mp4",
+ contentLength: options.contentLength,
+ metadata: {
+ videoId,
+ fileName: options.fileName ?? key.split("/").at(-1),
+ contentType: options.contentType ?? "video/mp4",
+ },
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("Google Drive video names", () => {
+ it("preserves exact valid titles and rejects blank or control-character names", () => {
+ expect(getGoogleDriveVideoNames("Launch 🚀: Q3/Q4? (final)")).toEqual({
+ folderName: "Launch 🚀: Q3/Q4? (final)",
+ fileName: "Launch 🚀: Q3/Q4? (final).mp4",
+ });
+ expect(getGoogleDriveVideoNames("Already.MP4")).toEqual({
+ folderName: "Already.MP4",
+ fileName: "Already.MP4",
+ });
+ expect(getGoogleDriveVideoNames("Same title")).toEqual(
+ getGoogleDriveVideoNames("Same title"),
+ );
+ expect(getGoogleDriveVideoNames(" \t ")).toBeNull();
+ expect(getGoogleDriveVideoNames("Visible\u0085control")).toBeNull();
+ });
+
+ it.each(["video", "userVideo"] as const)(
+ "creates %s-layout folders and final MP4 names from an explicit pre-insert title",
+ async (folderLayout) => {
+ const harness = makeRepoHarness();
+ const generatedIds = [
+ "result-id",
+ "owner-folder-id",
+ "video-folder-id",
+ "warning-id",
+ ];
+ const folderBodies: Record<string, unknown>[] = [];
+ let filePostSawReservation = false;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.includes("/files/generateIds")) {
+ return jsonResponse({ ids: [generatedIds.shift()] });
+ }
+ if (
+ url.includes("/drive/v3/files?") &&
+ !url.includes("uploadType=") &&
+ init?.method === "POST"
+ ) {
+ const body = requestBody(init);
+ if (body) folderBodies.push(body);
+ return jsonResponse({ id: body?.id, name: body?.name });
+ }
+ if (url.includes("uploadType=multipart")) {
+ return jsonResponse({ id: "warning-id" });
+ }
+ if (url.includes("uploadType=resumable") && init?.method === "POST") {
+ filePostSawReservation = harness.objects.has(
+ objectMapKey(integrationId, resultKey),
+ );
+ return response(200, { Location: "https://upload.test/session" });
+ }
+ throw new Error(
+ `Unexpected Drive request: ${init?.method ?? "GET"} ${url}`,
+ );
+ }),
+ );
+
+ await Effect.runPromise(
+ createGoogleDriveResumableUpload(
+ harness.repo,
+ makeConfig(folderLayout),
+ {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key: resultKey,
+ contentType: "video/mp4",
+ videoTitle: "Café / roadmap 🚀",
+ },
+ makeTokenStore(),
+ ),
+ );
+
+ const folderNames = folderBodies
+ .filter((body) => body.mimeType === GOOGLE_DRIVE_FOLDER_MIME_TYPE)
+ .map((body) => body.name);
+ expect(folderNames).toContain("Café / roadmap 🚀");
+ if (folderLayout === "userVideo")
+ expect(folderNames).toContain(videoOwnerId);
+ expect(filePostSawReservation).toBe(true);
+ const filePost = (
+ vi.mocked(fetch).mock.calls as Array<[string, RequestInit]>
+ ).find(
+ ([url, init]) =>
+ String(url).includes("uploadType=resumable") &&
+ init.method === "POST",
+ );
+ expect(requestBody(filePost?.[1])).toMatchObject({
+ id: "result-id",
+ name: "Café / roadmap 🚀.mp4",
+ parents: [
+ folderLayout === "userVideo" ? "video-folder-id" : "owner-folder-id",
+ ],
+ appProperties: { capObjectKey: resultKey },
+ });
+ expect(harness.upserts.at(-1)).toMatchObject({
+ providerObjectId: "result-id",
+ metadata: { fileName: "Café / roadmap 🚀.mp4" },
+ });
+ },
+ );
+
+ it("uses a matching video owner and integration for final names but leaves auxiliary and mismatched objects alone", async () => {
+ const matching = makeRepoHarness([
+ {
+ id: videoId,
+ name: "Org member's demo",
+ ownerId: videoOwnerId,
+ storageIntegrationId: integrationId,
+ },
+ ]);
+ matching.putObject(
+ storedObjectInput(".cap-folders/video-1", "folder-id", {
+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ }),
+ );
+ matching.putObject(
+ storedObjectInput(
+ ".cap-warnings/video-1/DO_NOT_EDIT_OR_DELETE.txt",
+ "warning-id",
+ { contentType: "text/plain" },
+ ),
+ );
+ const postedNames: string[] = [];
+ let nextId = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = String(input);
+ if (url.includes("/files/generateIds")) {
+ nextId += 1;
+ return jsonResponse({ ids: [`new-file-${nextId}`] });
+ }
+ if (url.includes("uploadType=resumable") && init?.method === "POST") {
+ postedNames.push(String(requestBody(init)?.name));
+ return response(200, { Location: `https://upload.test/${nextId}` });
+ }
+ throw new Error(
+ `Unexpected Drive request: ${init?.method ?? "GET"} ${url}`,
+ );
+ }),
+ );
+
+ for (const key of [resultKey, `${videoOwnerId}/${videoId}/thumbnail.png`]) {
+ await Effect.runPromise(
+ createGoogleDriveResumableUpload(
+ matching.repo,
+ makeConfig(),
+ {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key,
+ contentType: key.endsWith(".mp4") ? "video/mp4" : "image/png",
+ },
+ makeTokenStore(),
+ ),
+ );
+ }
+
+ const mismatched = makeRepoHarness([
+ {
+ id: videoId,
+ name: "Must not leak",
+ ownerId: videoOwnerId,
+ storageIntegrationId: otherIntegrationId,
+ },
+ ]);
+ mismatched.putObject(
+ storedObjectInput(".cap-folders/video-1", "folder-id", {
+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ }),
+ );
+ mismatched.putObject(
+ storedObjectInput(
+ ".cap-warnings/video-1/DO_NOT_EDIT_OR_DELETE.txt",
+ "warning-id",
+ { contentType: "text/plain" },
+ ),
+ );
+ await Effect.runPromise(
+ createGoogleDriveResumableUpload(
+ mismatched.repo,
+ makeConfig(),
+ {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key: resultKey,
+ contentType: "video/mp4",
+ },
+ makeTokenStore(),
+ ),
+ );
+
+ expect(postedNames).toEqual([
+ "Org member's demo.mp4",
+ "thumbnail.png",
+ "result.mp4",
+ ]);
+ });
+});
+
+describe("Google Drive upload updates and copies", () => {
+ it("overwrites only the content type while preserving the file id and metadata", async () => {
+ const harness = makeRepoHarness();
+ const existing = harness.putObject(
+ storedObjectInput(resultKey, "existing-file-id", {
+ contentLength: 4321,
+ fileName: "User renamed this in Drive.mp4",
+ }),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ response(200, { Location: "https://upload.test/existing" }),
+ ),
+ );
+
+ await Effect.runPromise(
+ createGoogleDriveResumableUpload(
+ harness.repo,
+ makeConfig(),
+ {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key: resultKey,
+ contentType: "video/mp4",
+ },
+ makeTokenStore(),
+ ),
+ );
+
+ const [url, init] = vi.mocked(fetch).mock.calls[0] as [string, RequestInit];
+ expect(url).toContain("/files/existing-file-id?uploadType=resumable");
+ expect(init.method).toBe("PATCH");
+ expect(requestBody(init)).toEqual({ mimeType: "video/mp4" });
+ expect(harness.upserts.at(-1)).toMatchObject({
+ providerObjectId: "existing-file-id",
+ contentLength: null,
+ preserveMetadata: true,
+ });
+ expect(
+ harness.objects.get(objectMapKey(integrationId, resultKey))?.metadata,
+ ).toEqual(existing.metadata);
+ });
+
+ it.each([404, 410])(
+ "recreates a missing complete file after %i with its current Cap title and stable identity",
+ async (missingStatus) => {
+ const harness = makeRepoHarness([
+ {
+ id: videoId,
+ name: "Current café / launch",
+ ownerId: videoOwnerId,
+ storageIntegrationId: integrationId,
+ },
+ ]);
+ const existing = harness.putObject(
+ storedObjectInput(resultKey, "missing-file-id", {
+ fileName: "Stale managed title.mp4",
+ }),
+ );
+ existing.metadata = {
+ ...existing.metadata,
+ duration: "42",
+ resolution: "3840x2160",
+ };
+ harness.putObject(
+ storedObjectInput(".cap-folders/video-1", "folder-id", {
+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ }),
+ );
+ harness.putObject(
+ storedObjectInput(
+ ".cap-warnings/video-1/DO_NOT_EDIT_OR_DELETE.txt",
+ "warning-id",
+ { contentType: "text/plain" },
+ ),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
+ if (init?.method === "PATCH") return response(missingStatus);
+ if (init?.method === "POST")
+ return response(200, { Location: "https://upload.test/recreated" });
+ throw new Error(`Unexpected Drive method: ${init?.method}`);
+ }),
+ );
+
+ const uploadUrl = await Effect.runPromise(
+ createGoogleDriveResumableUpload(
+ harness.repo,
+ makeConfig(),
+ {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key: resultKey,
+ contentType: "video/mp4",
+ },
+ makeTokenStore(),
+ ),
+ );
+
+ expect(uploadUrl).toBe("https://upload.test/recreated");
+ const [, postInit] = vi.mocked(fetch).mock.calls[1] as [
+ string,
+ RequestInit,
+ ];
+ expect(postInit.method).toBe("POST");
+ expect(requestBody(postInit)).toEqual({
+ id: "missing-file-id",
+ name: "Current café / launch.mp4",
+ mimeType: "video/mp4",
+ parents: ["folder-id"],
+ appProperties: { capObjectKey: resultKey },
+ });
+ expect(harness.upserts.at(-1)).toMatchObject({
+ objectKey: resultKey,
+ providerObjectId: "missing-file-id",
+ preserveMetadata: false,
+ metadata: {
+ fileName: "Current café / launch.mp4",
+ duration: "42",
+ resolution: "3840x2160",
+ },
+ });
+ },
+ );
+
+ it.each([404, 410])(
+ "reuses a reserved id after %i and recovers a concurrent POST conflict with PATCH",
+ async (missingStatus) => {
+ const harness = makeRepoHarness();
+ harness.putObject(
+ storedObjectInput(resultKey, "reserved-file-id", {
+ status: "pending",
+ }),
+ );
+ harness.putObject(
+ storedObjectInput(".cap-folders/video-1", "folder-id", {
+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ }),
+ );
+ harness.putObject(
+ storedObjectInput(
+ ".cap-warnings/video-1/DO_NOT_EDIT_OR_DELETE.txt",
+ "warning-id",
+ { contentType: "text/plain" },
+ ),
+ );
+ let patchCount = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
+ if (init?.method === "PATCH") {
+ patchCount += 1;
+ return patchCount === 1
+ ? response(missingStatus)
+ : response(200, { Location: "https://upload.test/recovered" });
+ }
+ if (init?.method === "POST") return response(409);
+ throw new Error(`Unexpected Drive method: ${init?.method}`);
+ }),
+ );
+
+ const uploadUrl = await Effect.runPromise(
+ createGoogleDriveResumableUpload(
+ harness.repo,
+ makeConfig(),
+ {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key: resultKey,
+ contentType: "video/mp4",
+ },
+ makeTokenStore(),
+ ),
+ );
+
+ expect(uploadUrl).toBe("https://upload.test/recovered");
+ expect(patchCount).toBe(2);
+ expect(harness.upserts.at(-1)).toMatchObject({
+ providerObjectId: "reserved-file-id",
+ preserveMetadata: true,
+ });
+ },
+ );
+
+ it("copies a final MP4 with the target title and records its managed metadata", async () => {
+ const harness = makeRepoHarness([
+ {
+ id: videoId,
+ name: "Copied: launch/demo",
+ ownerId: videoOwnerId,
+ storageIntegrationId: integrationId,
+ },
+ ]);
+ harness.putObject(
+ storedObjectInput(".cap-folders/video-1", "folder-id", {
+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ }),
+ );
+ harness.putObject(
+ storedObjectInput(
+ ".cap-warnings/video-1/DO_NOT_EDIT_OR_DELETE.txt",
+ "warning-id",
+ { contentType: "text/plain" },
+ ),
+ );
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ jsonResponse({
+ id: "copied-file-id",
+ name: "Copied: launch/demo.mp4",
+ mimeType: "video/mp4",
+ size: "1234",
+ }),
+ ),
+ );
+
+ await Effect.runPromise(
+ copyGoogleDriveFile({
+ repo: harness.repo,
+ config: makeConfig(),
+ sourceFileId: "source-file-id",
+ input: {
+ integrationId,
+ ownerId: integrationOwnerId,
+ videoId,
+ key: resultKey,
+ contentType: "video/mp4",
+ },
+ tokenStore: makeTokenStore(),
+ }),
+ );
+
+ const [, init] = vi.mocked(fetch).mock.calls[0] as [string, RequestInit];
+ expect(requestBody(init)).toEqual({
+ name: "Copied: launch/demo.mp4",
+ parents: ["folder-id"],
+ appProperties: { capObjectKey: resultKey },
+ });
+ expect(harness.upserts.at(-1)).toMatchObject({
+ providerObjectId: "copied-file-id",
+ contentLength: 1234,
+ metadata: {
+ videoId,
+ fileName: "Copied: launch/demo.mp4",
+ contentType: "video/mp4",
+ },
+ });
+ });
+});
+
+type DriveFileState = {
+ id: string;
+ name: string;
+ mimeType: string;
+ size?: string;
+ md5Checksum?: string;
+ parents: string[];
+ trashed: boolean;
+ appProperties?: Record<string, string>;
+ capabilities: { canRename: boolean };
+};
+
+const makeDriveFileFetch = (
+ files: Map<string, DriveFileState>,
+ options: {
+ failPatchFor?: string;
+ events?: string[];
+ } = {},
+) => {
+ let failed = false;
+ return vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input));
+ const fileId = decodeURIComponent(url.pathname.split("/").at(-1) ?? "");
+ const file = files.get(fileId);
+ if (!file) return response(404);
+ if (!init?.method || init.method === "GET") {
+ options.events?.push(`GET:${fileId}`);
+ return jsonResponse(file);
+ }
+ if (init.method === "PATCH") {
+ options.events?.push(`PATCH:${fileId}`);
+ if (options.failPatchFor === fileId && !failed) {
+ failed = true;
+ return response(503);
+ }
+ const body = requestBody(init);
+ if (typeof body?.name === "string") file.name = body.name;
+ return jsonResponse({ id: file.id, name: file.name });
+ }
+ throw new Error(`Unexpected Drive request: ${init.method} ${url}`);
+ });
+};
+
+const makeSyncHarness = (
+ fileStatus: StoredObject["uploadStatus"] = "complete",
+) => {
+ const harness = makeRepoHarness();
+ const folderKey = ".cap-folders/video-1";
+ const folderObject = harness.putObject(
+ storedObjectInput(folderKey, "folder-id", {
+ contentType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ fileName: "Old title",
+ }),
+ );
+ const fileObject = harness.putObject(
+ storedObjectInput(resultKey, "file-id", {
+ status: fileStatus,
+ fileName: "Old title.mp4",
+ }),
+ );
+ const files = new Map<string, DriveFileState>([
+ [
+ "folder-id",
+ {
+ id: "folder-id",
+ name: "Old title",
+ mimeType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ parents: ["root-folder"],
+ trashed: false,
+ capabilities: { canRename: true },
+ },
+ ],
+ [
+ "file-id",
+ {
+ id: "file-id",
+ name: "Old title.mp4",
+ mimeType: "video/mp4",
+ size: "5678",
+ md5Checksum: "original-md5",
+ parents: ["folder-id"],
+ trashed: false,
+ appProperties: {
+ capObjectKey: resultKey,
+ customerTag: "keep-me",
+ },
+ capabilities: { canRename: true },
+ },
+ ],
+ ]);
+ return { harness, files, folderObject, fileObject };
+};
+
+const syncVideo = {
+ id: videoId,
+ ownerId: videoOwnerId,
+ name: "New title: 测试 🎬",
+ storageIntegrationId: integrationId,
+};
+
+describe("Google Drive title synchronization", () => {
+ it("re-reads the current title and converges when it changes during the first patch", async () => {
+ const initialVideo = { ...syncVideo, name: "First title" };
+ const latestVideo = { ...syncVideo, name: "Latest title" };
+ const { harness, files } = makeSyncHarness();
+ harness.setVideo(initialVideo);
+ const driveFetch = makeDriveFileFetch(files);
+ let patchCount = 0;
+ const fetchMock = vi.fn(
+ async (input: string | URL | Request, init?: RequestInit) => {
+ const result = await driveFetch(input, init);
+ if (init?.method === "PATCH" && ++patchCount === 1) {
+ harness.setVideo(latestVideo);
+ }
+ return result;
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const dependencies = Layer.merge(
+ Layer.succeed(StorageRepo, harness.repo),
+ Layer.succeed(S3Buckets, {} as S3Buckets),
+ );
+ const storageLayer = StorageService.DefaultWithoutDependencies.pipe(
+ Layer.provide(dependencies),
+ );
+
+ await Effect.runPromise(
+ StorageService.syncVideoDisplayNames(videoId).pipe(
+ Effect.provide(storageLayer),
+ ),
+ );
+
+ expect(
+ fetchMock.mock.calls
+ .filter(([, init]) => init?.method === "PATCH")
+ .map(([, init]) => requestBody(init)),
+ ).toEqual([
+ { name: "First title" },
+ { name: "First title.mp4" },
+ { name: "Latest title" },
+ { name: "Latest title.mp4" },
+ ]);
+ expect(files.get("folder-id")?.name).toBe("Latest title");
+ expect(files.get("file-id")?.name).toBe("Latest title.mp4");
+ });
+
+ it("uses name-only patches and verifies ids, parents, hashes, and app properties", async () => {
+ const { harness, files } = makeSyncHarness();
+ harness.setFileNameUpdateResult(() => false);
+ const fetchMock = makeDriveFileFetch(files);
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ Effect.runPromise(
+ syncGoogleDriveVideoNames(
+ harness.repo,
+ makeConfig(),
+ syncVideo,
+ makeTokenStore(),
+ ),
+ ),
+ ).resolves.toBe(true);
+
+ const patchBodies = fetchMock.mock.calls
+ .filter(([, init]) => init?.method === "PATCH")
+ .map(([, init]) => requestBody(init));
+ expect(patchBodies).toEqual([
+ { name: "New title: 测试 🎬" },
+ { name: "New title: 测试 🎬.mp4" },
+ ]);
+ expect(files.get("folder-id")).toMatchObject({
+ id: "folder-id",
+ name: "New title: 测试 🎬",
+ parents: ["root-folder"],
+ });
+ expect(files.get("file-id")).toMatchObject({
+ id: "file-id",
+ name: "New title: 测试 🎬.mp4",
+ size: "5678",
+ md5Checksum: "original-md5",
+ parents: ["folder-id"],
+ appProperties: {
+ capObjectKey: resultKey,
+ customerTag: "keep-me",
+ },
+ });
+ expect(harness.fileNameUpdates).toHaveLength(2);
+ });
+
+ it("renames a usable pending result only after every target passes provider preflight", async () => {
+ const { harness, files, fileObject } = makeSyncHarness("pending");
+ const events: string[] = [];
+ const fetchMock = makeDriveFileFetch(files, { events });
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ Effect.runPromise(
+ syncGoogleDriveVideoNames(
+ harness.repo,
+ makeConfig(),
+ syncVideo,
+ makeTokenStore(),
+ ),
+ ),
+ ).resolves.toBe(true);
+ expect(events.indexOf("PATCH:folder-id")).toBeGreaterThan(
+ events.indexOf("GET:file-id"),
+ );
+ expect(fileObject).toMatchObject({
+ providerObjectId: "file-id",
+ uploadStatus: "pending",
+ contentLength: null,
+ });
+ });
+
+ it.each([
+ ["zero provider size", "0", null],
+ ["stored length mismatch", "5678", 1234],
+ ] as const)(
+ "retries a pending result with %s without patching",
+ async (_, size, contentLength) => {
+ const { harness, files, fileObject } = makeSyncHarness("pending");
+ fileObject.contentLength = contentLength;
+ const providerFile = files.get("file-id");
+ if (providerFile) providerFile.size = size;
+ const fetchMock = makeDriveFileFetch(files);
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ Effect.runPromise(
+ syncGoogleDriveVideoNames(
+ harness.repo,
+ makeConfig(),
+ syncVideo,
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toBeDefined();
+ expect(
+ fetchMock.mock.calls.filter(([, init]) => init?.method === "PATCH"),
+ ).toHaveLength(0);
+ expect(fileObject.uploadStatus).toBe("pending");
+ },
+ );
+
+ it("resumes idempotently after a partial Drive failure", async () => {
+ const { harness, files } = makeSyncHarness();
+ const fetchMock = makeDriveFileFetch(files, { failPatchFor: "file-id" });
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(
+ Effect.runPromise(
+ syncGoogleDriveVideoNames(
+ harness.repo,
+ makeConfig(),
+ syncVideo,
+ makeTokenStore(),
+ ),
+ ),
+ ).rejects.toBeDefined();
+ expect(files.get("folder-id")?.name).toBe("New title: 测试 🎬");
+ expect(files.get("file-id")?.name).toBe("Old title.mp4");
+
+ await expect(
+ Effect.runPromise(
+ syncGoogleDriveVideoNames(
+ harness.repo,
+ makeConfig(),
+ syncVideo,
+ makeTokenStore(),
+ ),
+ ),
+ ).resolves.toBe(true);
+ expect(files.get("file-id")?.name).toBe("New title: 测试 🎬.mp4");
+ });
+});
diff --git a/packages/web-backend/src/Storage/GoogleDrive.ts b/packages/web-backend/src/Storage/GoogleDrive.ts
index c981dbd91..7a9a26db3 100644
--- a/packages/web-backend/src/Storage/GoogleDrive.ts
+++ b/packages/web-backend/src/Storage/GoogleDrive.ts
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
import { serverEnv } from "@cap/env";
import { Storage, type User, type Video } from "@cap/web-domain";
import { Effect, Either, Option, Schedule } from "effect";
+import { getGoogleDriveVideoNames } from "./google-drive-names.ts";
import type {
GoogleDriveAccessTokenCache,
GoogleDriveIntegrationConfig,
@@ -25,7 +26,12 @@ export type GoogleDriveFile = {
name?: string;
mimeType?: string;
size?: string;
+ md5Checksum?: string;
modifiedTime?: string;
+ parents?: string[];
+ trashed?: boolean;
+ appProperties?: Record<string, string>;
+ capabilities?: { canRename?: boolean };
};
type GoogleDriveListResponse = {
@@ -77,6 +83,7 @@ export type CreateGoogleDriveUploadInput = {
key: string;
contentType: string;
contentLength?: number;
+ videoTitle?: string;
};
const normalizeContentType = (contentType?: string | null) =>
@@ -483,6 +490,40 @@ const getDriveFileName = (key: string) => {
return parts.at(-1) ?? "file";
};
+const getVideoNamesForUpload = (
+ repo: StorageRepo,
+ input: CreateGoogleDriveUploadInput,
+) =>
+ Effect.gen(function* () {
+ const [ownerId, videoId] = input.key.split("/");
+ if (!input.videoId || input.videoId !== videoId) return null;
+ if (input.videoTitle !== undefined) {
+ return getGoogleDriveVideoNames(input.videoTitle);
+ }
+ const video = yield* repo.getVideoForNameSync(input.videoId);
+ if (
+ Option.isNone(video) ||
+ video.value.ownerId !== ownerId ||
+ video.value.storageIntegrationId !== input.integrationId
+ ) {
+ return null;
+ }
+ return getGoogleDriveVideoNames(video.value.name);
+ }).pipe(Effect.mapError((cause) => new Storage.StorageError({ cause })));
+
+const getNewDriveFileName = (
+ repo: StorageRepo,
+ input: CreateGoogleDriveUploadInput,
+) =>
+ Effect.gen(function* () {
+ const parts = input.key.split("/");
+ if (parts.length === 3 && parts[2] === "result.mp4") {
+ const names = yield* getVideoNamesForUpload(repo, input);
+ if (names) return names.fileName;
+ }
+ return getDriveFileName(input.key);
+ });
+
const getDriveFolderParts = (
key: string,
config: GoogleDriveIntegrationConfig,
@@ -768,6 +809,7 @@ const getOrCreateGoogleDriveFolder = ({
folderPath,
name,
parentId,
+ isVideoFolder,
tokenStore,
}: {
repo: StorageRepo;
@@ -776,6 +818,7 @@ const getOrCreateGoogleDriveFolder = ({
folderPath: string;
name: string;
parentId: string;
+ isVideoFolder: boolean;
tokenStore?: GoogleDriveTokenStore;
}) =>
Effect.gen(function* () {
@@ -819,15 +862,24 @@ const getOrCreateGoogleDriveFolder = ({
);
}
- yield* createGoogleDriveFolderWithId(
- config,
- folderId,
- name,
- parentId,
- tokenStore,
- ).pipe(
+ yield* Effect.gen(function* () {
+ const names = isVideoFolder
+ ? yield* getVideoNamesForUpload(repo, input)
+ : null;
+ const displayName = names?.folderName ?? name;
+ if (displayName !== name) {
+ yield* repo.updateObjectFileName(reserved, displayName);
+ }
+ yield* createGoogleDriveFolderWithId(
+ config,
+ folderId,
+ displayName,
+ parentId,
+ tokenStore,
+ );
+ }).pipe(
Effect.tapError(() =>
- repo.deleteObjectByKey(input.integrationId, folderObjectKey),
+ repo.deleteObjectByKey(input.integrationId, folderObjectKey, folderId),
),
);
yield* repo.markObjectComplete(input.integrationId, folderObjectKey);
@@ -932,6 +984,9 @@ const getGoogleDriveUploadParentId = (
folderPath: pathParts.join("/"),
name: folderName,
parentId,
+ isVideoFolder:
+ pathParts.length === (config.folderLayout === "userVideo" ? 2 : 1) &&
+ folderName === input.videoId,
tokenStore,
});
if (pathParts.length === 1) {
@@ -1020,128 +1075,126 @@ export const createGoogleDriveResumableUpload = (
{
method: "PATCH",
headers,
- body: JSON.stringify({
- name: getDriveFileName(input.key),
- mimeType: contentType,
- appProperties: {
- capObjectKey: input.key,
- },
- }),
+ body: JSON.stringify({ mimeType: contentType }),
},
tokenStore,
).pipe(Effect.flatMap(requireUploadUrl));
const startSessionForNewFile = (fileId: string, parentId: string) =>
- driveFetch(
- config,
- appendSharedDriveCreateParams(
- `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size`,
- ),
- {
- method: "POST",
- headers,
- body: JSON.stringify({
- id: fileId,
- name: getDriveFileName(input.key),
- mimeType: contentType,
- parents: [parentId],
- appProperties: {
- capObjectKey: input.key,
- },
- }),
- },
- tokenStore,
- ).pipe(Effect.flatMap(requireUploadUrl));
-
- const existing = yield* repo.getObjectByKey(input.integrationId, input.key);
- if (Option.isSome(existing)) {
- const existingFileId = existing.value.providerObjectId;
- let resolvedFileId = existingFileId;
-
- const patched = yield* startSessionForExistingFile(existingFileId).pipe(
- Effect.either,
- );
- let uploadUrl: string;
- if (Either.isRight(patched)) {
- uploadUrl = patched.right;
- } else if (isDriveRequestStatus(patched.left, 404, 410)) {
- // The stored file id was reserved (files.generateIds) but its upload
- // session never completed, so the file doesn't exist on Drive yet and
- // can't be PATCHed. Create it instead, reusing the reserved id so
- // concurrent presigns converge on the same file.
- const parentId = yield* getGoogleDriveUploadParentId(
- repo,
+ Effect.gen(function* () {
+ const fileName = yield* getNewDriveFileName(repo, input);
+ const uploadUrl = yield* driveFetch(
config,
- input,
+ appendSharedDriveCreateParams(
+ `${DRIVE_UPLOAD_BASE}/files?uploadType=resumable&fields=id,name,mimeType,size`,
+ ),
+ {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ id: fileId,
+ name: fileName,
+ mimeType: contentType,
+ parents: [parentId],
+ appProperties: { capObjectKey: input.key },
+ }),
+ },
tokenStore,
- );
- const created = yield* startSessionForNewFile(
- existingFileId,
- parentId,
- ).pipe(Effect.either);
- if (Either.isRight(created)) {
- uploadUrl = created.right;
- } else if (isDriveRequestStatus(created.left, 409)) {
- // The file materialized between the two calls; PATCH now works.
- uploadUrl = yield* startSessionForExistingFile(existingFileId);
- } else {
- // The reserved id itself is unusable (e.g. the integration was
- // reconnected to a different account) — start over with a fresh id.
- const freshFileId = yield* generateGoogleDriveFileId(
- config,
- tokenStore,
- );
- uploadUrl = yield* startSessionForNewFile(freshFileId, parentId);
- resolvedFileId = freshFileId;
- }
- } else {
- return yield* Effect.fail(patched.left);
- }
+ ).pipe(Effect.flatMap(requireUploadUrl));
+ return { uploadUrl, fileName };
+ });
- yield* repo.upsertObject({
+ const existing = yield* repo.getObjectByKey(input.integrationId, input.key);
+ let object: Option.Option.Value<typeof existing>;
+ let newReservation = false;
+ if (Option.isSome(existing)) {
+ object = existing.value;
+ } else {
+ const fileId = yield* generateGoogleDriveFileId(config, tokenStore);
+ object = yield* repo.reserveObject({
integrationId: input.integrationId,
ownerId: input.ownerId,
videoId: input.videoId,
objectKey: input.key,
- providerObjectId: resolvedFileId,
- uploadSessionUrl: uploadUrl,
- uploadStatus: "pending",
+ providerObjectId: fileId,
contentType,
- contentLength: input.contentLength ?? existing.value.contentLength,
+ contentLength: input.contentLength ?? null,
metadata: {
- ...(existing.value.metadata ?? {}),
videoId: input.videoId ?? undefined,
fileName: getDriveFileName(input.key),
contentType,
},
});
- return uploadUrl;
+ newReservation = object.providerObjectId === fileId;
}
- const [parentId, fileId] = yield* Effect.all([
- getGoogleDriveUploadParentId(repo, config, input, tokenStore),
- generateGoogleDriveFileId(config, tokenStore),
- ]);
-
- const uploadUrl = yield* startSessionForNewFile(fileId, parentId);
+ let resolvedFileId = object.providerObjectId;
+ let fileName = object.metadata?.fileName;
+ let createdFile = false;
+ let uploadUrl: string | undefined;
+ if (!newReservation) {
+ const patched = yield* startSessionForExistingFile(resolvedFileId).pipe(
+ Effect.either,
+ );
+ if (Either.isRight(patched)) {
+ uploadUrl = patched.right;
+ } else if (!isDriveRequestStatus(patched.left, 404, 410)) {
+ return yield* Effect.fail(patched.left);
+ }
+ }
+ if (uploadUrl === undefined) {
+ const parentId = yield* getGoogleDriveUploadParentId(
+ repo,
+ config,
+ input,
+ tokenStore,
+ );
+ const created = yield* startSessionForNewFile(
+ resolvedFileId,
+ parentId,
+ ).pipe(Effect.either);
+ if (Either.isRight(created)) {
+ uploadUrl = created.right.uploadUrl;
+ fileName = created.right.fileName;
+ createdFile = true;
+ } else if (isDriveRequestStatus(created.left, 409)) {
+ uploadUrl = yield* startSessionForExistingFile(resolvedFileId);
+ } else if (
+ !newReservation &&
+ isDriveRequestStatus(created.left, 400, 404, 410)
+ ) {
+ const freshFileId = yield* generateGoogleDriveFileId(
+ config,
+ tokenStore,
+ );
+ const fresh = yield* startSessionForNewFile(freshFileId, parentId);
+ uploadUrl = fresh.uploadUrl;
+ fileName = fresh.fileName;
+ createdFile = true;
+ resolvedFileId = freshFileId;
+ } else {
+ return yield* Effect.fail(created.left);
+ }
+ }
yield* repo.upsertObject({
integrationId: input.integrationId,
ownerId: input.ownerId,
videoId: input.videoId,
objectKey: input.key,
- providerObjectId: fileId,
+ providerObjectId: resolvedFileId,
uploadSessionUrl: uploadUrl,
uploadStatus: "pending",
contentType,
contentLength: input.contentLength ?? null,
+ preserveMetadata: !createdFile,
metadata: {
+ ...(object.metadata ?? {}),
videoId: input.videoId ?? undefined,
- fileName: getDriveFileName(input.key),
+ fileName,
contentType,
},
});
-
return uploadUrl;
});
@@ -1153,7 +1206,7 @@ export const getGoogleDriveFileMetadata = (
driveFetch(
config,
appendSharedDriveCreateParams(
- `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size`,
+ `${DRIVE_API_BASE}/files/${encodeURIComponent(fileId)}?fields=id,name,mimeType,size,md5Checksum,parents,trashed,appProperties,capabilities(canRename)`,
),
undefined,
tokenStore,
@@ -1245,9 +1298,42 @@ export const getGoogleDriveObjectResponse = (
{ headers },
tokenStore,
);
+
return response;
});
+const discardGoogleDriveResponseBody = (response: Response) =>
+ Effect.tryPromise({
+ try: async () => {
+ await response.body?.cancel();
+ return response.status;
+ },
+ catch: (cause) => new Storage.StorageError({ cause }),
+ });
+
+const getUsableGoogleDriveFileSize = (file: GoogleDriveFile) => {
+ const size = Number(file.size);
+ return Number.isSafeInteger(size) && size > 0 ? size : null;
+};
+
+const googleDriveFileMatchesTarget = (
+ file: GoogleDriveFile,
+ input: {
+ providerObjectId: string;
+ mimeType: string;
+ parentId: string | null;
+ key: string;
+ },
+) =>
+ input.parentId !== null &&
+ file.id === input.providerObjectId &&
+ !file.trashed &&
+ file.mimeType === input.mimeType &&
+ file.parents?.length === 1 &&
+ file.parents[0] === input.parentId &&
+ (input.mimeType === GOOGLE_DRIVE_FOLDER_MIME_TYPE ||
+ file.appProperties?.capObjectKey === input.key);
+
export const deleteGoogleDriveFile = (
config: GoogleDriveIntegrationConfig,
fileId: string,
@@ -1284,6 +1370,7 @@ export const copyGoogleDriveFile = ({
input,
tokenStore,
);
+ const fileName = yield* getNewDriveFileName(repo, input);
const response = yield* driveFetch(
config,
appendSharedDriveCreateParams(
@@ -1293,7 +1380,7 @@ export const copyGoogleDriveFile = ({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- name: getDriveFileName(input.key),
+ name: fileName,
parents: [parentId],
appProperties: {
capObjectKey: input.key,
@@ -1322,8 +1409,198 @@ export const copyGoogleDriveFile = ({
uploadStatus: "complete",
contentType: copied.mimeType ?? input.contentType,
contentLength: copied.size ? Number(copied.size) : null,
+ metadata: {
+ videoId: input.videoId ?? undefined,
+ fileName: copied.name ?? fileName,
+ contentType: copied.mimeType ?? input.contentType,
+ },
});
});
+export const syncGoogleDriveVideoNames = (
+ repo: StorageRepo,
+ config: GoogleDriveIntegrationConfig,
+ video: {
+ id: Video.VideoId;
+ ownerId: User.UserId;
+ name: string;
+ storageIntegrationId: Storage.StorageIntegrationId;
+ },
+ tokenStore?: GoogleDriveTokenStore,
+) =>
+ Effect.gen(function* () {
+ const names = getGoogleDriveVideoNames(video.name);
+ if (!names) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Video title cannot be used as a Google Drive name"),
+ }),
+ );
+ }
+ const integrationId = video.storageIntegrationId;
+ const folderKey = getDriveFolderObjectKey(
+ config.folderLayout === "userVideo"
+ ? `${video.ownerId}/${video.id}`
+ : video.id,
+ );
+ const folder = yield* repo.getObjectByKey(integrationId, folderKey);
+ const fileKey = `${video.ownerId}/${video.id}/result.mp4`;
+ const file = yield* repo.getObjectByKey(integrationId, fileKey);
+ let folderParentId = config.folderId;
+ if (config.folderLayout === "userVideo" && Option.isSome(folder)) {
+ const userFolder = yield* repo.getObjectByKey(
+ integrationId,
+ getDriveFolderObjectKey(video.ownerId),
+ );
+ if (
+ Option.isNone(userFolder) ||
+ userFolder.value.uploadStatus !== "complete"
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Google Drive user folder is not ready"),
+ }),
+ );
+ }
+ folderParentId = userFolder.value.providerObjectId;
+ }
+ const targets = [
+ {
+ object: folder,
+ name: names.folderName,
+ key: folderKey,
+ parentId: folderParentId,
+ mimeType: GOOGLE_DRIVE_FOLDER_MIME_TYPE,
+ },
+ {
+ object: file,
+ name: names.fileName,
+ key: fileKey,
+ parentId: Option.isSome(folder) ? folder.value.providerObjectId : null,
+ mimeType: "video/mp4",
+ },
+ ];
+ const verifiedTargets: Array<{
+ target: (typeof targets)[number];
+ object: Option.Option.Value<(typeof targets)[number]["object"]>;
+ before: GoogleDriveFile;
+ }> = [];
+ for (const target of targets) {
+ if (Option.isNone(target.object)) continue;
+ const object = target.object.value;
+ if (
+ object.videoId !== video.id ||
+ object.integrationId !== integrationId ||
+ object.objectKey !== target.key ||
+ !target.parentId ||
+ (object.uploadStatus !== "complete" &&
+ !(object.uploadStatus === "pending" && target.key === fileKey))
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Google Drive name target is not ready"),
+ }),
+ );
+ }
+ }
+ for (const target of targets) {
+ if (Option.isNone(target.object)) continue;
+ const object = target.object.value;
+ const before = yield* getGoogleDriveFileMetadata(
+ config,
+ object.providerObjectId,
+ tokenStore,
+ );
+ if (
+ !googleDriveFileMatchesTarget(before, {
+ providerObjectId: object.providerObjectId,
+ mimeType: target.mimeType,
+ parentId: target.parentId,
+ key: target.key,
+ })
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Google Drive name target identity changed"),
+ }),
+ );
+ }
+ if (object.uploadStatus === "pending") {
+ const usableSize = getUsableGoogleDriveFileSize(before);
+ if (
+ usableSize === null ||
+ (object.contentLength !== null && object.contentLength !== usableSize)
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Google Drive file is not ready to rename"),
+ }),
+ );
+ }
+ }
+ verifiedTargets.push({ target, object, before });
+ }
+ for (const { target, object, before } of verifiedTargets) {
+ if (before.name !== target.name) {
+ if (before.capabilities?.canRename === false) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Google Drive file cannot be renamed"),
+ }),
+ );
+ }
+ const renameResponse = yield* driveFetch(
+ config,
+ appendSharedDriveCreateParams(
+ `${DRIVE_API_BASE}/files/${encodeURIComponent(object.providerObjectId)}?fields=id,name`,
+ ),
+ {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: target.name }),
+ },
+ tokenStore,
+ );
+ yield* discardGoogleDriveResponseBody(renameResponse);
+ const after = yield* getGoogleDriveFileMetadata(
+ config,
+ object.providerObjectId,
+ tokenStore,
+ );
+ if (
+ after.id !== before.id ||
+ after.name !== target.name ||
+ after.mimeType !== before.mimeType ||
+ after.size !== before.size ||
+ after.md5Checksum !== before.md5Checksum ||
+ after.trashed !== before.trashed ||
+ JSON.stringify(after.parents) !== JSON.stringify(before.parents) ||
+ JSON.stringify(after.appProperties) !==
+ JSON.stringify(before.appProperties)
+ ) {
+ return yield* Effect.fail(
+ new Storage.StorageError({
+ cause: new Error("Google Drive name update did not verify"),
+ }),
+ );
+ }
+ }
+ if (object.metadata?.fileName !== target.name) {
+ const updated = yield* repo.updateObjectFileName(object, target.name);
+ if (!updated) {
+ const current = yield* repo.getObjectByKey(integrationId, target.key);
+ if (
+ Option.isNone(current) ||
+ current.value.id !== object.id ||
+ current.value.providerObjectId !== object.providerObjectId ||
+ current.value.metadata?.fileName !== target.name
+ )
+ return false;
+ }
+ }
+ }
+ return true;
+ }).pipe(Effect.mapError((cause) => new Storage.StorageError({ cause })));
+
export const parseVideoIdFromObjectKey = (key: string) =>
Option.fromNullable(key.split("/")[1]).pipe(Option.filter((id) => id !== ""));
diff --git a/packages/web-backend/src/Storage/StorageRepo.ts b/packages/web-backend/src/Storage/StorageRepo.ts
index 4e63dbee5..a9af0786b 100644
--- a/packages/web-backend/src/Storage/StorageRepo.ts
+++ b/packages/web-backend/src/Storage/StorageRepo.ts
@@ -57,6 +57,7 @@ export type StorageObjectInput = {
contentType?: string | null;
contentLength?: number | null;
metadata?: Storage.StorageObjectMetadata | null;
+ preserveMetadata?: boolean;
};
const getAffectedRows = (result: unknown) => {
@@ -338,7 +339,9 @@ export class StorageRepo extends Effect.Service<StorageRepo>()("StorageRepo", {
uploadStatus: value.uploadStatus,
contentType: value.contentType,
contentLength: value.contentLength,
- metadata: value.metadata,
+ metadata: input.preserveMetadata
+ ? Dz.sql`${Db.storageObjects.metadata}`
+ : value.metadata,
updatedAt: new Date(),
},
}),
@@ -418,6 +421,53 @@ export class StorageRepo extends Effect.Service<StorageRepo>()("StorageRepo", {
}),
);
+ const getVideoForNameSync = Effect.fn("StorageRepo.getVideoForNameSync")(
+ (videoId: Video.VideoId) =>
+ db
+ .use((db) =>
+ db
+ .select({
+ id: Db.videos.id,
+ name: Db.videos.name,
+ ownerId: Db.videos.ownerId,
+ storageIntegrationId: Db.videos.storageIntegrationId,
+ })
+ .from(Db.videos)
+ .where(Dz.eq(Db.videos.id, videoId))
+ .limit(1),
+ )
+ .pipe(Effect.map((rows) => Option.fromNullable(rows[0]))),
+ );
+
+ const updateObjectFileName = Effect.fn("StorageRepo.updateObjectFileName")(
+ (object: typeof Db.storageObjects.$inferSelect, fileName: string) =>
+ db
+ .use((db) =>
+ db
+ .update(Db.storageObjects)
+ .set({
+ metadata: Dz.sql`JSON_SET(COALESCE(${Db.storageObjects.metadata}, JSON_OBJECT()), '$.fileName', ${fileName})`,
+ updatedAt: new Date(),
+ })
+ .where(
+ Dz.and(
+ Dz.eq(Db.storageObjects.id, object.id),
+ Dz.eq(Db.storageObjects.integrationId, object.integrationId),
+ Dz.eq(
+ Db.storageObjects.objectKeyHash,
+ getObjectKeyHash(object.objectKey),
+ ),
+ Dz.eq(Db.storageObjects.objectKey, object.objectKey),
+ Dz.eq(
+ Db.storageObjects.providerObjectId,
+ object.providerObjectId,
+ ),
+ ),
+ ),
+ )
+ .pipe(Effect.map((result) => getAffectedRows(result) > 0)),
+ );
+
const listObjectsByPrefix = Effect.fn("StorageRepo.listObjectsByPrefix")(
(
integrationId: Storage.StorageIntegrationId,
@@ -476,7 +526,11 @@ export class StorageRepo extends Effect.Service<StorageRepo>()("StorageRepo", {
);
const deleteObjectByKey = Effect.fn("StorageRepo.deleteObjectByKey")(
- (integrationId: Storage.StorageIntegrationId, key: string) =>
+ (
+ integrationId: Storage.StorageIntegrationId,
+ key: string,
+ providerObjectId?: string,
+ ) =>
db.use((db) =>
db
.delete(Db.storageObjects)
@@ -484,6 +538,9 @@ export class StorageRepo extends Effect.Service<StorageRepo>()("StorageRepo", {
Dz.and(
Dz.eq(Db.storageObjects.integrationId, integrationId),
Dz.eq(Db.storageObjects.objectKeyHash, getObjectKeyHash(key)),
+ providerObjectId
+ ? Dz.eq(Db.storageObjects.providerObjectId, providerObjectId)
+ : undefined,
),
),
),
@@ -502,6 +559,8 @@ export class StorageRepo extends Effect.Service<StorageRepo>()("StorageRepo", {
upsertObject,
reserveObject,
getObjectByKey,
+ getVideoForNameSync,
+ updateObjectFileName,
listObjectsByPrefix,
markObjectComplete,
deleteObjectByKey,
diff --git a/packages/web-backend/src/Storage/google-drive-names.ts b/packages/web-backend/src/Storage/google-drive-names.ts
new file mode 100644
index 000000000..c012367f8
--- /dev/null
+++ b/packages/web-backend/src/Storage/google-drive-names.ts
@@ -0,0 +1,10 @@
+export const getGoogleDriveVideoNames = (title?: string | null) => {
+ if (!title?.trim() || /\p{Cc}/u.test(title)) {
+ return null;
+ }
+
+ return {
+ folderName: title,
+ fileName: /\.mp4$/i.test(title) ? title : `${title}.mp4`,
+ };
+};
diff --git a/packages/web-backend/src/Storage/index.ts b/packages/web-backend/src/Storage/index.ts
index b8e9a3186..8221a6bef 100644
--- a/packages/web-backend/src/Storage/index.ts
+++ b/packages/web-backend/src/Storage/index.ts
@@ -24,6 +24,7 @@ import {
getGoogleDriveObjectResponse,
getGoogleDriveObjectText,
parseVideoIdFromObjectKey,
+ syncGoogleDriveVideoNames,
} from "./GoogleDrive.ts";
import { createStorageObjectToken } from "./SignedObject.ts";
import type { GoogleDriveIntegrationConfig } from "./StorageRepo.ts";
@@ -34,6 +35,7 @@ type UploadTargetInput = {
contentLength?: number;
fields?: Record<string, string>;
method?: "post" | "put";
+ videoTitle?: string;
};
type MultipartAccess = {
@@ -372,6 +374,7 @@ const makeGoogleDriveAccess = ({
providerObjectId: file.id,
uploadStatus: "complete",
contentType,
+ preserveMetadata: true,
contentLength:
parseGoogleDriveContentLength(file) ??
previous.contentLength ??
@@ -720,6 +723,7 @@ const makeGoogleDriveAccess = ({
key,
contentType: input.contentType,
contentLength: input.contentLength,
+ videoTitle: input.videoTitle,
},
tokenStore,
).pipe(
@@ -899,6 +903,57 @@ export class Storage extends Effect.Service<Storage>()("Storage", {
return yield* access.createUploadTarget(key, input);
});
+ const syncVideoDisplayNames = Effect.fn("Storage.syncVideoDisplayNames")(
+ function* (videoId: Video.VideoId) {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const current = yield* mapStorageError(
+ repo.getVideoForNameSync(videoId),
+ );
+ if (Option.isNone(current) || !current.value.storageIntegrationId)
+ return;
+ const video = current.value;
+ const integrationId = current.value.storageIntegrationId;
+ const integration = yield* mapStorageError(
+ repo.getIntegrationById(integrationId),
+ );
+ if (Option.isNone(integration)) {
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error("Storage integration not found"),
+ }),
+ );
+ }
+ const config = yield* mapStorageError(
+ repo.getGoogleDriveConfig(integration.value),
+ );
+ const synced = yield* syncGoogleDriveVideoNames(
+ repo,
+ config,
+ { ...video, storageIntegrationId: integrationId },
+ makeGoogleDriveTokenStore(repo, integration.value),
+ );
+ const latest = yield* mapStorageError(
+ repo.getVideoForNameSync(videoId),
+ );
+ if (Option.isNone(latest)) return;
+ if (
+ synced &&
+ latest.value.name === video.name &&
+ latest.value.ownerId === video.ownerId &&
+ latest.value.storageIntegrationId === integrationId
+ )
+ return;
+ }
+ return yield* Effect.fail(
+ new StorageDomain.StorageError({
+ cause: new Error(
+ "Video changed during Google Drive name synchronization",
+ ),
+ }),
+ );
+ },
+ );
+
return {
getS3WritableAccessForUser,
getOrganizationWritableAccess,
@@ -906,6 +961,7 @@ export class Storage extends Effect.Service<Storage>()("Storage", {
getAccessForVideo,
createUploadTargetForUser,
createUploadTargetForVideo,
+ syncVideoDisplayNames,
};
}),
dependencies: [StorageRepo.Default, S3Buckets.Default],
@@ -932,6 +988,10 @@ export class Storage extends Effect.Service<Storage>()("Storage", {
);
static getAccessForVideo = (video: Video.Video) =>
Effect.flatMap(Storage, (storage) => storage.getAccessForVideo(video));
+ static syncVideoDisplayNames = (videoId: Video.VideoId) =>
+ Effect.flatMap(Storage, (storage) =>
+ storage.syncVideoDisplayNames(videoId),
+ );
static createUploadTargetForUser = (
userId: User.UserId,
key: string,