From 687ba898f617dc5110f808ee2310d28b2d1a5050 Mon Sep 17 00:00:00 2001 From: Aidan Dona Date: Thu, 8 Oct 2026 15:47:30 -0500 Subject: [PATCH] Media: name files when saving, and rename them in the library (file and references) Every upload and save (Upload, Frame at, Video thumbnails, a clip's Save to library) has a prefilled Name box; the name is also the readable part of the file's name, plus a short random ending. Fetch preview names its picture after the page. Rename on the Media page changes both, moving the file and its small copy and pointing every record that names it at the new path in one transaction. Co-Authored-By: Claude Opus 5.5 --- docs/media-uploads.md | 16 +++- server/src/clips.js | 28 +++--- server/src/media.js | 86 ++++++++++++++++-- server/src/routes/clips.js | 10 ++- server/src/routes/media.js | 122 ++++++++++++++++++++------ src/components/admin/MediaLibrary.tsx | 122 ++++++++++++++++++++++---- src/pages/admin/AdminClips.tsx | 61 +++++++++++-- src/pages/admin/AdminMedia.tsx | 78 +++++++++++++++- src/pages/admin/AdminVideoFrames.tsx | 26 +++++- 9 files changed, 475 insertions(+), 74 deletions(-) diff --git a/docs/media-uploads.md b/docs/media-uploads.md index 99ad77c..63fbb52 100644 --- a/docs/media-uploads.md +++ b/docs/media-uploads.md @@ -27,6 +27,18 @@ in the `media` table (`server/src/migrations/028_media.sql`). (`.vtt`, kept as they are, always in `captions/`). The type is read from the file's contents, not its name: a captions file has to start with `WEBVTT`. +- Every upload and save asks for a **Name** (prefilled: the file's own + name, "Video frame at 1:23", a clip's title and span). It's the + library's name and the readable part of the file's, plus a short + random ending: `images/spring-retreat-group-3f9c1a.webp` + (`slugify` and `storedNameFor` in `server/src/media.js`). Fetch preview + names its picture after the page's title. +- **Rename** (Media page, editors and up) changes both. The file and its + small copy move to a new name, and every record that names the file is + pointed at it in the same step (the same search the delete check + uses). Anything outside the site still holding the old address (a + sent newsletter, a shared link) stops working. A rename that only + changes capitals or punctuation keeps the file where it is. - Editors and up can upload. Admins and up can delete. The Media page shows which tables still use a file before deleting it, because nothing stops a file a record uses from being deleted. @@ -106,7 +118,9 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies } ``` - Filenames are random and never reused, so `immutable` is safe. + Every stored name ends in a random part and a new one is never an + existing file's, so `immutable` is safe; a rename makes a new name + rather than changing a file in place. 4. `sharp` is a server dependency now: run `pnpm install` in `/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries, diff --git a/server/src/clips.js b/server/src/clips.js index b8fec0e..f529d12 100644 --- a/server/src/clips.js +++ b/server/src/clips.js @@ -52,7 +52,7 @@ import { randomBytes } from "node:crypto"; import { access, constants, copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises"; import path from "node:path"; -import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js"; +import { UPLOADS_DIR, publicPath, storedNameFor } from "./media.js"; export const CLIPS_DIR = path.resolve(process.env.CLIPS_DIR ?? "./clips"); const YTDLP = process.env.YTDLP_PATH ?? "yt-dlp"; @@ -548,17 +548,24 @@ export function kick(db = dbRef) { export const fileOf = (job) => (job?.file ? filePath(job.file) : null); /* A finished clip, or a whole downloaded video, into the media - library: copied into the uploads directory under a random name and + library: copied into the uploads directory, named for `name` (the + Save to library box; blank: its title and span), and given a media row. A clip's working file is deleted; a video's is kept for cutting. Returns the media row's id. */ -export async function saveToLibrary(db, job, userId) { +export async function saveToLibrary(db, job, userId, name = null) { const from = fileOf(job); if (!from) throw new ClipError(410, "That clip's file is gone. Make it again."); const audio = job.file.endsWith(".mp3"); const ext = audio ? ".mp3" : ".mp4"; - const filename = `${randomBytes(12).toString("hex")}${ext}`; - const to = path.join(UPLOADS_DIR, filename); + const params = JSON.parse(job.params ?? "{}"); + const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`; + // A whole download is named for itself; a clip for its span. + const label = + name ?? + (job.kind === "source" + ? `${job.title ?? "Video"}${ext}` + : `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`); // Each step says what it was doing if it fails, so the page can // tell an admin (this tool is admin-only) what to fix: usually the @@ -576,6 +583,8 @@ export async function saveToLibrary(db, job, userId) { }; await step(`making the uploads folder ${UPLOADS_DIR}`, () => mkdir(UPLOADS_DIR, { recursive: true })); + const filename = await step("choosing its file name", () => storedNameFor(label, ext)); + const to = path.join(UPLOADS_DIR, filename); await step(`copying the clip into ${UPLOADS_DIR}`, () => copyFile(from, to)); let id; @@ -584,13 +593,6 @@ export async function saveToLibrary(db, job, userId) { ? { width: null, height: null } : await step("reading the clip's size", () => probe(from)); const { size } = await stat(from); - const params = JSON.parse(job.params ?? "{}"); - const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`; - // A whole download is named for itself; a clip for its span. - const label = - job.kind === "source" - ? `${job.title ?? "Video"}${ext}` - : `${job.title ?? "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)})${ext}`; id = await step("adding it to the media table", () => Number( @@ -616,7 +618,7 @@ export async function saveToLibrary(db, job, userId) { await rm(from, { force: true }); update(db, job.id, { saved_media_id: id, file: null }); } - return { id, url: `${PUBLIC_PREFIX}${filename}` }; + return { id, url: publicPath(filename) }; } /* After a clip has gone out in full: its file isn't needed. */ diff --git a/server/src/media.js b/server/src/media.js index 19f3f2c..c4c6c1a 100644 --- a/server/src/media.js +++ b/server/src/media.js @@ -28,8 +28,12 @@ is: it's already small, and rasterizing it would lose the point of it. So is a WebVTT file, always into captions/. - Names are random, so two uploads of "logo.png" can't collide - and a filename says nothing about what's in it. + A stored name is made from the name it's given (the Name box on + every upload and save), plus a short random ending, so two + uploads called "Logo" can't collide: 'images/logo-3f9c1a.webp'. + The ending also means no name can end in -640, the small copies' + mark. Renaming (renameStored) makes a new stored name and moves + the file, its small copy and every record naming it to it. ── Folders ── Each upload goes in a folder by what it's for (FOLDERS): logos/ @@ -80,6 +84,37 @@ export function isStoredName(name) { return parts.length === 1 || (parts.length === 2 && FOLDERS.includes(parts[0])); } +/* A name as the readable part of a stored name: lowercase letters, + digits and hyphens, accents dropped, at most 60 characters. + Nothing usable (eg. only emoji) gives `fallback`. */ +export function slugify(name, fallback = "file") { + const slug = String(name ?? "") + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/\.[a-z0-9]{2,4}$/, "") // a typed "photo.jpg" keeps its own ending off + .replace(/[^a-z0-9]+/g, "-") + .slice(0, 60) + .replace(/^-+|-+$/g, ""); + return slug || fallback; +} + +/* A new stored name in `dir` ('' for the root) for something called + `name`, ending in `ext` ('.webp'), that no file has yet: writing + over one would lose it, and a failed save would then delete it. */ +export async function storedNameFor(name, ext, dir = "") { + for (let tries = 0; tries < 8; tries++) { + const filename = `${dir ? `${dir}/` : ""}${slugify(name)}-${randomBytes(3).toString("hex")}${ext}`; + try { + await stat(path.join(UPLOADS_DIR, filename)); + } catch (err) { + if (err.code === "ENOENT") return filename; + throw err; + } + } + throw new MediaError(500, "Couldn't find a free file name. Try again."); +} + /* The public path of a stored name, each part escaped. */ export const publicPath = (filename) => `${PUBLIC_PREFIX}${String(filename).split("/").map(encodeURIComponent).join("/")}`; @@ -167,7 +202,7 @@ function sniff(buf) { and leave nothing behind. ───────────────────────────────────────────────────────────── */ -export async function store(buf, { keepOriginal = false, folder } = {}) { +export async function store(buf, { keepOriginal = false, folder, name } = {}) { if (buf.length === 0) throw new MediaError(400, "The file is empty."); if (buf.length > MAX_UPLOAD_BYTES) { throw new MediaError(413, `Files can be at most ${MAX_UPLOAD_BYTES / MB} MB.`); @@ -216,10 +251,9 @@ export async function store(buf, { keepOriginal = false, folder } = {}) { } const dir = kind === "vtt" ? "captions" : folderOf(folder); - const base = `${randomBytes(12).toString("hex")}${type.ext}`; - const filename = `${dir}/${base}`; - await mkdir(path.join(UPLOADS_DIR, dir), { recursive: true }); + const filename = await storedNameFor(name, type.ext, dir); + const base = path.basename(filename); // Written under a temporary name and renamed, so a half-written // file is never served under its real one. const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`); @@ -300,6 +334,46 @@ export async function remove(filename) { } } +/* ── Renaming ────────────────────────────────────────────────── + Moves a stored file (and its small copy) to a new name made + from `name`, keeping its folder and ending, and returns the new + stored name. `commit(newName)` writes the database's side (the + media row and every record naming the file) and must be + synchronous, so it runs in one transaction; if it throws, the + files go back where they were. + ───────────────────────────────────────────────────────────── */ + +export async function renameStored(filename, name, commit) { + if (!isStoredName(filename)) throw new MediaError(400, "That file can't be renamed."); + const dir = filename.includes("/") ? filename.split("/")[0] : ""; + const ext = path.extname(filename).toLowerCase(); + const next = await storedNameFor(name, ext, dir); + + const moves = [[filename, next]]; + const thumb = thumbName(filename); + if (!THUMB.test(filename) && (await stat(path.join(UPLOADS_DIR, thumb)).catch(() => null))) { + moves.push([thumb, thumbName(next)]); + } + + const done = []; + try { + for (const [from, to] of moves) { + await rename(path.join(UPLOADS_DIR, from), path.join(UPLOADS_DIR, to)); + done.push([from, to]); + } + commit(next); + return next; + } catch (err) { + for (const [from, to] of done.reverse()) { + await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, from)).catch((undo) => + console.error(`media: couldn't move ${to} back to ${from}: ${undo.message}`), + ); + } + if (err.code === "ENOENT") throw new MediaError(404, "The file is missing from the uploads folder."); + throw err; + } +} + /* ── Files copied in by hand ─────────────────────────────────── */ /* What a file already on disk is: the fields a media row needs, or diff --git a/server/src/routes/clips.js b/server/src/routes/clips.js index 6c88d04..54944c6 100644 --- a/server/src/routes/clips.js +++ b/server/src/routes/clips.js @@ -11,9 +11,9 @@ GET /clips/:id/download a finished clip, as an attachment; its file is deleted once it has gone out in full, unless saved - POST /clips/:id/save a finished clip, or a whole - downloaded video, into the media - library + POST /clips/:id/save { name }: a finished clip, or a + whole downloaded video, into the + media library under that name POST /clips/:id/drive { folder }: a finished clip (or a whole downloaded video) into a folder under Media in Drive, as a @@ -47,6 +47,7 @@ import { } from "../clips.js"; import { NO_STORE } from "../shape.js"; import { UPLOADS_DIR } from "../media.js"; +import { nameFrom } from "./media.js"; import { driveDelete, driveReady, driveShareWithAnyone, driveUploadFile } from "../googleService.js"; import { cleanFolder, inDrive, recordDriveUpload } from "./files.js"; @@ -219,7 +220,8 @@ clips.post("/clips/:id/save", async (c) => { if (job.status !== "done") throw new ClipError(400, "Only a finished download or clip can be saved."); if (job.saved_media_id) throw new ClipError(409, "It's already in the media library."); if (!job.file) throw new ClipError(410, "Its file is gone from the server."); - const media = await saveToLibrary(db, job, c.get("user").id); + const body = (await c.req.json().catch(() => null)) ?? {}; + const media = await saveToLibrary(db, job, c.get("user").id, nameFrom(body.name)); console.log(`clips: clip ${job.id} saved to the library by ${c.get("user").email}`); return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE); }); diff --git a/server/src/routes/media.js b/server/src/routes/media.js index 74b3c4e..b194d77 100644 --- a/server/src/routes/media.js +++ b/server/src/routes/media.js @@ -9,9 +9,11 @@ (registerLooseFiles, at most every SCAN_EVERY_MS) POST /media upload one image or .vtt (multipart: file, - keep_original, folder: FOLDERS in - media.js, default images) + name, keep_original, folder: FOLDERS + in media.js, default images) GET /media/:id/uses which records name this file + PATCH /media/:id rename it ({ name }): the file too, + and every record naming it DELETE /media/:id remove the row and the file POST /link-preview a page's title, description and preview image, the image saved into @@ -26,18 +28,24 @@ claim /media and answer "Unknown entity." ═══════════════════════════════════════════════════════════════ */ +import path from "node:path"; + import { Hono } from "hono"; import { bodyLimit } from "hono/body-limit"; import { requireAuth, requireRole } from "../auth.js"; +import { tx } from "../db.js"; import { FOLDERS, MAX_UPLOAD_BYTES, MediaError, PUBLIC_PREFIX, publicPath, + isStoredName, registerLooseFiles, remove, + renameStored, + slugify, store, } from "../media.js"; import { fetchImage, previewLink } from "../linkPreview.js"; @@ -77,6 +85,13 @@ export function shape(row) { }; } +/* A name typed in a Name box: trimmed, at most 200 characters, null + when blank (the caller's default then applies). */ +export function nameFrom(value) { + const name = typeof value === "string" ? value.trim().slice(0, 200) : ""; + return name || null; +} + const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_email FROM media m LEFT JOIN admin_users u ON u.id = m.uploaded_by`; @@ -84,7 +99,8 @@ const SELECT = `SELECT m.*, u.name AS uploaded_by_name, u.email AS uploaded_by_e /* Writes the file, then its row; a failed insert takes the file back out so nothing is left on disk that the library can't see. */ export async function addToLibrary(db, buf, { originalName, keepOriginal, userId, folder }) { - const stored = await store(buf, { keepOriginal, folder }); + // The stored file is named for it too (slugify in media.js). + const stored = await store(buf, { keepOriginal, folder, name: originalName }); try { const { lastInsertRowid } = db .prepare( @@ -156,7 +172,7 @@ media.post( if (!(file instanceof File)) return c.json({ error: "No file was sent." }, 400); const row = await addToLibrary(db, Buffer.from(await file.arrayBuffer()), { - originalName: file.name, + originalName: nameFrom(body.name) ?? file.name, keepOriginal: body.keep_original === "1", folder: body.folder, userId: user.id, @@ -186,7 +202,8 @@ media.post("/link-preview", requireRole("editor"), async (c) => { if (page.image) { try { const row = await addToLibrary(c.get("db"), await fetchImage(page.image), { - originalName: `preview ${new URL(page.image).hostname}`, + // Named for the page it previews; renamed in the library if wanted. + originalName: page.title?.trim() || `preview ${new URL(page.image).hostname}`, folder: "thumbnails", keepOriginal: false, userId: user.id, @@ -216,7 +233,7 @@ media.post("/video-frame", requireRole("editor"), async (c) => { return c.json({ error: "Expected a JSON body." }, 400); } const row = await addToLibrary(c.get("db"), await grabFrame(body.url, Number(body.seconds)), { - originalName: `video frame ${Math.floor(Number(body.seconds))}s`, + originalName: nameFrom(body.name) ?? `video frame ${Math.floor(Number(body.seconds))}s`, folder: "thumbnails", keepOriginal: false, userId: user.id, @@ -231,13 +248,36 @@ media.post("/video-frame", requireRole("editor"), async (c) => { typed into a field) its bare name, which media.ts resolves to the same place. Read from the live schema rather than a list of image columns, so a new image field is covered the day it's added. */ -function usesOf(db, filename) { - return recordsNaming(db, [ +const namesFor = (filename) => [ + ...new Set([ `${PUBLIC_PREFIX}${filename}`, `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, publicPath(filename), filename, - ]); + ]), +]; + +function usesOf(db, filename) { + return recordsNaming(db, namesFor(filename)); +} + +/* Every content table's TEXT columns: [{ table, columns }]. Names + come from the schema, not a request; they're quoted anyway. */ +function contentColumns(db) { + return db + .prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) + .all() + .map((t) => t.name) + .filter((name) => !NOT_CONTENT.has(name)) + .map((table) => ({ + table, + columns: db + .prepare(`SELECT name, type FROM pragma_table_info(?)`) + .all(table) + .filter((col) => col.type.toUpperCase() === "TEXT") + .map((col) => col.name), + })) + .filter(({ columns }) => columns.length > 0); } /* Which content tables have a TEXT column holding exactly one of @@ -245,23 +285,9 @@ function usesOf(db, filename) { what links to a file (routes/files.js). */ export function recordsNaming(db, values) { values = [...new Set(values)]; - const tables = db - .prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`) - .all() - .map((t) => t.name) - .filter((name) => !NOT_CONTENT.has(name)); - + const marks = values.map(() => "?").join(", "); const uses = []; - for (const table of tables) { - const columns = db - .prepare(`SELECT name, type FROM pragma_table_info(?)`) - .all(table) - .filter((col) => col.type.toUpperCase() === "TEXT") - .map((col) => col.name); - if (columns.length === 0) continue; - - // Names come from the schema, not the request; quoted anyway. - const marks = values.map(() => "?").join(", "); + for (const { table, columns } of contentColumns(db)) { const where = columns.map((col) => `"${col}" IN (${marks})`).join(" OR "); const { n } = db .prepare(`SELECT COUNT(*) AS n FROM "${table}" WHERE ${where}`) @@ -271,6 +297,25 @@ export function recordsNaming(db, values) { return uses; } +/* Points every record naming `from` at `to` instead: the same exact + values usesOf finds, each swapped for its new form (a bare name + for a bare name, the public path for any path). Returns how many + values were rewritten. The touch triggers move each record's + updated_at, so an editor still open on one is told it changed + rather than saving the old path back. */ +function rewriteRecords(db, from, to) { + const swaps = namesFor(from).map((old) => [old, old === from ? to : publicPath(to)]); + let changed = 0; + for (const { table, columns } of contentColumns(db)) { + for (const col of columns) { + for (const [old, next] of swaps) { + changed += Number(db.prepare(`UPDATE "${table}" SET "${col}" = ? WHERE "${col}" = ?`).run(next, old).changes); + } + } + } + return changed; +} + function findOr404(c) { const id = Number(c.req.param("id")); const row = Number.isInteger(id) @@ -285,6 +330,33 @@ media.get("/media/:id/uses", (c) => { return c.json({ uses: usesOf(c.get("db"), row.filename) }, 200, NO_STORE); }); +/* A new name ({ name }): the library's name and the file's own, with + every record that names the file pointed at the new one, in one + transaction (renameStored in media.js moves the files back if it + fails). A name whose readable part is unchanged (eg. only its + capitals) keeps the file where it is. */ +media.patch("/media/:id", requireRole("editor"), async (c) => { + const db = c.get("db"); + const row = findOr404(c); + const body = (await c.req.json().catch(() => null)) ?? {}; + const name = nameFrom(body.name); + if (!name) throw new MediaError(400, "Give it a name."); + + const sameFile = path.basename(row.filename).startsWith(`${slugify(name)}-`) || !isStoredName(row.filename); + let records = 0; + const filename = sameFile + ? (db.prepare(`UPDATE media SET original_name = ? WHERE id = ?`).run(name, row.id), row.filename) + : await renameStored(row.filename, name, (next) => + tx(db, () => { + db.prepare(`UPDATE media SET filename = ?, original_name = ? WHERE id = ?`).run(next, name, row.id); + records = rewriteRecords(db, row.filename, next); + }), + ); + + console.log(`media ${row.filename} renamed to ${filename} ("${name}"), ${records} references updated, by ${c.get("user").email}`); + return c.json({ media: shape(db.prepare(`${SELECT} WHERE m.id = ?`).get(row.id)), updated: records }, 200, NO_STORE); +}); + media.delete("/media/:id", requireRole("admin"), async (c) => { const row = findOr404(c); c.get("db").prepare(`DELETE FROM media WHERE id = ?`).run(row.id); diff --git a/src/components/admin/MediaLibrary.tsx b/src/components/admin/MediaLibrary.tsx index 73f9304..eee94cf 100644 --- a/src/components/admin/MediaLibrary.tsx +++ b/src/components/admin/MediaLibrary.tsx @@ -134,14 +134,54 @@ export function mediaSize(item: MediaItem) { /* ── Data ────────────────────────────────────────────────────── */ -export function uploadImage(file: File, keepOriginal: boolean, folder?: string): Promise { +/* `name` is the library's name for it and the readable part of its + file name (server/src/media.js); blank: the file's own name. */ +export function uploadImage(file: File, keepOriginal: boolean, folder?: string, name?: string): Promise { const form = new FormData(); form.append("file", file); + if (name?.trim()) form.append("name", name.trim()); if (keepOriginal) form.append("keep_original", "1"); if (folder) form.append("folder", folder); return upload("/admin/media", form).then((data) => data.media); } +/* What a Name box starts with for a chosen file: its name without the + ending, separators read as spaces ("spring_retreat-1.jpg" → + "spring retreat 1"). */ +export function nameOfFile(file: File): string { + return file.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ").trim(); +} + +/* A Name box, labeled, for anything about to be saved to the library. */ +export function NameBox({ + value, + onChange, + className = "", + label = "Name", +}: { + value: string; + onChange: (value: string) => void; + className?: string; + label?: string; +}) { + const id = useId(); + return ( +
+ + onChange(e.target.value)} + className="min-w-0 flex-1 border border-muted/25 bg-surface px-2 py-1 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25" + /> +
+ ); +} + /* How long a search waits after the last keystroke. */ export const SEARCH_PAUSE_MS = 250; /* The most the library route sends (MAX_LIST, server/src/routes/media.js). */ @@ -204,36 +244,58 @@ export function UploadButton({ const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [framing, setFraming] = useState(null); + // Chosen (and framed) but not sent yet: each waits with a Name box, + // prefilled from its own name, until Upload is pressed. + const [pending, setPending] = useState>([]); // Captions are kept as they are, so there's no original to keep. const captions = folder === "captions"; + const clearInput = () => { + if (inputRef.current) inputRef.current.value = ""; + }; + // A single photo for a field with a shape is framed first; SVGs and - // GIFs (which would lose their animation) go as they are. + // GIFs (which would lose their animation) go as they are. Either + // way the names come next. function choose(files: FileList | null) { const one = files?.length === 1 ? files[0] : null; if (crop && one && /^image\/(jpeg|png|webp)$/.test(one.type)) setFraming(one); - else send(files ? Array.from(files) : []); + else name(files ? Array.from(files) : []); } - async function send(files: File[]) { + function name(files: File[]) { + setError(null); + setPending(files.map((file) => ({ file, name: nameOfFile(file) }))); + clearInput(); + } + + function cancel() { + setPending([]); + clearInput(); + } + + async function send() { + const files = pending; if (files.length === 0) return; setBusy(true); setError(null); try { // One at a time: each is up to 25 MB, and a failure should - // name the file it happened to. - for (const file of files) { + // name the file it happened to. What went stays gone from the + // list; what didn't stays, to try again. + for (const [index, { file, name }] of files.entries()) { try { - onUploaded(await uploadImage(file, keepOriginal, folder)); + onUploaded(await uploadImage(file, keepOriginal, folder, name)); } catch (err) { const why = err instanceof ApiError ? err.message : "Upload failed."; - setError(files.length > 1 ? `${file.name}: ${why}` : why); - break; + setError(files.length > 1 ? `${name || file.name}: ${why}` : why); + setPending(files.slice(index)); + return; } } + setPending([]); } finally { setBusy(false); - if (inputRef.current) inputRef.current.value = ""; } } @@ -243,10 +305,10 @@ export function UploadButton({ )} + {pending.length > 0 && ( +
+ {pending.map((item, index) => ( + 1 ? `Name ${index + 1}` : "Name"} + value={item.name} + onChange={(value) => + setPending((list) => list.map((entry, i) => (i === index ? { ...entry, name: value } : entry))) + } + /> + ))} +

Also its file name, eg. spring-retreat-group-3f9c1a.webp.

+
+ + +
+
+ )} {error &&

{error}

} {framing && crop && ( { setFraming(null); - if (file) send([file]); - else if (inputRef.current) inputRef.current.value = ""; + if (file) name([file]); + else clearInput(); }} /> )} @@ -658,18 +743,24 @@ export function startOf(url: string): number { } } +/* What a frame's Name box says until somebody types in it. */ +export const frameName = (text: string) => `Video frame at ${text.trim() || "0:00"}`; + function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) { const [text, setText] = useState(() => clock(startOf(url))); + // null: follow the time ("Video frame at 1:23"); typed, it's kept. + const [typedName, setTypedName] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const timeId = useId(); const seconds = parseClock(text); + const name = typedName ?? frameName(text); async function take() { setBusy(true); setError(null); try { - const { media } = await post("/admin/video-frame", { url, seconds }); + const { media } = await post("/admin/video-frame", { url, seconds, name }); onSaved(media.url); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't take that frame."); @@ -686,6 +777,7 @@ function FrameFromVideo({ url, className, onSaved }: { url: string; className: s
setText(e.target.value)} placeholder="eg. 1:23" className={className} />
+ diff --git a/src/pages/admin/AdminClips.tsx b/src/pages/admin/AdminClips.tsx index 3db94f8..a72dbb5 100644 --- a/src/pages/admin/AdminClips.tsx +++ b/src/pages/admin/AdminClips.tsx @@ -20,6 +20,7 @@ import { Link } from "react-router-dom"; import { ApiError, del, get, post } from "../../lib/api.ts"; import { clock, parseClock } from "../../lib/clock.ts"; import { accentText, BRAND } from '../../lib/color.ts' +import { NameBox } from "../../components/admin/MediaLibrary.tsx"; const MUTED = "var(--color-muted)"; const POLL_MS = 2000; @@ -71,6 +72,52 @@ const primary = const input = "border border-muted/25 bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25"; +/* Save to library: a Name box first, prefilled with the video's title + (and a clip's span), which also names the file. `act` is the + page's, so a failure shows on the row like any other action. */ +function SaveToLibrary({ + id, + defaultName, + act, +}: { + id: number; + defaultName: string; + act: (fn: () => Promise) => Promise; +}) { + const [name, setName] = useState(null); + const [busy, setBusy] = useState(false); + + if (name === null) { + return ( + + ); + } + + return ( +
+ + + +
+ ); +} + /* Save to Drive: a folder under Media (Tools → Media → Files), then the clip goes there as a Files entry. Opens on a folder named for the clip's kind (Videos, Audio) when there is one. */ @@ -477,9 +524,7 @@ export default function AdminClips() { {/* The whole video, before (or without) cutting: it stays here to cut from either way. */} {s.status === "done" && s.has_file && !s.saved_url && ( - + )} {s.saved_url && ( @@ -553,9 +598,13 @@ export default function AdminClips() { > Download - + )} {clip.saved_url && ( diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx index 77c869a..e96c652 100644 --- a/src/pages/admin/AdminMedia.tsx +++ b/src/pages/admin/AdminMedia.tsx @@ -17,7 +17,7 @@ a page (an image field stores the path, not a foreign key). ═══════════════════════════════════════════════════════════════ */ -import { useEffect, useState } from "react"; +import { useEffect, useState, type FormEvent } from "react"; import { Link } from "react-router-dom"; import { ApiError, del, get, patch, post } from "../../lib/api.ts"; @@ -38,6 +38,7 @@ import { FolderTabs, formatBytes, MediaGrid, + NameBox, UPLOAD_HELP, UploadButton, useMediaLibrary, @@ -131,6 +132,73 @@ function DeleteControl({ ); } +/* Rename: the library's name and the file's own. Opening it asks what + uses the file first, since the server repoints those records at the + new address and anything outside the site (a sent newsletter, a + shared link) keeps the old one, which stops working. */ +function RenameControl({ item, onRenamed }: { item: MediaItem; onRenamed: (item: MediaItem) => void }) { + const [name, setName] = useState(null); + const [uses, setUses] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function open() { + setName(item.original_name); + setError(null); + setUses(null); + try { + setUses((await get(`/admin/media/${item.id}/uses`, { ttl: 0 })).uses); + } catch { + setUses([]); + } + } + + async function save(e: FormEvent) { + e.preventDefault(); + if (!name?.trim()) return; + setBusy(true); + setError(null); + try { + const { media } = await patch(`/admin/media/${item.id}`, { name }); + onRenamed(media); + setName(null); + } catch (err) { + setError(err instanceof ApiError ? err.message : "Couldn't rename that."); + } finally { + setBusy(false); + } + } + + if (name === null) { + return ( + + ); + } + + const count = uses?.reduce((sum, use) => sum + use.count, 0) ?? 0; + return ( +
+ +

+ {uses === null + ? "Checking what uses it…" + : `Also renames the file${count > 0 ? `, and updates the ${count} record${count === 1 ? "" : "s"} using it` : ""}. Links to the old address outside the site (eg. a sent newsletter) will stop working.`} +

+
+ + +
+ {error &&

{error}

} + + ); +} + function CopyPath({ url, label = "Copy path" }: { url: string; label?: string }) { const [copied, setCopied] = useState(false); return ( @@ -573,6 +641,14 @@ export default function AdminMedia() { > Open + {roleCanWrite(user) && ( + + setItems((current) => (current ?? []).map((m) => (m.id === renamed.id ? renamed : m))) + } + /> + )} {canDelete(user) && (
-

At {clock(frame.seconds)}

+

{frame.media.original_name}

+

+ At {clock(frame.seconds)} +

{frame.url}

@@ -78,10 +81,14 @@ export default function AdminVideoFrames() { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [frames, setFrames] = useState([]); + // null: follow the time ("Video frame at 1:23"); typed, it's kept. + const [typedName, setTypedName] = useState(null); const urlId = useId(); const timeId = useId(); + const nameId = useId(); const seconds = parseClock(time); + const name = typedName ?? frameName(time); // A pasted link that carries its own time (t=83) sets the box. function changeUrl(next: string) { @@ -97,7 +104,7 @@ export default function AdminVideoFrames() { setError(null); try { const link = url.trim(); - const { media } = await post("/admin/video-frame", { url: link, seconds }); + const { media } = await post("/admin/video-frame", { url: link, seconds, name }); setFrames((list) => [{ media, url: link, seconds }, ...list]); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't take that frame."); @@ -143,6 +150,19 @@ export default function AdminVideoFrames() { className={`mt-1 w-full ${input}`} />
+
+ + setTypedName(e.target.value)} + className={`mt-1 w-full ${input}`} + /> +