Let the clip tool save a clip to a Drive folder

Save to Drive, beside Save to library, puts a finished clip in a folder
under Media (Videos or Audio chosen first to match it) as a Files
entry, shared by link, so pages can link to it (migration 051). The
clip streams from disk through a resumable upload, so a long one
isn't read into memory. A clip can be in both the library and Drive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 23:29:28 -05:00
parent e1542d8d87
commit 42d1536ee6
6 changed files with 219 additions and 17 deletions

View file

@ -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. */

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
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.");

View file

@ -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);
},
);