Open source CapCut alternative.
TypeScript
feat(site): Cut library thumbnails, folders, drag-drop & URL import
David Le3a6ff979ad1c
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex be85b48e..e9e07465 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -1,7 +1,22 @@"use client";import { useEffect, useRef, useState } from "react";-import { Film, FolderOpen, Loader2, Music, Plus, Trash2, Upload } from "lucide-react";+import {+ Check,+ Film,+ Folder,+ FolderOpen,+ FolderPlus,+ Link as LinkIcon,+ Loader2,+ MoreHorizontal,+ Music,+ Pencil,+ Plus,+ Trash2,+ Upload,+ X,+} from "lucide-react";import { Button } from "@/components/ui/button";import {AlertDialog,@@ -14,22 +29,52 @@ import {AlertDialogTitle,} from "@/components/ui/alert-dialog";import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { clearAssetDrag, setLibraryDragData } from "@/cut/lib/assetDrag";+import {+ createLibraryFolder,deleteFromLibrary,+ deleteLibraryFolder,fetchLibrary,+ importUrlToLibrary,libraryMediaUrl,+ libraryThumbUrl,+ moveLibraryAsset,+ renameLibraryFolder,uploadToLibrary,type LibraryAsset,+ type LibraryFolder,} from "@/cut/lib/library";import { formatTime } from "@/cut/lib/time";+import { cn } from "@/lib/utils";export function LibraryView() {const [assets, setAssets] = useState<LibraryAsset[] | null>(null);+ const [folders, setFolders] = useState<LibraryFolder[]>([]);+ const [activeFolder, setActiveFolder] = useState<string | null>(null); // null = Allconst [uploading, setUploading] = useState(0);+ const [importing, setImporting] = useState(false);+ const [url, setUrl] = useState("");+ const [urlError, setUrlError] = useState<string | null>(null);const [deleting, setDeleting] = useState<LibraryAsset | null>(null);const inputRef = useRef<HTMLInputElement>(null);+ const reload = () =>+ fetchLibrary()+ .then((d) => {+ setAssets(d.assets);+ setFolders(d.folders);+ })+ .catch(() => setAssets([]));+useEffect(() => {- void fetchLibrary().then(setAssets).catch(() => setAssets([]));+ void reload();}, []);const upload = async (files: FileList) => {@@ -38,6 +83,10 @@ export function LibraryView() {for (const file of list) {try {const asset = await uploadToLibrary(file);+ if (activeFolder) {+ await moveLibraryAsset(asset.id, activeFolder).catch(() => {});+ asset.folderId = activeFolder;+ }setAssets((prev) => [asset, ...(prev ?? [])]);} catch {// Skip unreadable files; the rest of the batch still uploads.@@ -47,16 +96,52 @@ export function LibraryView() {}};+ const importUrl = async () => {+ const value = url.trim();+ if (!value || importing) return;+ setImporting(true);+ setUrlError(null);+ try {+ const asset = await importUrlToLibrary(value);+ if (activeFolder) {+ await moveLibraryAsset(asset.id, activeFolder).catch(() => {});+ asset.folderId = activeFolder;+ }+ setAssets((prev) => [asset, ...(prev ?? [])]);+ setUrl("");+ } catch (e) {+ setUrlError(e instanceof Error ? e.message : "Could not import that URL.");+ } finally {+ setImporting(false);+ }+ };+const remove = async () => {if (!deleting) return;- await deleteFromLibrary(deleting.id);- setAssets((prev) => (prev ?? []).filter((a) => a.id !== deleting.id));+ const id = deleting.id;setDeleting(null);+ setAssets((prev) => (prev ?? []).filter((a) => a.id !== id));+ try {+ await deleteFromLibrary(id);+ } catch {+ void reload();+ }};+ const move = async (assetId: string, folderId: string | null) => {+ setAssets((prev) =>+ (prev ?? []).map((a) => (a.id === assetId ? { ...a, folderId } : a))+ );+ await moveLibraryAsset(assetId, folderId).catch(() => void reload());+ };++ const shown = (assets ?? []).filter((a) =>+ activeFolder === null ? true : (a.folderId ?? null) === activeFolder+ );+return (<div className="mx-auto w-full max-w-6xl px-10 py-9">- <div className="mb-6 flex items-center justify-between">+ <div className="mb-5 flex items-center justify-between gap-4"><div><h1 className="text-lg font-semibold tracking-tight">Library</h1><p className="mt-0.5 text-sm text-muted-foreground">@@ -79,18 +164,66 @@ export function LibraryView() {/></div>+ {/* Import from a URL (TikTok, YouTube, Instagram, …). */}+ <div className="mb-5 flex flex-col gap-1.5">+ <div className="flex items-center gap-2">+ <div className="relative flex-1">+ <LinkIcon className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={url}+ placeholder="Paste a TikTok, YouTube, or Instagram link…"+ className="pl-8"+ onChange={(e) => setUrl(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") void importUrl();+ }}+ />+ </div>+ <Button variant="outline" disabled={!url.trim() || importing} onClick={() => void importUrl()}>+ {importing ? <Loader2 className="animate-spin" /> : <LinkIcon />} Import+ </Button>+ </div>+ {urlError && <p className="text-xs text-destructive">{urlError}</p>}+ </div>++ <FolderBar+ folders={folders}+ active={activeFolder}+ counts={countByFolder(assets ?? [])}+ onSelect={setActiveFolder}+ onCreate={async (name) => {+ const f = await createLibraryFolder(name);+ setFolders((prev) => [...prev, f]);+ setActiveFolder(f.id);+ }}+ onRename={async (id, name) => {+ setFolders((prev) => prev.map((f) => (f.id === id ? { ...f, name } : f)));+ await renameLibraryFolder(id, name).catch(() => void reload());+ }}+ onDelete={async (id) => {+ setFolders((prev) => prev.filter((f) => f.id !== id));+ setAssets((prev) =>+ (prev ?? []).map((a) => (a.folderId === id ? { ...a, folderId: null } : a))+ );+ if (activeFolder === id) setActiveFolder(null);+ await deleteLibraryFolder(id).catch(() => void reload());+ }}+ />+{assets === null ? (<div className="grid place-items-center py-24 text-muted-foreground"><Loader2 className="size-5 animate-spin" /></div>- ) : assets.length === 0 && uploading === 0 ? (+ ) : shown.length === 0 && uploading === 0 ? (<buttonclassName="grid w-full cursor-pointer place-items-center rounded-2xl border-2 border-dashed border-border py-24 transition-colors hover:border-primary/40"onClick={() => inputRef.current?.click()}><div className="flex flex-col items-center gap-3 text-center"><FolderOpen className="size-8 text-muted-foreground" />- <div className="text-base font-medium">Your library is empty</div>+ <div className="text-base font-medium">+ {activeFolder ? "This folder is empty" : "Your library is empty"}+ </div><p className="max-w-xs text-sm text-muted-foreground">Add intros, outros, logo stings, and music once — reuse them inevery cut.@@ -99,8 +232,14 @@ export function LibraryView() {</button>) : (<div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-4">- {assets.map((a) => (- <LibraryCard key={a.id} asset={a} onDelete={() => setDeleting(a)} />+ {shown.map((a) => (+ <LibraryCard+ key={a.id}+ asset={a}+ folders={folders}+ onDelete={() => setDeleting(a)}+ onMove={(folderId) => void move(a.id, folderId)}+ />))}{uploading > 0 && (<div className="flex aspect-square flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-input text-xs text-muted-foreground">@@ -137,21 +276,191 @@ export function LibraryView() {);}+function countByFolder(assets: LibraryAsset[]): Map<string | null, number> {+ const m = new Map<string | null, number>();+ for (const a of assets) {+ const key = a.folderId ?? null;+ m.set(key, (m.get(key) ?? 0) + 1);+ }+ return m;+}++/** Folder chips: All + each folder, with create/rename/delete inline. */+function FolderBar({+ folders,+ active,+ counts,+ onSelect,+ onCreate,+ onRename,+ onDelete,+}: {+ folders: LibraryFolder[];+ active: string | null;+ counts: Map<string | null, number>;+ onSelect: (id: string | null) => void;+ onCreate: (name: string) => void | Promise<void>;+ onRename: (id: string, name: string) => void | Promise<void>;+ onDelete: (id: string) => void | Promise<void>;+}) {+ const [creating, setCreating] = useState(false);+ const [editingId, setEditingId] = useState<string | null>(null);+ const [draft, setDraft] = useState("");++ const chip = (label: string, count: number | undefined, selected: boolean, onClick: () => void) => (+ <button+ className={cn(+ "flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors",+ selected+ ? "border-primary bg-primary/10 text-primary"+ : "border-border text-muted-foreground hover:text-foreground"+ )}+ onClick={onClick}+ >+ {label}+ {count ? <span className="tabular-nums opacity-60">{count}</span> : null}+ </button>+ );++ return (+ <div className="mb-5 flex flex-wrap items-center gap-2">+ {chip("All", undefined, active === null, () => onSelect(null))}+ {folders.map((f) =>+ editingId === f.id ? (+ <span key={f.id} className="flex items-center gap-1">+ <Input+ autoFocus+ value={draft}+ className="h-7 w-32 text-xs"+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && draft.trim()) {+ void onRename(f.id, draft.trim());+ setEditingId(null);+ } else if (e.key === "Escape") setEditingId(null);+ }}+ />+ <Button+ size="icon-sm"+ variant="ghost"+ onClick={() => {+ if (draft.trim()) void onRename(f.id, draft.trim());+ setEditingId(null);+ }}+ >+ <Check />+ </Button>+ </span>+ ) : (+ <span key={f.id} className="group/chip flex items-center gap-0.5">+ <button+ className={cn(+ "flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors",+ active === f.id+ ? "border-primary bg-primary/10 text-primary"+ : "border-border text-muted-foreground hover:text-foreground"+ )}+ onClick={() => onSelect(f.id)}+ onDoubleClick={() => {+ setDraft(f.name);+ setEditingId(f.id);+ }}+ >+ <Folder className="size-3" />+ {f.name}+ {counts.get(f.id) ? (+ <span className="tabular-nums opacity-60">{counts.get(f.id)}</span>+ ) : null}+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Folder options"+ className="size-6 text-muted-foreground opacity-0 group-hover/chip:opacity-100"+ />+ }+ >+ <MoreHorizontal className="size-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ <DropdownMenuItem+ onClick={() => {+ setDraft(f.name);+ setEditingId(f.id);+ }}+ >+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={() => void onDelete(f.id)}>+ <Trash2 /> Delete folder+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </span>+ )+ )}++ {creating ? (+ <span className="flex items-center gap-1">+ <Input+ autoFocus+ value={draft}+ placeholder="Folder name"+ className="h-7 w-32 text-xs"+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && draft.trim()) {+ void onCreate(draft.trim());+ setDraft("");+ setCreating(false);+ } else if (e.key === "Escape") setCreating(false);+ }}+ />+ <Button size="icon-sm" variant="ghost" onClick={() => setCreating(false)}>+ <X />+ </Button>+ </span>+ ) : (+ <button+ className="flex shrink-0 items-center gap-1 rounded-full border border-dashed border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground"+ onClick={() => {+ setDraft("");+ setCreating(true);+ }}+ >+ <FolderPlus className="size-3.5" /> New folder+ </button>+ )}+ </div>+ );+}+export function LibraryCard({asset: a,+ folders,onDelete,onUse,+ onMove,}: {asset: LibraryAsset;+ folders?: LibraryFolder[];onDelete?: () => void;onUse?: () => void;+ onMove?: (folderId: string | null) => void;}) {const videoRef = useRef<HTMLVideoElement>(null);const [hovering, setHovering] = useState(false);return (<div- className="group flex cursor-pointer flex-col gap-1.5"+ className="group flex flex-col gap-1.5"+ draggable+ onDragStart={(e) => setLibraryDragData(e, a)}+ onDragEnd={clearAssetDrag}onMouseEnter={() => {if (a.type === "video") setHovering(true);}}@@ -159,16 +468,15 @@ export function LibraryCard({videoRef.current?.pause();setHovering(false);}}- onClick={onUse}>- <div className="relative aspect-square overflow-hidden rounded-xl border border-border bg-muted transition-shadow group-hover:shadow-[0_4px_20px_rgba(0,0,0,0.1)]">+ <div className="relative aspect-square cursor-grab overflow-hidden rounded-xl border border-border bg-muted transition-shadow group-hover:shadow-[0_4px_20px_rgba(0,0,0,0.1)] active:cursor-grabbing">{a.type === "video" ? (<>- <video- src={`${libraryMediaUrl(a.fileName)}#t=0.1`}- muted- playsInline- preload="metadata"+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={libraryThumbUrl(a.id)}+ alt=""+ loading="lazy"className="size-full object-cover"/>{hovering && (@@ -192,24 +500,62 @@ export function LibraryCard({{formatTime(a.duration)}</span>{onUse && (- <span className="absolute top-1.5 left-1.5 grid size-5 scale-75 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 transition-all group-hover:scale-100 group-hover:opacity-100">- <Plus className="size-3" />- </span>- )}- {onDelete && (- <Button- variant="ghost"- size="icon-xs"- aria-label="Remove from library"- className="absolute top-1.5 right-1.5 bg-black/40 text-white opacity-0 group-hover:opacity-100 hover:bg-black/60 hover:text-white"+ <button+ aria-label="Add to timeline"+ title="Add to timeline"+ className="absolute top-1.5 left-1.5 grid size-6 place-items-center rounded-full bg-primary text-primary-foreground opacity-0 shadow transition-all group-hover:opacity-100 hover:scale-110"onClick={(e) => {e.stopPropagation();- onDelete();+ onUse();}}>- <Trash2 />- </Button>+ <Plus className="size-3.5" />+ </button>)}+ <div className="absolute top-1.5 right-1.5 flex gap-1 opacity-0 group-hover:opacity-100">+ {onMove && folders && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Move to folder"+ title="Move to folder"+ className="bg-black/40 text-white hover:bg-black/60 hover:text-white"+ />+ }+ >+ <Folder />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => onMove(null)}>+ {(a.folderId ?? null) === null && <Check />} No folder+ </DropdownMenuItem>+ {folders.length > 0 && <DropdownMenuSeparator />}+ {folders.map((f) => (+ <DropdownMenuItem key={f.id} onClick={() => onMove(f.id)}>+ {a.folderId === f.id && <Check />} {f.name}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ {onDelete && (+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Remove from library"+ className="bg-black/40 text-white hover:bg-black/60 hover:text-white"+ onClick={(e) => {+ e.stopPropagation();+ onDelete();+ }}+ >+ <Trash2 />+ </Button>+ )}+ </div>{a.type === "video" && !hovering && (<span className="absolute bottom-1.5 left-1.5 text-white/90"><Film className="size-3.5 drop-shadow" />diff --git a/site/src/cut/lib/assetDrag.ts b/site/src/cut/lib/assetDrag.tsindex df7799da..fe27bc8a 100644--- a/site/src/cut/lib/assetDrag.ts+++ b/site/src/cut/lib/assetDrag.ts@@ -1,6 +1,7 @@"use client";import type React from "react";+import type { LibraryAsset } from "./library";/** Internal HTML5 drag payload for project media assets. The custom MIME* keeps these drags invisible to the window-level OS-file import overlay,@@ -23,9 +24,38 @@ export function draggingAssetId(): string | null {return inFlightAssetId;}-/** Clear the in-flight id; call on `dragend` and after a drop. */+/** A library asset dragged from the library panel. Unlike a project asset it is+ * not in the project yet, so it carries its own MIME and a minimal shape the+ * timeline uses to size the drop preview before the copy-into-project happens. */+export const LIBRARY_MIME = "application/x-cut-library";++let inFlightLibrary: LibraryAsset | null = null;++export function setLibraryDragData(e: React.DragEvent, asset: LibraryAsset) {+ e.dataTransfer.setData(LIBRARY_MIME, asset.id);+ e.dataTransfer.effectAllowed = "copy";+ inFlightLibrary = asset;+}++export function draggingLibrary(): LibraryAsset | null {+ return inFlightLibrary;+}++export function hasLibraryDrag(e: React.DragEvent | DragEvent): boolean {+ const dt = "dataTransfer" in e ? e.dataTransfer : null;+ return !!dt && Array.from(dt.types).includes(LIBRARY_MIME);+}++export function draggedLibraryId(e: React.DragEvent | DragEvent): string | null {+ const dt = "dataTransfer" in e ? e.dataTransfer : null;+ if (!dt || !Array.from(dt.types).includes(LIBRARY_MIME)) return null;+ return dt.getData(LIBRARY_MIME) || null;+}++/** Clear the in-flight ids; call on `dragend` and after a drop. */export function clearAssetDrag() {inFlightAssetId = null;+ inFlightLibrary = null;}export function draggedAssetId(e: React.DragEvent | DragEvent): string | null {diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 9c102639..879938f2 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -5,6 +5,13 @@ import { useEditor } from "./store";import type { MediaAsset } from "./types";import { mediaUrl } from "./types";+export interface LibrarySource {+ url: string;+ title?: string;+ uploader?: string;+ uploadDate?: string;+}+export interface LibraryAsset {id: string;fileName: string;@@ -14,15 +21,77 @@ export interface LibraryAsset {width?: number;height?: number;addedAt: number;+ folderId?: string | null;+ source?: LibrarySource;+}++export interface LibraryFolder {+ id: string;+ name: string;+ createdAt: number;+}++export interface LibraryData {+ assets: LibraryAsset[];+ folders: LibraryFolder[];}export const libraryMediaUrl = (fileName: string) =>apiUrl(`/api/cut/library/media/${encodeURIComponent(fileName)}`);-export async function fetchLibrary(): Promise<LibraryAsset[]> {+/** A sharp, server-generated poster for a library video. */+export const libraryThumbUrl = (id: string) =>+ apiUrl(`/api/cut/library/thumb/${encodeURIComponent(id)}`);++export async function fetchLibrary(): Promise<LibraryData> {const res = await apiFetch("/api/cut/library");if (!res.ok) throw new Error("Could not load the library.");- return (await res.json()) as LibraryAsset[];+ return (await res.json()) as LibraryData;+}++export async function importUrlToLibrary(url: string): Promise<LibraryAsset> {+ const res = await apiFetch("/api/cut/library/import-url", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ url }),+ });+ const body = (await res.json()) as LibraryAsset & { error?: string };+ if (!res.ok) throw new Error(body.error ?? "Could not import that URL.");+ return body;+}++export async function createLibraryFolder(name: string): Promise<LibraryFolder> {+ const res = await apiFetch("/api/cut/library/folders", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ });+ const body = (await res.json()) as LibraryFolder & { error?: string };+ if (!res.ok) throw new Error(body.error ?? "Could not create folder.");+ return body;+}++export async function renameLibraryFolder(id: string, name: string): Promise<void> {+ const res = await apiFetch(`/api/cut/library/folders/${id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name }),+ });+ if (!res.ok) throw new Error("Could not rename folder.");+}++export async function deleteLibraryFolder(id: string): Promise<void> {+ const res = await apiFetch(`/api/cut/library/folders/${id}`, { method: "DELETE" });+ if (!res.ok) throw new Error("Could not delete folder.");+}++export async function moveLibraryAsset(assetId: string, folderId: string | null): Promise<void> {+ const res = await apiFetch("/api/cut/library/move", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ assetId, folderId }),+ });+ if (!res.ok) throw new Error("Could not move asset.");}export async function uploadToLibrary(file: File): Promise<LibraryAsset> {@@ -39,8 +108,9 @@ export async function deleteFromLibrary(id: string) {if (!res.ok) throw new Error("Could not delete.");}-/** Copy a library asset into the open project and put it on the timeline. */-export async function addLibraryAssetToProject(+/** Copy a library asset into the open project's media and register it, without+ * placing it on the timeline. Callers choose where it lands. */+export async function importLibraryAsset(projectId: string,lib: LibraryAsset): Promise<MediaAsset> {@@ -62,8 +132,17 @@ export async function addLibraryAssetToProject(height: lib.height,url: mediaUrl(projectId, body.fileName),};+ useEditor.getState().addAsset(asset);+ return asset;+}++/** Copy a library asset into the open project and append it to the timeline. */+export async function addLibraryAssetToProject(+ projectId: string,+ lib: LibraryAsset+): Promise<MediaAsset> {+ const asset = await importLibraryAsset(projectId, lib);const s = useEditor.getState();- s.addAsset(asset);if (asset.type === "video") s.addClipFromAsset(asset.id);else s.addAudioFromAsset(asset.id);return asset;diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex ef4c4050..c04d6794 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -1,12 +1,19 @@import {addFromProject,addUpload,+ createFolder,+ deleteFolder,+ ensureLibraryThumb,libMediaPath,+ listFolders,listLibrary,+ moveAsset,removeAsset,+ renameFolder,useInProject,} from "../library";import { serveFileRange } from "../serveFile";+import { importFromUrl } from "../urlImport";const err = (message: string, status: number) => Response.json({ error: message }, { status });const caught = (e: unknown, fallback: string) =>@@ -15,7 +22,71 @@ const caught = (e: unknown, fallback: string) =>/** The shared library: reusable media outside any project. */export const libraryApi = {async list() {- return Response.json(await listLibrary());+ const [assets, folders] = await Promise.all([listLibrary(), listFolders()]);+ return Response.json({ assets, folders });+ },++ /** A sharp, cached still for a library video. */+ async serveThumb(req: Request, { id }: { id: string }) {+ try {+ const p = await ensureLibraryThumb(decodeURIComponent(id));+ if (!p) return new Response("No thumbnail.", { status: 404 });+ return serveFileRange(p, req);+ } catch {+ return new Response("No thumbnail.", { status: 404 });+ }+ },++ /** Download a media URL straight into the library. */+ async importUrl(req: Request) {+ try {+ const { url } = (await req.json()) as { url?: string };+ if (!url) return err("No URL provided.", 400);+ return Response.json(await importFromUrl(url));+ } catch (e) {+ return caught(e, "Could not import that URL.");+ }+ },++ async createFolder(req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ return Response.json(await createFolder(name ?? ""));+ } catch (e) {+ return caught(e, "Could not create folder.");+ }+ },++ async renameFolder(req: Request, { id }: { id: string }) {+ try {+ const { name } = (await req.json()) as { name?: string };+ return Response.json(await renameFolder(id, name ?? ""));+ } catch (e) {+ return caught(e, "Could not rename folder.");+ }+ },++ async deleteFolder(_req: Request, { id }: { id: string }) {+ try {+ await deleteFolder(id);+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete folder.");+ }+ },++ /** Move an asset into a folder (or `null` to ungroup). */+ async move(req: Request) {+ try {+ const { assetId, folderId } = (await req.json()) as {+ assetId: string;+ folderId: string | null;+ };+ await moveAsset(assetId, folderId ?? null);+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not move asset.");+ }},async upload(req: Request) {diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 26b4ddd0..ec664035 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -9,8 +9,17 @@ import { exists, uniqueName, writeJsonAtomic } from "./util";/** The shared library: reusable media that lives outside any project. */export const LIBRARY_ROOT = path.join(cutDataRoot(), "library");const LIB_MEDIA = path.join(LIBRARY_ROOT, "media");+const LIB_THUMBS = path.join(LIBRARY_ROOT, "thumbs");const INDEX = path.join(LIBRARY_ROOT, "library.json");+/** Where a URL-imported asset came from, kept as notes on the asset. */+export interface LibrarySource {+ url: string;+ title?: string;+ uploader?: string;+ uploadDate?: string; // yt-dlp YYYYMMDD+}+export interface LibraryAsset {id: string;fileName: string;@@ -20,10 +29,19 @@ export interface LibraryAsset {width?: number;height?: number;addedAt: number;+ folderId?: string | null;+ source?: LibrarySource;+}++export interface LibraryFolder {+ id: string;+ name: string;+ createdAt: number;}interface LibraryIndex {assets: LibraryAsset[];+ folders?: LibraryFolder[];}export function libMediaPath(fileName: string) {@@ -33,6 +51,13 @@ export function libMediaPath(fileName: string) {return path.join(LIB_MEDIA, safe);}+export function libThumbPath(id: string) {+ assertLocalRuntime();+ const safe = id.replace(/[^a-zA-Z0-9_-]/g, "");+ if (!safe) throw new Error("Invalid id.");+ return path.join(LIB_THUMBS, `${safe}.jpg`);+}+async function readIndex(): Promise<LibraryIndex> {assertLocalRuntime();let raw: string;@@ -110,6 +135,54 @@ async function probe(filePath: string) {return { duration: Number.isFinite(duration) ? duration : 0, width, height };}+function ffmpeg(args: string[]): Promise<void> {+ return new Promise((resolve, reject) => {+ const p = spawn("ffmpeg", args);+ const timer = setTimeout(() => p.kill("SIGKILL"), 30_000);+ let err = "";+ p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-1000)));+ p.on("error", reject);+ p.on("close", (code) => {+ clearTimeout(timer);+ code === 0+ ? resolve()+ : reject(new Error(err.split("\n").slice(-2).join("\n") || "ffmpeg failed."));+ });+ });+}++// Concurrent thumbnail requests for the same asset share one ffmpeg run.+const thumbInFlight = new Map<string, Promise<string | null>>();++/** A sharp still for a library video, generated with ffmpeg and cached to disk.+ * Audio assets have none. Returns the jpg path, or null when unavailable. */+export async function ensureLibraryThumb(id: string): Promise<string | null> {+ const asset = await getAsset(id);+ if (!asset || asset.type !== "video") return null;+ const dest = libThumbPath(id);+ if (await exists(dest)) return dest;+ const running = thumbInFlight.get(id);+ if (running) return running;+ const job = (async () => {+ try {+ await mkdir(LIB_THUMBS, { recursive: true });+ // A frame a beat in avoids black leading frames; scale down but stay sharp.+ const at = Math.min(1, Math.max(0.1, (asset.duration || 2) / 10));+ await ffmpeg([+ "-y", "-ss", at.toFixed(2), "-i", libMediaPath(asset.fileName),+ "-frames:v", "1", "-vf", "scale='min(640,iw)':-2", "-q:v", "3", dest,+ ]);+ return dest;+ } catch {+ return null;+ } finally {+ thumbInFlight.delete(id);+ }+ })();+ thumbInFlight.set(id, job);+ return job;+}+async function freeName(original: string) {const base = path.basename(original).replace(/[^\w.\-() ]+/g, "_").slice(-80);return uniqueName(base, libMediaPath);@@ -121,7 +194,11 @@ function typeOf(fileName: string): "video" | "audio" | null {return null;}-async function register(fileName: string, name: string): Promise<LibraryAsset> {+export async function register(+ fileName: string,+ name: string,+ source?: LibrarySource+): Promise<LibraryAsset> {const type = typeOf(fileName);if (!type) throw new Error("Unsupported file type.");const meta = await probe(libMediaPath(fileName));@@ -133,10 +210,14 @@ async function register(fileName: string, name: string): Promise<LibraryAsset> {duration: meta.duration,...(meta.width ? { width: meta.width, height: meta.height } : {}),addedAt: Date.now(),+ folderId: null,+ ...(source ? { source } : {}),};const idx = await readIndex();idx.assets.push(asset);await writeIndex(idx);+ // Warm the thumbnail so the tile paints without waiting on the serve path.+ void ensureLibraryThumb(asset.id).catch(() => {});return asset;}@@ -163,6 +244,19 @@ export async function addFromProject(return register(dest, name || fileName);}+/** Move a freshly downloaded file into the library and register it. */+export async function addDownloaded(+ srcPath: string,+ name: string,+ source?: LibrarySource+): Promise<LibraryAsset> {+ if (!typeOf(srcPath)) throw new Error("Unsupported file type.");+ await mkdir(LIB_MEDIA, { recursive: true });+ const dest = await freeName(path.basename(srcPath));+ await copyFile(srcPath, libMediaPath(dest));+ return register(dest, name || path.basename(srcPath), source);+}+/** Copy a library asset into a project's media folder. Returns the file name* inside the project. */export async function useInProject(assetId: string, projectId: string): Promise<string> {@@ -184,8 +278,60 @@ export async function removeAsset(id: string) {idx.assets = idx.assets.filter((a) => a.id !== id);await writeIndex(idx);await rm(libMediaPath(asset.fileName), { force: true });+ await rm(libThumbPath(id), { force: true });}export function getAsset(id: string) {return readIndex().then((idx) => idx.assets.find((a) => a.id === id));}++// --- Folders: a flat set of named groups; assets carry a folderId. ---++export async function listFolders(): Promise<LibraryFolder[]> {+ const idx = await readIndex();+ return (idx.folders ?? []).slice().sort((a, b) => a.createdAt - b.createdAt);+}++export async function createFolder(name: string): Promise<LibraryFolder> {+ const trimmed = name.trim();+ if (!trimmed) throw new Error("Folder name required.");+ const folder: LibraryFolder = {+ id: crypto.randomUUID().slice(0, 8),+ name: trimmed.slice(0, 80),+ createdAt: Date.now(),+ };+ const idx = await readIndex();+ idx.folders = [...(idx.folders ?? []), folder];+ await writeIndex(idx);+ return folder;+}++export async function renameFolder(id: string, name: string): Promise<LibraryFolder> {+ const trimmed = name.trim();+ if (!trimmed) throw new Error("Folder name required.");+ const idx = await readIndex();+ const folder = (idx.folders ?? []).find((f) => f.id === id);+ if (!folder) throw new Error("Folder not found.");+ folder.name = trimmed.slice(0, 80);+ await writeIndex(idx);+ return folder;+}++export async function deleteFolder(id: string) {+ const idx = await readIndex();+ idx.folders = (idx.folders ?? []).filter((f) => f.id !== id);+ // Assets in the folder fall back to ungrouped rather than vanishing.+ for (const a of idx.assets) if (a.folderId === id) a.folderId = null;+ await writeIndex(idx);+}++export async function moveAsset(assetId: string, folderId: string | null) {+ const idx = await readIndex();+ const asset = idx.assets.find((a) => a.id === assetId);+ if (!asset) throw new Error("Library asset not found.");+ if (folderId && !(idx.folders ?? []).some((f) => f.id === folderId)) {+ throw new Error("Folder not found.");+ }+ asset.folderId = folderId;+ await writeIndex(idx);+}diff --git a/site/src/cut/server/urlImport.ts b/site/src/cut/server/urlImport.tsnew file mode 100644index 00000000..d6d35267--- /dev/null+++ b/site/src/cut/server/urlImport.ts@@ -0,0 +1,98 @@+import { spawn } from "node:child_process";+import { mkdtemp, readdir, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { addDownloaded, type LibraryAsset } from "./library";+import { assertLocalRuntime } from "./local-only";++// Download a media URL (TikTok, YouTube, Instagram, …) into the shared library+// with the bundled yt-dlp. The engine finds yt-dlp on its widened PATH exactly+// like ffmpeg.++const MEDIA_EXT = /\.(mp4|mov|m4v|webm|mkv|mp3|m4a|aac|wav|ogg|flac)$/i;++// A small ceiling so a burst of pastes can't spawn unbounded downloads.+const MAX_ACTIVE = 2;+let active = 0;++interface YtMeta {+ title?: string;+ uploader?: string;+ upload_date?: string;+ webpage_url?: string;+}++export async function importFromUrl(url: string): Promise<LibraryAsset> {+ assertLocalRuntime();+ if (!/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");+ if (active >= MAX_ACTIVE) {+ throw new Error("Too many downloads in progress. Try again in a moment.");+ }+ active++;+ const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-dl-"));+ try {+ const meta = await runYtDlp(url.trim(), tmp);+ // Pick the largest media file left behind (the merged output).+ const names = (await readdir(tmp)).filter((f) => MEDIA_EXT.test(f));+ if (names.length === 0) throw new Error("Nothing downloadable was found at that URL.");+ const sized = await Promise.all(+ names.map(async (n) => ({ n, size: (await stat(path.join(tmp, n))).size }))+ );+ const file = sized.sort((a, b) => b.size - a.size)[0].n;+ const title = (meta.title || "Imported clip").slice(0, 120);+ return await addDownloaded(path.join(tmp, file), title, {+ url: meta.webpage_url || url.trim(),+ title: meta.title,+ uploader: meta.uploader,+ uploadDate: meta.upload_date,+ });+ } finally {+ active--;+ void rm(tmp, { recursive: true, force: true });+ }+}++function runYtDlp(url: string, dir: string): Promise<YtMeta> {+ return new Promise((resolve, reject) => {+ const p = spawn("yt-dlp", [+ "--no-playlist",+ "--no-progress",+ "-f", "mp4/bestvideo*+bestaudio/best",+ "--merge-output-format", "mp4",+ "-o", path.join(dir, "%(id)s.%(ext)s"),+ "--print-json",+ url,+ ]);+ const timer = setTimeout(() => {+ p.kill("SIGKILL");+ reject(new Error("Download timed out."));+ }, 300_000);+ timer.unref();+ let out = "";+ let err = "";+ p.stdout.on("data", (d) => (out += d.toString()));+ p.stderr.on("data", (d) => (err = (err + d.toString()).slice(-2000)));+ p.on("error", (e) => {+ clearTimeout(timer);+ reject(+ e.message.includes("ENOENT")+ ? new Error("yt-dlp is not available in this build.")+ : e+ );+ });+ p.on("close", (code) => {+ clearTimeout(timer);+ if (code !== 0) {+ reject(new Error(err.split("\n").filter(Boolean).slice(-1)[0] || "Download failed."));+ return;+ }+ // --print-json emits the info dict as JSON; take the last JSON line.+ const line = out.trim().split("\n").reverse().find((l) => l.trimStart().startsWith("{"));+ try {+ resolve(line ? (JSON.parse(line) as YtMeta) : {});+ } catch {+ resolve({});+ }+ });+ });+}