Request details, Drive folders, image folders, clip tool to Drive (v1.9.12 to v1.9.14-content-display) #16

Merged
ngu-git-admin merged 13 commits from content-display into main 2026-09-30 19:05:26 +01:00
6 changed files with 219 additions and 17 deletions
Showing only changes of commit 42d1536ee6 - Show all commits

View file

@ -14,6 +14,16 @@ server once it's downloaded, unless **Save to library** is pressed first,
which puts it in the media library as an upload (usable as a featured which puts it in the media library as an upload (usable as a featured
video or in a video block). Everything is cleared a day after it's made. video or in a video block). Everything is cleared a day after it's made.
**Save to Drive** puts a copy in a folder under Media in the shared
Google Drive (pick it, eg. `Media/Videos` or `Media/Audio`; the list is
Tools → Media → Files's folders, and the one named for the clip's kind
is chosen first). It becomes a Files entry, shared with anyone who has
the link, so pages link to it with Choose a file. It's uploaded straight
from the server's copy (the working file, or the library's), streamed
rather than read into memory, so a long clip is fine; nginx isn't in the
way. A clip can be in both the library and Drive. Needs Google Drive set
up (`docs/google-drive-and-mail.md`) and migration 051.
Only YouTube and Facebook links are accepted, and only for videos NGU owns Only YouTube and Facebook links are accepted, and only for videos NGU owns
or has permission to use. Sources can be up to 4 hours and 4 GB; clips up or has permission to use. Sources can be up to 4 hours and 4 GB; clips up
to an hour. Limits are constants at the top of `server/src/clips.js`. to an hour. Limits are constants at the top of `server/src/clips.js`.

View file

@ -32,7 +32,9 @@
Setup: docs/google-drive-and-mail.md. Setup: docs/google-drive-and-mail.md.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { readFileSync } from "node:fs"; import { createReadStream, readFileSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { createSign } from "node:crypto"; import { createSign } from "node:crypto";
const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"; const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
@ -99,11 +101,11 @@ async function accessToken(scope, subject) {
return data.access_token; return data.access_token;
} }
async function call(url, init, scope, subject) { async function call(url, init, scope, subject, timeoutMs = 60_000) {
const res = await fetch(url, { const res = await fetch(url, {
...init, ...init,
headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` }, headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` },
signal: AbortSignal.timeout(60_000), signal: AbortSignal.timeout(timeoutMs),
}); });
if (!res.ok) { if (!res.ok) {
const detail = await res.json().catch(() => null); const detail = await res.json().catch(() => null);
@ -270,6 +272,41 @@ export async function driveRename(id, name) {
); );
} }
/* A file on disk into a folder of the shared drive, streamed through
a resumable upload rather than read into memory (a video clip can
be large). Returns { id, webViewLink }, as driveUpload does. */
export async function driveUploadFile(folder, name, mime, filePath) {
const { size } = await stat(filePath);
const start = await call(
`${DRIVE_UPLOAD}?uploadType=resumable&supportsAllDrives=true&fields=id,webViewLink`,
{
method: "POST",
headers: {
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": mime,
"X-Upload-Content-Length": String(size),
},
body: JSON.stringify({ name, parents: [await driveFolder(folder)] }),
},
DRIVE_SCOPE,
);
const session = start.headers.get("location");
if (!session) throw new GoogleError("Drive didn't start the upload.");
const res = await call(
session,
{
method: "PUT",
headers: { "Content-Type": mime, "Content-Length": String(size) },
body: Readable.toWeb(createReadStream(filePath)),
duplex: "half",
},
DRIVE_SCOPE,
undefined,
30 * 60_000,
);
return await res.json();
}
/* Anyone with the link can view: for files the public site links to. /* Anyone with the link can view: for files the public site links to.
Refused when the shared drive (or the Workspace) doesn't allow Refused when the shared drive (or the Workspace) doesn't allow
sharing outside the organization. */ sharing outside the organization. */

View file

@ -0,0 +1,10 @@
-- ═══════════════════════════════════════════════════════════════
-- 051 CLIPS SAVED TO DRIVE
--
-- Tools → Video clips → Save to Drive puts a finished clip in a folder
-- under the shared drive's Media folder, as a Files entry
-- (drive_files, 048). The job keeps which one, as it keeps its media
-- library copy in saved_media_id; a clip can be in both.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE clip_jobs ADD COLUMN saved_drive_file_id INTEGER REFERENCES drive_files (id) ON DELETE SET NULL;

View file

@ -13,6 +13,9 @@
gone out in full, unless saved gone out in full, unless saved
POST /clips/:id/save a finished clip into the media POST /clips/:id/save a finished clip into the media
library library
POST /clips/:id/drive { folder }: a finished clip into a
folder under Media in Drive, as a
Files entry (routes/files.js)
DELETE /clips/:id a job and its files (a source DELETE /clips/:id a job and its files (a source
takes its clips) takes its clips)
@ -23,6 +26,7 @@
import { createReadStream } from "node:fs"; import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises"; import { stat } from "node:fs/promises";
import path from "node:path";
import { Readable } from "node:stream"; import { Readable } from "node:stream";
import { Hono } from "hono"; import { Hono } from "hono";
@ -40,6 +44,9 @@ import {
toolVersions, toolVersions,
} from "../clips.js"; } from "../clips.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
import { UPLOADS_DIR } from "../media.js";
import { driveDelete, driveReady, driveShareWithAnyone, driveUploadFile } from "../googleService.js";
import { cleanFolder, inDrive, recordDriveUpload } from "./files.js";
const clips = new Hono(); const clips = new Hono();
@ -71,15 +78,19 @@ function shape(job) {
has_file: Boolean(job.file), has_file: Boolean(job.file),
saved_media_id: job.saved_media_id, saved_media_id: job.saved_media_id,
saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null, saved_url: job.saved_filename ? `/uploads/${job.saved_filename}` : null,
saved_drive: job.saved_drive_file_id
? { id: job.saved_drive_file_id, url: job.saved_drive_url, folder: job.saved_drive_folder }
: null,
downloaded_at: job.downloaded_at, downloaded_at: job.downloaded_at,
created_at: job.created_at, created_at: job.created_at,
finished_at: job.finished_at, finished_at: job.finished_at,
}; };
} }
const SELECT = `SELECT j.*, m.filename AS saved_filename const SELECT = `SELECT j.*, m.filename AS saved_filename, d.url AS saved_drive_url, d.folder AS saved_drive_folder
FROM clip_jobs j FROM clip_jobs j
LEFT JOIN media m ON m.id = j.saved_media_id`; LEFT JOIN media m ON m.id = j.saved_media_id
LEFT JOIN drive_files d ON d.id = j.saved_drive_file_id`;
function findOr404(c) { function findOr404(c) {
const id = Number(c.req.param("id")); const id = Number(c.req.param("id"));
@ -210,6 +221,49 @@ clips.post("/clips/:id/save", async (c) => {
return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE); return c.json({ media, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE);
}); });
/* Into Drive: the working file, or once it's gone into the library,
the library's copy. It stays wherever it was, so a clip can be in
both, and the day's sweep still clears the working file. */
clips.post("/clips/:id/drive", async (c) => {
const db = c.get("db");
const job = findOr404(c);
if (job.kind !== "clip" || job.status !== "done") throw new ClipError(400, "Only a finished clip can be saved.");
if (job.saved_drive_file_id) throw new ClipError(409, "It's already in Drive.");
if (!driveReady()) throw new ClipError(400, "Google Drive isn't set up on the server (docs/google-drive-and-mail.md).");
const folder = cleanFolder((await body(c)).folder);
if (folder === null) throw new ClipError(422, "That isn't a folder name.");
const from = fileOf(job) ?? (job.saved_filename ? path.join(UPLOADS_DIR, job.saved_filename) : null);
if (!from) throw new ClipError(410, "That clip's file is gone. Make it again.");
const audio = from.endsWith(".mp3");
const mime = audio ? "audio/mpeg" : "video/mp4";
const params = job.params ? JSON.parse(job.params) : {};
const stamp = (s) => `${Math.floor(s / 60)}m${String(Math.floor(s % 60)).padStart(2, "0")}s`;
const name = `${(job.title ?? "Clip").replace(/[\u0000-\u001f"\\/]+/g, " ").trim().slice(0, 120) || "Clip"} (${stamp(params.start ?? 0)} to ${stamp(params.end ?? 0)}).${audio ? "mp3" : "mp4"}`;
let uploaded;
try {
uploaded = await driveUploadFile(inDrive(folder), name, mime, from);
} catch (err) {
console.warn(`clips: clip ${job.id} to Drive failed: ${err.message}`);
throw new ClipError(502, `Google Drive didn't take it: ${err.message}`);
}
try {
await driveShareWithAnyone(uploaded.id);
} catch (err) {
await driveDelete(uploaded.id).catch(() => {});
throw new ClipError(
502,
`Drive wouldn't share it with anyone who has the link (${err.message}). The sharing settings must allow sharing outside the organization.`,
);
}
const { size } = await stat(from);
const file = await recordDriveUpload(db, uploaded, { name, mime, bytes: size, folder, userId: c.get("user").id });
db.prepare(`UPDATE clip_jobs SET saved_drive_file_id = ? WHERE id = ?`).run(file.id, job.id);
console.log(`clips: clip ${job.id} saved to Drive (${inDrive(folder)}) by ${c.get("user").email}`);
return c.json({ file, job: shape(db.prepare(`${SELECT} WHERE j.id = ?`).get(job.id)) }, 200, NO_STORE);
});
clips.delete("/clips/:id", async (c) => { clips.delete("/clips/:id", async (c) => {
const job = findOr404(c); const job = findOr404(c);
if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish."); if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish.");

View file

@ -65,7 +65,7 @@ import { NO_STORE } from "../shape.js";
const files = new Hono(); const files = new Hono();
files.use("*", requireAuth); files.use("*", requireAuth);
const FOLDER = "Media"; export const FOLDER = "Media";
const MAX_DEPTH = 3; const MAX_DEPTH = 3;
/* A folder path as given, cleaned: '' for FOLDER itself, or up to /* A folder path as given, cleaned: '' for FOLDER itself, or up to
@ -79,7 +79,19 @@ export function cleanFolder(value) {
if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null; if (parts.length > MAX_DEPTH || parts.some((part) => part.length > 60 || part === "." || part === "..")) return null;
return parts.join("/"); return parts.join("/");
} }
const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER); export const inDrive = (folder) => (folder ? `${FOLDER}/${folder}` : FOLDER);
/* A file just uploaded to Drive (and shared) into the list: its row,
and the first try at its preview (more follow on their own).
Returns what the list shows. Also how the clip tool's Save to Drive
lands (routes/clips.js). */
export async function recordDriveUpload(db, uploaded, { name, mime, bytes, folder, userId }) {
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, bytes, uploaded.webViewLink, folder, userId).lastInsertRowid;
await fetchPreview(db, db.prepare(`${SELECT} WHERE f.id = ?`).get(id), userId);
return shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id));
}
const MAX_FILE_BYTES = 50 * 1024 * 1024; const MAX_FILE_BYTES = 50 * 1024 * 1024;
const MAX_LIST = 500; const MAX_LIST = 500;
// Seconds after upload to ask Drive for the preview again. // Seconds after upload to ask Drive for the preview again.
@ -270,15 +282,10 @@ files.post(
); );
} }
const id = db
.prepare(`INSERT INTO drive_files (drive_id, name, mime, bytes, url, folder, uploaded_by) VALUES (?, ?, ?, ?, ?, ?, ?)`)
.run(uploaded.id, name, mime, buffer.length, uploaded.webViewLink, folder, user.id).lastInsertRowid;
const row = db.prepare(`${SELECT} WHERE f.id = ?`).get(id);
console.log(`files: ${name} uploaded by ${user.email}`); console.log(`files: ${name} uploaded by ${user.email}`);
// The first preview try is waited for; Drive often has it already.
// The first try is waited for; Drive often has the picture already. const saved = await recordDriveUpload(db, uploaded, { name, mime, bytes: buffer.length, folder, userId: user.id });
await fetchPreview(db, row, user.id); return c.json({ file: saved }, 201, NO_STORE);
return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE);
}, },
); );

View file

@ -38,6 +38,8 @@ type Job = {
has_file: boolean; has_file: boolean;
saved_media_id: number | null; saved_media_id: number | null;
saved_url: string | null; saved_url: string | null;
/** In Drive, under Media (Save to Drive): its Files entry. */
saved_drive: { id: number; url: string; folder: string } | null;
downloaded_at: string | null; downloaded_at: string | null;
}; };
@ -87,6 +89,80 @@ const primary =
const input = const input =
"rounded-lg 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"; "rounded-lg 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 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. */
function SaveToDrive({ clip, onSaved }: { clip: Job; onSaved: () => void }) {
const [folders, setFolders] = useState<string[] | null>(null);
const [folder, setFolder] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const audio = clip.params?.format === "audio";
async function open() {
setError(null);
try {
const data = await get("/admin/files", { ttl: 0 });
if (!data.ready) return setError("Google Drive isn't set up on the server.");
const list: string[] = data.folders ?? [];
setFolders(list);
const wanted = audio ? /^audio$/i : /^videos?$/i;
setFolder(list.find((f) => wanted.test(f)) ?? "");
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't load the folders.");
}
}
async function save() {
setBusy(true);
setError(null);
try {
await post(`/admin/clips/${clip.id}/drive`, { folder });
onSaved();
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't save it to Drive.");
setBusy(false);
}
}
return (
<>
{folders === null ? (
<button type="button" className={button} onClick={open}>
Save to Drive
</button>
) : (
<span className="flex flex-wrap items-center gap-2">
<label className="sr-only" htmlFor={`drive-folder-${clip.id}`}>
Folder in Drive
</label>
<select
id={`drive-folder-${clip.id}`}
value={folder}
disabled={busy}
onChange={(e) => setFolder(e.target.value)}
className="rounded-lg border border-muted/25 bg-surface px-2 py-1 text-sm text-body"
>
<option value="">Media (not in a folder)</option>
{folders.map((f) => (
<option key={f} value={f}>
Media/{f}
</option>
))}
</select>
<button type="button" className={button} disabled={busy} onClick={save}>
{busy ? "Uploading…" : "Save"}
</button>
<button type="button" className="text-sm" style={{ color: MUTED }} onClick={() => setFolders(null)}>
Cancel
</button>
</span>
)}
{error && <span className="text-sm text-danger">{error}</span>}
</>
);
}
function Card({ title, children }: { title: string; children: ReactNode }) { function Card({ title, children }: { title: string; children: ReactNode }) {
return ( return (
<section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5"> <section className="mt-6 rounded-2xl border border-brand/20 bg-surface p-5">
@ -484,7 +560,15 @@ export default function AdminClips() {
In the media library In the media library
</Link> </Link>
)} )}
{clip.status === "done" && !clip.has_file && !clip.saved_url && ( {clip.status === "done" && !clip.saved_drive && (clip.has_file || clip.saved_url) && (
<SaveToDrive clip={clip} onSaved={load} />
)}
{clip.saved_drive && (
<a href={clip.saved_drive.url} target="_blank" rel="noreferrer" className="text-sm underline" style={{ color: accentText(BRAND) }}>
In Drive: Media{clip.saved_drive.folder ? `/${clip.saved_drive.folder}` : ""}
</a>
)}
{clip.status === "done" && !clip.has_file && !clip.saved_url && !clip.saved_drive && (
<span className="text-sm" style={{ color: MUTED }}> <span className="text-sm" style={{ color: MUTED }}>
Downloaded, and deleted from the server Downloaded, and deleted from the server
</span> </span>
@ -505,7 +589,7 @@ export default function AdminClips() {
))} ))}
</ul> </ul>
<p className="mt-3 text-xs" style={{ color: MUTED }}> <p className="mt-3 text-xs" style={{ color: MUTED }}>
A clip is deleted from the server once it's downloaded, unless it's saved to the library first. A clip is deleted from the server once it's downloaded, unless it's saved to the library first. Save to Drive puts a copy in a folder under Media in the shared Drive, as a Files entry pages can link to.
Everything here is cleared a day after it's made. Everything here is cleared a day after it's made.
</p> </p>
</Card> </Card>