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
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue