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 <noreply@anthropic.com>
This commit is contained in:
parent
14a22ca44d
commit
687ba898f6
9 changed files with 475 additions and 74 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue