diff --git a/docs/video-clips.md b/docs/video-clips.md index 3271885..90a558a 100644 --- a/docs/video-clips.md +++ b/docs/video-clips.md @@ -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 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 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`. diff --git a/server/src/googleService.js b/server/src/googleService.js index e1234d2..214edc5 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -32,7 +32,9 @@ 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"; const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive"; @@ -99,11 +101,11 @@ async function accessToken(scope, subject) { 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, { ...init, headers: { ...init.headers, Authorization: `Bearer ${await accessToken(scope, subject)}` }, - signal: AbortSignal.timeout(60_000), + signal: AbortSignal.timeout(timeoutMs), }); if (!res.ok) { 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. Refused when the shared drive (or the Workspace) doesn't allow sharing outside the organization. */ diff --git a/server/src/migrations/051_clip_drive.sql b/server/src/migrations/051_clip_drive.sql new file mode 100644 index 0000000..d352968 --- /dev/null +++ b/server/src/migrations/051_clip_drive.sql @@ -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; diff --git a/server/src/routes/clips.js b/server/src/routes/clips.js index 70586ad..c899217 100644 --- a/server/src/routes/clips.js +++ b/server/src/routes/clips.js @@ -13,6 +13,9 @@ gone out in full, unless saved POST /clips/:id/save a finished clip into the media 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 takes its clips) @@ -23,6 +26,7 @@ import { createReadStream } from "node:fs"; import { stat } from "node:fs/promises"; +import path from "node:path"; import { Readable } from "node:stream"; import { Hono } from "hono"; @@ -40,6 +44,9 @@ import { toolVersions, } from "../clips.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(); @@ -71,15 +78,19 @@ function shape(job) { has_file: Boolean(job.file), saved_media_id: job.saved_media_id, 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, created_at: job.created_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 - 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) { 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); }); +/* 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) => { const job = findOr404(c); if (job.status === "running") throw new ClipError(409, "It's running. Wait for it to finish."); diff --git a/server/src/routes/files.js b/server/src/routes/files.js index 08388f5..0b15465 100644 --- a/server/src/routes/files.js +++ b/server/src/routes/files.js @@ -65,7 +65,7 @@ import { NO_STORE } from "../shape.js"; const files = new Hono(); files.use("*", requireAuth); -const FOLDER = "Media"; +export const FOLDER = "Media"; const MAX_DEPTH = 3; /* 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; 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_LIST = 500; // 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}`); - - // The first try is waited for; Drive often has the picture already. - await fetchPreview(db, row, user.id); - return c.json({ file: shape(db.prepare(`${SELECT} WHERE f.id = ?`).get(id)) }, 201, NO_STORE); + // The first preview try is waited for; Drive often has it already. + const saved = await recordDriveUpload(db, uploaded, { name, mime, bytes: buffer.length, folder, userId: user.id }); + return c.json({ file: saved }, 201, NO_STORE); }, ); diff --git a/src/pages/admin/AdminClips.tsx b/src/pages/admin/AdminClips.tsx index 0c27dc7..8a37d43 100644 --- a/src/pages/admin/AdminClips.tsx +++ b/src/pages/admin/AdminClips.tsx @@ -38,6 +38,8 @@ type Job = { has_file: boolean; saved_media_id: number | 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; }; @@ -87,6 +89,80 @@ const primary = 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"; +/* 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(null); + const [folder, setFolder] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(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 ? ( + + ) : ( + + + + + + + )} + {error && {error}} + + ); +} + function Card({ title, children }: { title: string; children: ReactNode }) { return (
@@ -484,7 +560,15 @@ export default function AdminClips() { In the media library )} - {clip.status === "done" && !clip.has_file && !clip.saved_url && ( + {clip.status === "done" && !clip.saved_drive && (clip.has_file || clip.saved_url) && ( + + )} + {clip.saved_drive && ( + + In Drive: Media{clip.saved_drive.folder ? `/${clip.saved_drive.folder}` : ""} + + )} + {clip.status === "done" && !clip.has_file && !clip.saved_url && !clip.saved_drive && ( Downloaded, and deleted from the server @@ -505,7 +589,7 @@ export default function AdminClips() { ))}

- 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.