Skip to content

Open source CapCut alternative.

TypeScript
46.1 KB
Raw Blame
// Cloud twin of the engine's shared library (server/library.ts): asset metadata
// in CutLibraryAsset rows, template docs in CutTemplate rows, bytes in R2 under
// cut/<userId>/library/. Response shapes mirror the engine exactly.
import type {
  LibraryAsset,
  LibraryFolder,
  LibrarySource,
  LibraryTemplate,
  TemplateAudio,
  TemplateInput,
  TemplateLayer,
  TemplateMedia,
} from "../library";
import { templateExtras } from "../templateExtras";
import { notesCloud } from "@/cut/server/cloud/notes";
import { resolveParent, subtreeOf } from "@/cut/lib/folderTree";
import type { StoredAsset } from "@/cut/lib/types";
import type { Prisma } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
import { MEDIA_REDIRECT_HEADERS, mediaObjectUrl, mediaUrlLifetime } from "./mediaCdn";
import { getProject, takenMediaNames } from "./projects";
import { copy, del, head, libraryKey, presignPut, projectMediaKey } from "./r2";
import { addUsage, quotaCheck } from "./usage";
import { renderJobCheck } from "./limits";
import { wakeRenderWorker } from "./wake";
import { libraryTypeOf } from "@/cut/lib/libraryFileType";
import { itemName } from "@/cut/lib/itemName";
import { compatCoverIn, compatCovers } from "@/cut/lib/proxyNames";
import type { AssetType } from "@/cut/lib/types";
import { caught, decodeFileParam, dedupeName, err, HttpResponseError, inspirationFolderId, redirect, safeFileName, storableFileName } from "./util";
import { UserError } from "@/cut/lib/userError";

/** Cap on one signed-URL batch, matching the project media batch. */
const PRESIGN_GET_BATCH_MAX = 500;

/** The one job that builds an asset's playable copy, so a second ask joins it. */
export const libraryProxyJobId = (assetId: string) => `library-proxy-${assetId}`;

/** The objects under this account's library prefix: its files, and the
 * playable copies (kind "proxy", no project) built beside them. */
const LIBRARY_PREFIX_OBJECTS = { projectId: null, kind: { in: ["library", "proxy"] } };

/** Descriptive fields the engine derives with ffprobe; the cloud stores them on
 * the row, supplied by the client (which probed in the browser) or copied from
 * the source project doc. */
interface AssetMeta {
  name?: string;
  originalFile?: string;
  /** File name of the playable copy of an undecodable master, a quota-exempt
   * object (kind "proxy") under this account's library prefix. */
  proxyFile?: string;
  /** The short name the titling model read off the clip itself, standing in
   * for the file's own name wherever the asset is shown. Written once, by
   * cloud/clipTitle.ts. */
  title?: string;
  type?: AssetType;
  duration?: number;
  width?: number;
  height?: number;
  source?: LibrarySource;
  /** File name of the source's cover image, an object of its own under this
   * account's library prefix. */
  posterFile?: string;
  /** A linked item's identity: the hash every project names it by. The
   * page computes it before the upload, so a sync never reads the bytes. */
  contentKey?: string;
  /** What kind of table a LUT holds. */
  lut?: { kind: "1d" | "3d" | "shaper+3d"; size: number };
  /** How the asset entered the account from the iOS app: a phone camera
   * recording (the desktop's Camera Roll) or an inspiration item. */
  origin?: "camera" | "inspiration";
}

interface TemplateDoc {
  folderId?: string | null;
  duration: number;
  media: TemplateMedia[];
  layers: TemplateLayer[];
  audio: TemplateAudio[];
  texts: unknown[];
  cues: unknown[];
  sound?: LibraryTemplate["sound"];
  grade?: LibraryTemplate["grade"];
  transitions?: unknown[];
  stickers?: unknown[];
  captions?: unknown;
  project?: unknown;
}

/** A template with nothing on it saves nothing; a sound preset or a saved
 * grade is a template carrying only its treatment. */
const templateEmpty = (input: TemplateInput) =>
  !input.media?.length && !input.texts?.length && !input.cues?.length && !input.sound && !input.grade;

type MediaObjectRow = {
  id: string;
  r2Key: string;
  fileName: string;
  mime: string;
  bytes: bigint;
  uploadState: string;
};

async function takenLibraryNames(userId: string): Promise<Set<string>> {
  const rows = await prisma.cutMediaObject.findMany({
    where: { userId, ...LIBRARY_PREFIX_OBJECTS },
    select: { fileName: true },
  });
  return new Set(rows.map((r) => r.fileName));
}

export function assetView(
  row: { id: string; folderId: string | null; meta: unknown; createdAt: Date },
  obj: { fileName: string },
): LibraryAsset & { title?: string } {
  const meta = (row.meta ?? {}) as AssetMeta;
  return {
    id: row.id,
    fileName: obj.fileName,
    ...(meta.originalFile ? { originalFile: meta.originalFile } : {}),
    ...(meta.proxyFile ? { proxyFile: meta.proxyFile } : {}),
    name: meta.name ?? obj.fileName,
    type: meta.type ?? libraryTypeOf(obj.fileName) ?? "video",
    duration: meta.duration ?? 0,
    ...(meta.width ? { width: meta.width, height: meta.height } : {}),
    addedAt: row.createdAt.getTime(),
    folderId: row.folderId ?? null,
    ...(meta.source ? { source: meta.source } : {}),
    ...(meta.posterFile ? { posterFile: meta.posterFile } : {}),
    ...(meta.title ? { title: meta.title } : {}),
    ...(meta.origin ? { origin: meta.origin } : {}),
    ...(meta.contentKey ? { contentKey: meta.contentKey } : {}),
    ...(meta.lut ? { lut: meta.lut } : {}),
  };
}

export function templateView(row: {
  id: string;
  name: string;
  doc: unknown;
  createdAt: Date;
}): LibraryTemplate {
  const doc = row.doc as unknown as TemplateDoc;
  return {
    id: row.id,
    name: row.name,
    addedAt: row.createdAt.getTime(),
    folderId: doc.folderId ?? null,
    duration: doc.duration,
    media: doc.media ?? [],
    layers: doc.layers ?? [],
    audio: doc.audio ?? [],
    texts: doc.texts ?? [],
    cues: doc.cues ?? [],
    ...(doc.sound ? { sound: doc.sound } : {}),
    ...(templateExtras(doc) as Pick<LibraryTemplate, "transitions" | "stickers" | "captions" | "project" | "grade">),
  };
}

const asJson = (doc: TemplateDoc) => doc as unknown as Prisma.InputJsonValue;

async function findTemplate(userId: string, id: string) {
  return prisma.cutTemplate.findFirst({ where: { id, userId } });
}

/** A project media object row, complete, by fileName — the copy source for
 * save/saveTemplate/addToTemplate. */
async function projectMediaObject(
  userId: string,
  projectId: string,
  fileName: string,
) {
  return prisma.cutMediaObject.findFirst({
    where: {
      userId,
      projectId,
      kind: "media",
      fileName,
      uploadState: "complete",
    },
  });
}

async function libraryMediaObject(userId: string, fileName: string) {
  return prisma.cutMediaObject.findFirst({
    where: { userId, kind: "library", fileName },
  });
}

/** Copy one complete source object to a fresh library key, recording the row
 * and usage. Returns the library fileName. */
async function copyIntoLibrary(
  userId: string,
  src: MediaObjectRow,
  taken: Set<string>,
): Promise<string> {
  // A copy is new bytes on the account, held to the quota like an upload.
  const over = await quotaCheck(userId, Number(src.bytes));
  if (over) throw new HttpResponseError(over);
  const dest = dedupeName(safeFileName(src.fileName), taken);
  taken.add(dest);
  const key = libraryKey(userId, dest);
  await copy(src.r2Key, key);
  await prisma.$transaction(async (tx) => {
    await tx.cutMediaObject.create({
      data: {
        userId,
        r2Key: key,
        fileName: dest,
        mime: src.mime,
        bytes: src.bytes,
        kind: "library",
        uploadState: "complete",
      },
    });
    await addUsage(tx, userId, Number(src.bytes));
  });
  return dest;
}

/** Delete a library asset with its media object, bytes, and R2 key. Returns
 * bytes freed, or null when the asset is not this user's. Shared by the delete
 * route and the storage-reclamation sweep (gc.ts).
 *
 * `tombstone` keeps the asset row behind with `deletedAt` set. That row is how
 * a delete made here reaches the iOS app, which mirrors the Camera Roll on the
 * phone: the listing names it, and the phone takes the same clip off. The
 * reclamation sweep passes nothing, so an asset it collects simply stops being
 * listed and the phone keeps the copy it shot. */
export async function deleteLibraryAssetCascade(
  userId: string,
  id: string,
  opts?: { tombstone?: boolean },
): Promise<number | null> {
  const asset = await prisma.cutLibraryAsset.findFirst({
    where: { id, userId, deletedAt: null },
  });
  if (!asset) return null;
  const obj = await prisma.cutMediaObject.findFirst({
    where: { id: asset.mediaObjectId, userId },
  });
  // The cover image is a second object under the library prefix, referenced
  // only by this row, so it leaves with it.
  const posterName = ((asset.meta ?? {}) as AssetMeta).posterFile;
  const poster = posterName
    ? await prisma.cutMediaObject.findFirst({
        where: { userId, kind: "library", fileName: posterName },
      })
    : null;
  const originalName = ((asset.meta ?? {}) as AssetMeta).originalFile;
  const original = originalName
    ? await prisma.cutMediaObject.findFirst({ where: { userId, kind: "library", fileName: originalName } })
    : null;
  // The playable copy is derived from this asset alone, so it leaves too.
  const proxyName = ((asset.meta ?? {}) as AssetMeta).proxyFile;
  const proxy = proxyName
    ? await prisma.cutMediaObject.findFirst({ where: { userId, projectId: null, kind: "proxy", fileName: proxyName } })
    : null;
  const objects = [obj, poster, original, proxy].filter((o): o is NonNullable<typeof o> => !!o);
  // An exempt object never counted toward usage, so it frees nothing.
  const freed = objects
    .filter((o) => o.uploadState === "complete" && !o.quotaExempt)
    .reduce((n, o) => n + Number(o.bytes), 0);
  await prisma.$transaction(async (tx) => {
    if (opts?.tombstone) {
      await tx.cutLibraryAsset.update({
        where: { id },
        data: { deletedAt: new Date() },
      });
    } else {
      await tx.cutLibraryAsset.delete({ where: { id } });
    }
    for (const o of objects)
      await tx.cutMediaObject.delete({ where: { id: o.id } });
    if (freed > 0) await addUsage(tx, userId, -freed);
  });
  if (objects.length > 0) await del(objects.map((o) => o.r2Key));
  return freed;
}

/** Copy one library object into a project, recording the row and usage.
 * Returns the fileName inside the project. */
async function copyIntoProject(
  userId: string,
  projectId: string,
  libFileName: string,
  taken: Set<string>,
): Promise<string> {
  const src = await libraryMediaObject(userId, libFileName);
  if (!src) throw new UserError("library_asset_not_found", "Library asset not found.");
  const over = await quotaCheck(userId, Number(src.bytes));
  if (over) throw new HttpResponseError(over);
  const dest = dedupeName(safeFileName(libFileName), taken);
  taken.add(dest);
  const key = projectMediaKey(userId, projectId, dest);
  await copy(src.r2Key, key);
  await prisma.$transaction(async (tx) => {
    await tx.cutMediaObject.create({
      data: {
        userId,
        projectId,
        r2Key: key,
        fileName: dest,
        mime: src.mime,
        bytes: src.bytes,
        kind: "media",
        uploadState: "complete",
      },
    });
    await addUsage(tx, userId, Number(src.bytes));
  });
  return dest;
}

/** Delete one library media object (row + bytes + usage), best-effort on R2. */
async function deleteLibraryObject(userId: string, fileName: string) {
  const row = await libraryMediaObject(userId, fileName);
  if (!row) return;
  await prisma.$transaction(async (tx) => {
    await tx.cutMediaObject.delete({ where: { id: row.id } });
    if (row.uploadState === "complete")
      await addUsage(tx, userId, -Number(row.bytes));
  });
  await del([row.r2Key]);
}

const libraryFolderView = (row: {
  id: string;
  name: string;
  parentId: string | null;
  createdAt: Date;
}): LibraryFolder => ({
  id: row.id,
  name: row.name,
  parentId: row.parentId,
  createdAt: row.createdAt.getTime(),
});

export const libraryCloud = {
  /** The shelf. `?deleted=1` adds the tombstoned ids — the phone asks for
   * them to mirror a delete made here onto its Camera Roll, and it is the
   * only client that does. Every other listing skips the query and the rows
   * it would carry: an account that has pruned its shelf for a season has
   * thousands of them, and the editor reads none. */
  async list(userId: string, req?: Request) {
    const wantsDeleted = !!req && new URL(req.url).searchParams.get("deleted") === "1";
    const [assetRows, deletedRows, folderRows, templateRows] = await Promise.all([
      prisma.cutLibraryAsset.findMany({
        where: { userId, deletedAt: null },
        orderBy: { createdAt: "desc" },
      }),
      wantsDeleted
        ? prisma.cutLibraryAsset.findMany({
            where: { userId, deletedAt: { not: null } },
            select: { id: true },
          })
        : Promise.resolve([]),
      prisma.cutFolder.findMany({
        where: { userId, scope: "library" },
        orderBy: { createdAt: "asc" },
      }),
      prisma.cutTemplate.findMany({
        where: { userId },
        orderBy: { createdAt: "desc" },
      }),
    ]);
    const objs = await prisma.cutMediaObject.findMany({
      where: { id: { in: assetRows.map((r) => r.mediaObjectId) } },
      select: { id: true, fileName: true },
    });
    const byId = new Map(objs.map((o) => [o.id, o]));
    const assets = assetRows
      .map((r) => {
        const obj = byId.get(r.mediaObjectId);
        return obj ? assetView(r, obj) : null;
      })
      .filter((a): a is LibraryAsset => a !== null);
    const folders: LibraryFolder[] = folderRows.map(libraryFolderView);
    const templates = templateRows.map(templateView);
    // Assets someone deleted, for a client that holds its own copy of them:
    // the iOS app deletes the matching clip on the phone.
    return Response.json({
      assets,
      folders,
      templates,
      ...(wantsDeleted ? { deletedAssetIds: deletedRows.map((r) => r.id) } : {}),
    });
  },

  /** Mint a presigned PUT for a direct-to-library upload. */
  async presign(userId: string, req: Request) {
    try {
      const body = (await req.json()) as {
        fileName?: string;
        mime?: string;
        bytes?: number;
        resume?: boolean;
      };
      if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {
        return err("fileName and bytes are required.", 400);
      }
      if (!libraryTypeOf(body.fileName)) return err(new UserError("file_type_unsupported", "Unsupported file type."), 400);
      // A resumed upload already holds its claim: the client kept the bytes
      // (the iOS app's journal) and asks for a fresh URL under the same name.
      // A claim that completed in the meantime reports done and uploads
      // nothing; a same-named row of a different size is a different file and
      // falls through to a fresh claim under a deduped name.
      if (body.resume) {
        const row = await prisma.cutMediaObject.findFirst({
          where: { userId, kind: "library", fileName: safeFileName(body.fileName) },
          orderBy: { createdAt: "desc" },
        });
        if (row && Number(row.bytes) === Math.round(body.bytes)) {
          if (row.uploadState === "complete") {
            return Response.json({ fileName: row.fileName, key: row.r2Key, done: true });
          }
          const url = await presignPut(row.r2Key, body.mime ?? "application/octet-stream", Number(row.bytes));
          return Response.json({ fileName: row.fileName, key: row.r2Key, url });
        }
      }
      const over = await quotaCheck(userId, body.bytes);
      if (over) return over;
      const fileName = dedupeName(
        safeFileName(body.fileName),
        await takenLibraryNames(userId),
      );
      const key = libraryKey(userId, fileName);
      const bytes = Math.round(body.bytes);
      const url = await presignPut(key, body.mime ?? "application/octet-stream", bytes);
      await prisma.cutMediaObject.create({
        data: {
          userId,
          r2Key: key,
          fileName,
          mime: body.mime ?? "",
          bytes: BigInt(bytes),
          kind: "library",
          uploadState: "pending",
        },
      });
      return Response.json({ fileName, key, url });
    } catch (e) {
      return caught(e, new UserError("upload_presign_failed", "Could not presign the upload."));
    }
  },

  /** Finish a library upload: verify, mark complete, register the asset. An
   * inspiration upload files itself into the ensured Inspiration folder; any
   * other folderId must name one of this user's library folders. */
  async complete(userId: string, req: Request) {
    try {
      const { key, posterKey, meta, folderId } = (await req.json()) as {
        key?: string;
        posterKey?: string;
        meta?: AssetMeta;
        folderId?: string;
      };
      if (!key) return err("key is required.", 400);
      let destFolder: string | null = null;
      if (meta?.origin === "inspiration") {
        destFolder = await ensureInspirationFolder(userId);
      } else if (folderId) {
        const folder = await prisma.cutFolder.findFirst({
          where: { id: folderId, userId, scope: "library" },
        });
        if (!folder) return err(new UserError("folder_not_found", "Folder not found."), 404);
        destFolder = folderId;
      }
      const obj = await prisma.cutMediaObject.findFirst({
        where: { userId, r2Key: key },
      });
      if (!obj) return err(new UserError("upload_unknown", "Unknown upload."), 404);
      // A retried complete (the iOS app reconciling after an interrupted
      // sync) lands on the asset it already made instead of minting a twin.
      const already = await prisma.cutLibraryAsset.findFirst({
        where: { userId, mediaObjectId: obj.id, deletedAt: null },
      });
      if (already) return Response.json(assetView(already, obj));
      const info = obj.uploadState === "complete" ? null : await head(key);
      if (obj.uploadState !== "complete" && !info)
        return err(new UserError("upload_never_arrived", "The upload never arrived."), 400);
      // A cover that came up alongside the file: its own object, finished the
      // same way, named on the asset so the delete cascade takes it too.
      const posterObj = posterKey
        ? await prisma.cutMediaObject.findFirst({
            where: { userId, r2Key: posterKey },
          })
        : null;
      const posterInfo =
        posterObj && posterObj.uploadState !== "complete"
          ? await head(posterKey!)
          : null;
      const posterFile =
        posterInfo || posterObj?.uploadState === "complete"
          ? posterObj!.fileName
          : undefined;
      const row = await prisma.$transaction(async (tx) => {
        if (posterObj && posterInfo) {
          await tx.cutMediaObject.update({
            where: { id: posterObj.id },
            data: {
              uploadState: "complete",
              bytes: BigInt(posterInfo.bytes),
              ...(posterInfo.mime ? { mime: posterInfo.mime } : {}),
            },
          });
          await addUsage(tx, userId, posterInfo.bytes);
        }
        if (info) {
          await tx.cutMediaObject.update({
            where: { id: obj.id },
            data: {
              uploadState: "complete",
              bytes: BigInt(info.bytes),
              ...(info.mime ? { mime: info.mime } : {}),
            },
          });
          await addUsage(tx, userId, info.bytes);
        }
        return tx.cutLibraryAsset.create({
          data: {
            userId,
            mediaObjectId: obj.id,
            folderId: destFolder,
            meta: {
              name: meta?.name ?? obj.fileName,
              type: meta?.type ?? libraryTypeOf(obj.fileName) ?? "video",
              duration: meta?.duration ?? 0,
              ...(meta?.width
                ? { width: meta.width, height: meta.height }
                : {}),
              ...(meta?.source ? { source: meta.source } : {}),
              ...((posterFile ?? meta?.posterFile)
                ? { posterFile: posterFile ?? meta?.posterFile }
                : {}),
              ...(meta?.origin === "camera" || meta?.origin === "inspiration"
                ? { origin: meta.origin }
                : {}),
              ...(typeof meta?.contentKey === "string" ? { contentKey: meta.contentKey } : {}),
              ...(meta?.lut ? { lut: meta.lut } : {}),
            } as unknown as Prisma.InputJsonValue,
          },
        });
      });
      return Response.json(assetView(row, obj));
    } catch (e) {
      return caught(e, new UserError("upload_complete_failed", "Could not complete the upload."));
    }
  },

  /** Copy a library asset into a project's media space. */
  async use(userId: string, req: Request) {
    try {
      const { assetId, projectId } = (await req.json()) as {
        assetId: string;
        projectId: string;
      };
      const asset = await prisma.cutLibraryAsset.findFirst({
        where: { id: assetId, userId, deletedAt: null },
      });
      if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
      const obj = await prisma.cutMediaObject.findUnique({
        where: { id: asset.mediaObjectId },
      });
      if (!obj) throw new UserError("library_asset_not_found", "Library asset not found.");
      if (!(await getProject(userId, projectId)))
        throw new UserError("project_not_found", "Project not found.");
      const fileName = await copyIntoProject(
        userId,
        projectId,
        obj.fileName,
        await takenMediaNames(userId, projectId),
      );
      return Response.json({ fileName });
    } catch (e) {
      return caught(e, new UserError("library_add_failed", "Could not add from library."));
    }
  },

  /** Copy a project media file into the shared library. */
  async save(userId: string, req: Request) {
    try {
      const { projectId, fileName, name } = (await req.json()) as {
        projectId: string;
        fileName: string;
        name?: string;
      };
      const src = await projectMediaObject(userId, projectId, fileName);
      if (!src) throw new UserError("project_media_not_found", "Media file not found in project.");
      const project = await getProject(userId, projectId);
      const docAsset = (
        project?.doc as { assets?: StoredAsset[] } | undefined
      )?.assets?.find((a) => a.fileName === fileName);
      const dest = await copyIntoLibrary(
        userId,
        src,
        await takenLibraryNames(userId),
      );
      const obj = await libraryMediaObject(userId, dest);
      if (!obj) throw new UserError("library_save_failed", "Could not save to library.");
      const row = await prisma.cutLibraryAsset.create({
        data: {
          userId,
          mediaObjectId: obj.id,
          meta: {
            name: name || fileName,
            type: docAsset?.type ?? libraryTypeOf(dest) ?? "video",
            duration: docAsset?.duration ?? 0,
            ...(docAsset?.width
              ? { width: docAsset.width, height: docAsset.height }
              : {}),
          } as unknown as Prisma.InputJsonValue,
        },
      });
      return Response.json(assetView(row, obj));
    } catch (e) {
      return caught(e, new UserError("library_save_failed", "Could not save to library."));
    }
  },

  /** Rename the item, or fill in what a row was uploaded without: the
   * duration and pixel size the page read from the file the first time it cut
   * a clip from the asset. A measured value the row already holds stays. */
  async updateMeta(userId: string, id: string, req: Request) {
    try {
      const body = (await req.json()) as {
        name?: string;
        duration?: number;
        width?: number;
        height?: number;
      };
      const asset = await prisma.cutLibraryAsset.findFirst({
        where: { id, userId, deletedAt: null },
      });
      if (!asset) throw new UserError("library_asset_not_found", "Library asset not found.");
      const obj = await prisma.cutMediaObject.findUnique({
        where: { id: asset.mediaObjectId },
      });
      if (!obj) throw new UserError("library_asset_not_found", "Library asset not found.");
      const positive = (v: unknown) =>
        typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
      const meta = { ...((asset.meta ?? {}) as AssetMeta) };
      // A rename is the name the item goes by from now on. It takes the
      // title's place too, so a clip titled before it shows the new name and
      // one not titled yet never gets a title over it.
      if (body.name !== undefined) {
        meta.name = itemName(body.name);
        meta.title = meta.name;
      }
      const duration = positive(body.duration);
      const width = positive(body.width);
      const height = positive(body.height);
      if (duration !== undefined && !positive(meta.duration)) meta.duration = duration;
      if (width !== undefined && height !== undefined && !positive(meta.width)) {
        meta.width = width;
        meta.height = height;
      }
      await prisma.cutLibraryAsset.update({
        where: { id },
        data: { meta: meta as unknown as Prisma.InputJsonValue },
      });
      return Response.json(assetView({ ...asset, meta }, obj));
    } catch (e) {
      return caught(e, new UserError("library_asset_update_failed", "Could not update the library asset."));
    }
  },

  /** Move an item — asset or template — into a folder (or `null` to ungroup). */
  async move(userId: string, req: Request) {
    try {
      const { id, folderId } = (await req.json()) as {
        id: string;
        folderId: string | null;
      };
      if (folderId) {
        const folder = await prisma.cutFolder.findFirst({
          where: { id: folderId, userId, scope: "library" },
        });
        if (!folder) throw new UserError("folder_not_found", "Folder not found.");
      }
      const asset = await prisma.cutLibraryAsset.findFirst({
        where: { id, userId, deletedAt: null },
      });
      if (asset) {
        await prisma.cutLibraryAsset.update({
          where: { id },
          data: { folderId: folderId ?? null },
        });
        return Response.json({ ok: true });
      }
      const template = await findTemplate(userId, id);
      if (!template) throw new UserError("library_item_not_found", "Library item not found.");
      const doc = template.doc as unknown as TemplateDoc;
      await prisma.cutTemplate.update({
        where: { id },
        data: { doc: asJson({ ...doc, folderId: folderId ?? null }) },
      });
      return Response.json({ ok: true });
    } catch (e) {
      return caught(e, new UserError("library_item_move_failed", "Could not move item."));
    }
  },

  /** Queue the playable copy of a library video the browser cannot decode.
   * A row that already names one answers with itself, and a job already on
   * its way answers with that job. `compat` asks for the compat proxy
   * (lib/proxyNames.ts), which an audio file can take as well. */
  async proxy(userId: string, id: string, req: Request) {
    try {
      const { compat: asked } = (await req.json().catch(() => ({}))) as { compat?: unknown };
      const compat = compatCoverIn(asked);
      if (asked !== undefined && !compat) return err("compat is audio or video.", 400);
      const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId, deletedAt: null } });
      if (!asset) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
      const obj = await prisma.cutMediaObject.findFirst({ where: { id: asset.mediaObjectId, userId } });
      if (!obj) return err(new UserError("library_asset_not_found", "Library asset not found."), 404);
      const view = assetView(asset, obj);
      const takes = view.type === "video" || (compat === "audio" && view.type === "audio");
      if (!takes) return err(new UserError("playable_copy_video_only", "Only a video takes a playable copy."), 400);
      if (view.proxyFile && (!compat || compatCovers(view.proxyFile, compat))) return Response.json(view);
      const jobId = libraryProxyJobId(id);
      const existing = await prisma.cutRenderJob.findFirst({ where: { id: jobId, userId } });
      if (existing && (existing.state === "queued" || existing.state === "running")) {
        wakeRenderWorker();
        return Response.json({ jobId });
      }
      const capped = await renderJobCheck(userId);
      if (capped) return capped;
      const spec = { target: "library", assetId: id, ...(compat ? { compat } : {}) } as Prisma.InputJsonValue;
      if (existing) {
        // A finished or failed run goes again under the same id.
        await prisma.cutRenderJob.updateMany({
          where: { id: jobId, userId },
          data: { state: "queued", progress: 0, error: null, claimedAt: null, spec },
        });
      } else {
        await prisma.cutRenderJob.create({ data: { id: jobId, userId, projectId: null, kind: "proxy", spec } });
      }
      wakeRenderWorker();
      return Response.json({ jobId });
    } catch (e) {
      return caught(e, new UserError("playable_copy_make_failed", "Could not make the playable copy."));
    }
  },

  async remove(userId: string, id: string) {
    try {
      // Idempotent: a delete replayed from the iOS app's journal after the
      // asset already left reports done, so the tombstone clears.
      await deleteLibraryAssetCascade(userId, id, { tombstone: true });
      return Response.json({ ok: true });
    } catch (e) {
      return caught(e, new UserError("library_delete_failed", "Could not delete."));
    }
  },

  /** Signed edge URLs for library files, the library's twin of the project
   * media batch (media.ts presignGetBatch). Everything that reads bytes to
   * decode them — a card's frames, a clip dragged onto the timeline — reads
   * the object directly instead of through serveMedia's redirect, which is
   * what puts those reads on the chunk cache and the edge cache. Library files
   * are written once, so the URLs carry no version.
   *
   * A name with no completed object is left out; the client falls back to the
   * route for it. */
  async presignGetBatch(userId: string, req: Request) {
    try {
      const { files } = (await req.json()) as { files?: string[] };
      if (!Array.isArray(files)) return err("files is required.", 400);
      if (files.length > PRESIGN_GET_BATCH_MAX) return err("Too many files.", 400);
      const wanted = [
        ...new Set(
          files.flatMap((f) => (typeof f === "string" ? (storableFileName(f) ?? []) : [])),
        ),
      ];
      const rows = wanted.length
        ? await prisma.cutMediaObject.findMany({
            where: {
              userId,
              ...LIBRARY_PREFIX_OBJECTS,
              uploadState: "complete",
              fileName: { in: wanted },
            },
            select: { fileName: true },
          })
        : [];
      return Response.json({
        urls: rows.map((r) => ({
          fileName: r.fileName,
          url: mediaObjectUrl(libraryKey(userId, r.fileName)),
        })),
        expiresIn: mediaUrlLifetime(),
      });
    } catch (e) {
      return caught(e, new UserError("library_urls_sign_failed", "Could not sign the library URLs."));
    }
  },

  async serveMedia(userId: string, file: string, download = false) {
    try {
      const fileName = decodeFileParam(file);
      // Library files are written once — an import lands under a fresh name —
      // so the redirect itself is cacheable and a revisit paints every poster
      // from the browser's cache.
      return redirect(
        mediaObjectUrl(
          libraryKey(userId, fileName),
          download ? { downloadName: fileName } : undefined,
        ),
        MEDIA_REDIRECT_HEADERS,
      );
    } catch (e) {
      return caught(e, "Bad request.", 400);
    }
  },

  // --- Folders (scope "library") ---

  async createFolder(userId: string, req: Request) {
    try {
      const { name, parentId } = (await req.json()) as {
        name?: string;
        parentId?: string | null;
      };
      const trimmed = (name ?? "").trim();
      if (!trimmed) throw new UserError("folder_name_required", "Folder name required.");
      const folders = await prisma.cutFolder.findMany({
        where: { userId, scope: "library" },
        select: { id: true, parentId: true },
      });
      const row = await prisma.cutFolder.create({
        data: {
          userId,
          name: trimmed.slice(0, 80),
          scope: "library",
          parentId: resolveParent(folders, "", parentId),
        },
      });
      return Response.json(libraryFolderView(row));
    } catch (e) {
      return caught(e, new UserError("folder_create_failed", "Could not create folder."));
    }
  },

  /** Rename a folder, file it under another (null for the top level), or
   * both; a key left out keeps what the folder has. */
  async updateFolder(userId: string, id: string, req: Request) {
    try {
      const { name, parentId } = (await req.json()) as {
        name?: string;
        parentId?: string | null;
      };
      const trimmed = name?.trim();
      if (name !== undefined && !trimmed) throw new UserError("folder_name_required", "Folder name required.");
      const folders = await prisma.cutFolder.findMany({
        where: { userId, scope: "library" },
        select: { id: true, parentId: true },
      });
      if (!folders.some((f) => f.id === id)) throw new UserError("folder_not_found", "Folder not found.");
      const updated = await prisma.cutFolder.update({
        where: { id },
        data: {
          ...(trimmed ? { name: trimmed.slice(0, 80) } : {}),
          ...(parentId !== undefined
            ? { parentId: resolveParent(folders, id, parentId) }
            : {}),
        },
      });
      return Response.json(libraryFolderView(updated));
    } catch (e) {
      return caught(e, new UserError("folder_update_failed", "Could not update folder."));
    }
  },

  /** Delete a folder and everything in it: the folders filed under it,
   * however deep, and every asset and template they hold, each through the
   * cascade its own delete runs — an asset leaves a tombstone for the phone
   * like any other delete. A camera clip lives in Camera Roll whatever folder
   * it is filed under, so it stays, unfiled. The items go first and the
   * folders last, so a run that stops partway leaves the rest where a retry
   * finds it. */
  async deleteFolder(userId: string, id: string) {
    try {
      const folders = await prisma.cutFolder.findMany({
        where: { userId, scope: "library" },
        select: { id: true, parentId: true },
      });
      if (!folders.some((f) => f.id === id)) return Response.json({ ok: true });
      const tree = subtreeOf(folders, id);
      const assets = await prisma.cutLibraryAsset.findMany({
        where: { userId, folderId: { in: tree }, deletedAt: null },
        select: { id: true, meta: true },
      });
      const isCamera = (a: { meta: unknown }) => ((a.meta ?? {}) as AssetMeta).origin === "camera";
      for (const a of assets)
        if (!isCamera(a)) await deleteLibraryAssetCascade(userId, a.id, { tombstone: true });
      await prisma.cutLibraryAsset.updateMany({
        where: { userId, id: { in: assets.filter(isCamera).map((a) => a.id) } },
        data: { folderId: null },
      });
      const templates = await prisma.cutTemplate.findMany({ where: { userId } });
      for (const t of templates) {
        const folderId = (t.doc as unknown as TemplateDoc).folderId;
        if (folderId && tree.includes(folderId)) await deleteTemplateCascade(userId, t);
      }
      await notesCloud.deleteLibraryFolderNotes(userId, "cloud", tree);
      await prisma.cutFolder.deleteMany({
        where: { userId, scope: "library", id: { in: tree } },
      });
      return Response.json({ ok: true });
    } catch (e) {
      return caught(e, new UserError("folder_delete_failed", "Could not delete folder."));
    }
  },

  // --- Templates ---

  /** Save a timeline selection as a by-reference template: each source file is
   * copied into the library privately, then the edit is stored. */
  async saveTemplate(userId: string, req: Request) {
    try {
      const { projectId, ...input } = (await req.json()) as {
        projectId: string;
      } & TemplateInput;
      if (!(await getProject(userId, projectId)))
        throw new UserError("project_not_found", "Project not found.");
      if (templateEmpty(input)) throw new UserError("template_nothing_to_save", "Nothing to save.");
      // Every source is resolved and the whole batch checked against the quota
      // before the first copy, so the wall is met with nothing written; a
      // copy that still fails takes the ones before it back with it, since a
      // library object no template names is one nothing could ever find.
      const sources = await Promise.all(
        input.media.map(async (m) => {
          const src = await projectMediaObject(userId, projectId, m.fileName);
          if (!src) throw new UserError("project_media_not_found", "Media file not found in project.");
          return { m, src };
        }),
      );
      const over = await quotaCheck(
        userId,
        sources.reduce((sum, { src }) => sum + Number(src.bytes), 0),
      );
      if (over) throw new HttpResponseError(over);
      const taken = await takenLibraryNames(userId);
      const media: TemplateMedia[] = [];
      try {
        for (const { m, src } of sources) {
          const dest = await copyIntoLibrary(userId, src, taken);
          media.push({
            fileName: dest,
            name: m.name,
            type: m.type,
            duration: m.duration,
            width: m.width,
            height: m.height,
            ...(m.soundFrom ? { soundFrom: m.soundFrom } : {}),
          });
        }
      } catch (e) {
        for (const done of media) await deleteLibraryObject(userId, done.fileName).catch(() => {});
        throw e;
      }
      const doc: TemplateDoc = {
        folderId: null,
        duration: input.duration,
        media,
        layers: input.layers ?? [],
        audio: input.audio ?? [],
        texts: input.texts ?? [],
        cues: input.cues ?? [],
        ...(input.sound ? { sound: input.sound } : {}),
        ...templateExtras(input),
      };
      const row = await prisma.cutTemplate.create({
        data: {
          userId,
          name: (input.name || "Template").trim().slice(0, 80),
          doc: asJson(doc),
        },
      });
      return Response.json(templateView(row));
    } catch (e) {
      return caught(e, new UserError("template_save_failed", "Could not save the template."));
    }
  },

  /** Take in a template carried off another shelf: its media are presigned
   * objects already in R2, named here in the doc's own order. */
  async importTemplate(userId: string, req: Request) {
    try {
      const { keys, ...input } = (await req.json()) as TemplateInput & {
        keys?: string[];
        folderId?: string | null;
      };
      if (templateEmpty(input)) throw new UserError("template_nothing_to_add", "Nothing to add.");
      const media: TemplateMedia[] = [];
      for (const [i, m] of (input.media ?? []).entries()) {
        const key = keys?.[i];
        const obj = key
          ? await prisma.cutMediaObject.findFirst({
              where: { userId, r2Key: key },
            })
          : null;
        if (!obj) throw new UserError("template_media_missing", "Template media missing.");
        if (obj.uploadState !== "complete") {
          const info = await head(key!);
          if (!info) throw new UserError("upload_never_arrived", "The upload never arrived.");
          await prisma.$transaction(async (tx) => {
            await tx.cutMediaObject.update({
              where: { id: obj.id },
              data: {
                uploadState: "complete",
                bytes: BigInt(info.bytes),
                ...(info.mime ? { mime: info.mime } : {}),
              },
            });
            await addUsage(tx, userId, info.bytes);
          });
        }
        media.push({ ...m, fileName: obj.fileName });
      }
      const doc: TemplateDoc = {
        folderId: input.folderId ?? null,
        duration: input.duration,
        media,
        layers: input.layers ?? [],
        audio: input.audio ?? [],
        texts: input.texts ?? [],
        cues: input.cues ?? [],
        ...(input.sound ? { sound: input.sound } : {}),
        ...templateExtras(input),
      };
      const row = await prisma.cutTemplate.create({
        data: {
          userId,
          name: (input.name || "Template").trim().slice(0, 80),
          doc: asJson(doc),
        },
      });
      return Response.json(templateView(row));
    } catch (e) {
      return caught(e, new UserError("template_add_failed", "Could not add the template."));
    }
  },

  /** Materialize a template into a project: copy its media in and hand back the
   * project file names (in template media order) plus the stored edit. */
  async useTemplate(userId: string, id: string, req: Request) {
    try {
      const { projectId } = (await req.json()) as { projectId: string };
      if (!(await getProject(userId, projectId)))
        throw new UserError("project_not_found", "Project not found.");
      const row = await findTemplate(userId, id);
      if (!row) throw new UserError("template_not_found", "Template not found.");
      const template = templateView(row);
      // The whole batch against the quota before the first copy; a project
      // copy that still fails is unreferenced project media, which the sweep
      // reclaims.
      let incoming = 0;
      for (const m of template.media) {
        const src = await libraryMediaObject(userId, m.fileName);
        if (!src) throw new UserError("library_asset_not_found", "Library asset not found.");
        incoming += Number(src.bytes);
      }
      const over = await quotaCheck(userId, incoming);
      if (over) throw new HttpResponseError(over);
      const taken = await takenMediaNames(userId, projectId);
      const media: TemplateMedia[] = [];
      for (const m of template.media) {
        const dest = await copyIntoProject(
          userId,
          projectId,
          m.fileName,
          taken,
        );
        media.push({ ...m, fileName: dest });
      }
      return Response.json({ template, media });
    } catch (e) {
      return caught(e, new UserError("template_add_failed", "Could not add the template."));
    }
  },

  /** Append one project media file to a template as a part at its end. */
  async addToTemplate(userId: string, id: string, req: Request) {
    try {
      const { projectId, ...input } = (await req.json()) as {
        projectId: string;
        media: TemplateMedia;
        layer?: Omit<TemplateLayer, "media" | "start">;
        audio?: Omit<TemplateAudio, "media" | "start">;
        extend: number;
      };
      const row = await findTemplate(userId, id);
      if (!row) throw new UserError("template_not_found", "Template not found.");
      const src = await projectMediaObject(
        userId,
        projectId,
        input.media.fileName,
      );
      if (!src) throw new UserError("project_media_not_found", "Media file not found in project.");
      const dest = await copyIntoLibrary(
        userId,
        src,
        await takenLibraryNames(userId),
      );
      const doc = row.doc as unknown as TemplateDoc;
      const mi = (doc.media ?? []).length;
      const next: TemplateDoc = {
        ...doc,
        media: [...(doc.media ?? []), { ...input.media, fileName: dest }],
        audio: input.audio
          ? [
              ...(doc.audio ?? []),
              { ...input.audio, media: mi, start: doc.duration },
            ]
          : (doc.audio ?? []),
        layers:
          !input.audio && input.layer
            ? [
                ...(doc.layers ?? []),
                { ...input.layer, media: mi, start: doc.duration },
              ]
            : (doc.layers ?? []),
        duration: doc.duration + input.extend,
      };
      const updated = await prisma.cutTemplate.update({
        where: { id },
        data: { doc: asJson(next) },
      });
      return Response.json(templateView(updated));
    } catch (e) {
      return caught(e, new UserError("template_append_failed", "Could not add to the template."));
    }
  },

  async renameTemplate(userId: string, id: string, req: Request) {
    try {
      const { name } = (await req.json()) as { name?: string };
      const next = itemName(name);
      const row = await findTemplate(userId, id);
      if (!row) throw new UserError("template_not_found", "Template not found.");
      const updated = await prisma.cutTemplate.update({
        where: { id },
        data: { name: next },
      });
      return Response.json(templateView(updated));
    } catch (e) {
      return caught(e, new UserError("template_rename_failed", "Could not rename the template."));
    }
  },

  async removeTemplate(userId: string, id: string) {
    try {
      const row = await findTemplate(userId, id);
      if (row) await deleteTemplateCascade(userId, row);
      return Response.json({ ok: true });
    } catch (e) {
      return caught(e, new UserError("template_delete_failed", "Could not delete the template."));
    }
  },
};

/** Delete a template row with its media copies, which are private to it. */
async function deleteTemplateCascade(
  userId: string,
  row: NonNullable<Awaited<ReturnType<typeof findTemplate>>>,
) {
  await prisma.cutTemplate.delete({ where: { id: row.id } });
  const doc = row.doc as unknown as TemplateDoc;
  for (const m of doc.media ?? []) await deleteLibraryObject(userId, m.fileName);
}

/** The folder a new account starts with, so the Library shows that it takes
 * font files before anyone has dropped one in. Derived from the user id, so a
 * retried signup lands on the same row; an ordinary folder otherwise, free to
 * rename, empty, or delete. */
export const fontsFolderId = (userId: string) => `fonts-${userId}`;

/** The Inspiration folder, created the first time an inspiration item lands.
 * Its id is derived (util.inspirationFolderId), so every writer converges on
 * one row; an ordinary folder otherwise, free to rename or delete. */
export async function ensureInspirationFolder(userId: string): Promise<string> {
  const id = inspirationFolderId(userId);
  await prisma.cutFolder.upsert({
    where: { id },
    create: { id, userId, name: "Inspiration", scope: "library" },
    update: {},
  });
  return id;
}

export async function seedFontsFolder(userId: string): Promise<void> {
  const id = fontsFolderId(userId);
  if (await prisma.cutFolder.findUnique({ where: { id } })) return;
  await prisma.cutFolder.create({
    data: { id, userId, name: "Fonts", scope: "library" },
  });
}