Cotton code
458 lines · 23.1 KB · TypeScriptRaw
/** * FOUR FREE FILMS INTO FILMS (owner, 30 Oct 2026: "if there's some movie * that's open source that you can download and put in the database, that * would be great to view it"): the Blender Foundation's open movies, each * downloaded from download.blender.org, kept as the object's media and named * by one film row, so the film viewer plays it full screen. * *   pnpm films:seed-open --base <url> --token-file <path> [--cache <dir>] [--wait <seconds>] * * --base        the Worker's address for the object: http://127.0.0.1:8787/b/<slug> under *               `wrangler dev`, https://cottondb.com for the owner's own (the token names it). * --token-file  a file holding an owner `ctn_` token of that object; never printed. A dev seeding tool: it *               writes film rows in the clear for the object to seal, which a device may not, so it runs only *               on an account with token scopes off (TOKEN-SCOPES-GO-LIVE.md). * --cache       where the downloads and the prepared files are kept (default *               ~/.cache/cottondb/open-films); a second run downloads nothing. * --wait        how long the run waits for the object's artwork engine (src/artwork.ts) *               to fill each poster (default 120 s). * * Each film: the official file is downloaded (and unzipped where Blender * ships it zipped) and sent as it is when it is an MP4 or a MOV, which the * phone's player (AVFoundation) opens; Sintel, which Blender ships only as * MKV, which it does not, is remuxed by ffmpeg into an MP4 by stream copy — * no frame or sample re-encoded, its subtitles as MP4 text tracks. (A MOV is * not remuxed too: Tears of Steel's MP3 track, copied into an MP4, is one * AVFoundation no longer hears.) The Worker takes each in parts * (`POST /v1/media/<key>?uploads`, src/media.ts) under * `<database id>/videos/<sha256>.<mp4|mov>`. Its row (title, year, kind film, * status want_to_watch, its director and length, and a review saying its licence * and source) names that key in the film table's player column — the column * its slip plays from (`slip.player`), which the phone's viewer opens full * screen — and leaves the poster EMPTY: the object's artwork engine fills it * from Wikidata. The run waits for each poster; one the engine did not fill * is the film's official poster, uploaded by the run and said so. * * A film table whose slip names no player column has nowhere to hold a * film's file, and the run refuses before it downloads anything. * * IDEMPOTENT: a film is found by its title and year among the object's * films; one already holding its file is left as it is, so a second run * changes nothing (media go by key: the object answers `stored: false`). * * Tests: `pnpm -s test:scripts` (films-seed-open.test.ts), and the run against * `wrangler dev`: `pnpm -s exec tsx scripts/__tests__/e2e-films-seed-open.ts`. */import { spawnSync } from "node:child_process";import { createHash } from "node:crypto";import { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";import { open } from "node:fs/promises";import { homedir } from "node:os";import { isAbsolute, join, resolve } from "node:path";import { Readable } from "node:stream";import { pipeline } from "node:stream/promises";import { pathToFileURL } from "node:url";export class SeedRefusal extends Error {}/** One open movie: where its file comes from, and what its row says. */export interface OpenFilm {  /** The prepared file's name in the cache. */  slug: string;  title: string;  year: string;  director: string;  /** The official download. */  url: string;  /** Its size in bytes, as download.blender.org lists it. */  bytes: number;  /** The file inside, when the download is a zip. */  inside: string | null;  /** What the file is: its frame and its tracks. */  what: string;  licence: string;  attribution: string;  /** The film's official poster, uploaded when the artwork engine fills none. */  poster: string;}export const FILMS: OpenFilm[] = [  {    slug: "big-buck-bunny",    title: "Big Buck Bunny",    year: "2008",    director: "Sacha Goedegebure",    url: "https://download.blender.org/demo/movies/BBB/bbb_sunflower_1080p_30fps_normal.mp4.zip",    bytes: 275_524_128,    inside: "bbb_sunflower_1080p_30fps_normal.mp4",    what: "the 1080p 30 fps MP4 (H.264, stereo MP3 and 5.1 AC-3)",    licence: "CC BY 3.0",    attribution: "© copyright 2008, Blender Foundation / www.bigbuckbunny.org",    poster: "https://peach.blender.org/wp-content/uploads/poster_bunny_big.jpg",  },  {    slug: "sintel",    title: "Sintel",    year: "2010",    director: "Colin Levy",    url: "https://download.blender.org/durian/movies/Sintel.2010.1080p.mkv",    bytes: 1_180_090_590,    inside: null,    what: "the 1080p release (H.264, 5.1 AC-3, its subtitles), shipped as MKV only, remuxed to MP4 without re-encoding",    licence: "CC BY 3.0",    attribution: "© copyright Blender Foundation | durian.blender.org",    poster: "https://commons.wikimedia.org/wiki/Special:FilePath/Sintel_poster.jpg?width=1000",  },  {    slug: "tears-of-steel",    title: "Tears of Steel",    year: "2012",    director: "Ian Hubert",    url: "https://download.blender.org/demo/movies/ToS/tears_of_steel_1080p.mov.zip",    bytes: 583_774_281,    inside: "tears_of_steel_1080p.mov",    what: "the 1080p release (H.264, stereo MP3), shipped as MOV",    licence: "CC BY 3.0",    attribution: "(CC) Blender Foundation | mango.blender.org",    poster: "https://commons.wikimedia.org/wiki/Special:FilePath/Tos-poster.png?width=1000",  },  {    slug: "elephants-dream",    title: "Elephants Dream",    year: "2006",    director: "Bassam Kurdali",    url: "https://download.blender.org/ED/elephantsdream-1024-h264-st-aac.mov",    bytes: 326_632_467,    inside: null,    what: "the largest H.264 release, 1024×576 (stereo AAC), shipped as MOV; no 1080p exists",    licence: "CC BY 2.5",    attribution: "© copyright 2006, Blender Foundation / Netherlands Media Art Institute / www.elephantsdream.org",    poster: "https://download.blender.org/ED/cover.jpg",  },];/** The row's review (where the old film's notes went, Cinemas 5 Nov 2026): its licence and where its file came from. */export function notesOf(film: OpenFilm): string {  return `A Blender Foundation open movie, licensed ${film.licence}: ${film.attribution}. Source: ${film.url} (${film.what}).`;}/** Each part of an upload but the last: past R2's 5 MB floor, under the Worker's 100 MB request. */export const PART_BYTES = 64 * 1024 * 1024;export interface SeedArgs {  base: string;  token: string;  cache: string;  waitSeconds: number;}export function parseArgs(argv: string[], cwd = process.env.INIT_CWD ?? process.cwd()): SeedArgs {  const value = (name: string): string | undefined => {    const i = argv.indexOf(`--${name}`);    if (i < 0) return undefined;    const v = argv[i + 1];    if (!v || v.startsWith("--")) throw new SeedRefusal(`--${name} needs a value`);    return v;  };  const known = new Set(["base", "token-file", "cache", "wait"]);  for (const a of argv) if (a.startsWith("--") && !known.has(a.slice(2))) throw new SeedRefusal(`unknown flag ${a}`);  const path = (p: string): string => (p.startsWith("~/") ? join(homedir(), p.slice(2)) : isAbsolute(p) ? p : resolve(cwd, p));  const base = value("base")?.replace(/\/+$/, "");  if (!base || !/^https?:\/\//.test(base)) throw new SeedRefusal("--base is the object's address: http://127.0.0.1:8787/b/<slug> under wrangler dev, or https://cottondb.com");  const file = value("token-file");  if (!file) throw new SeedRefusal("--token-file names a file holding an owner ctn_ token of the object");  let token: string;  try {    token = readFileSync(path(file), "utf8").trim();  } catch {    throw new SeedRefusal(`--token-file ${file} cannot be read`);  }  if (!token.startsWith("ctn_")) throw new SeedRefusal(`--token-file ${file} holds no ctn_ token`);  const wait = Number(value("wait") ?? "120");  if (!Number.isFinite(wait) || wait < 0) throw new SeedRefusal("--wait is a number of seconds");  return { base, token, cache: path(value("cache") ?? "~/.cache/cottondb/open-films"), waitSeconds: wait };}// ── the object ───────────────────────────────────────────────────────────type Doc = Record<string, unknown>;/** The object's side: its definitions, its films, its acts and its media, all with the owner token. */export class Client {  readonly base: string;  private readonly token: string;  private readonly fetcher: typeof fetch;  constructor(base: string, token: string, fetcher: typeof fetch = fetch) {    this.base = base;    this.token = token;    this.fetcher = fetcher;  }  async call<T = Doc>(method: string, path: string, body?: unknown, raw?: { bytes: Uint8Array; type: string }): Promise<T> {    let r: Response;    try {      r = await this.fetcher(`${this.base}${path}`, {        method,        headers: { authorization: `Bearer ${this.token}`, ...(raw ? { "content-type": raw.type } : body !== undefined ? { "content-type": "application/json" } : {}) },        body: raw ? raw.bytes : body !== undefined ? JSON.stringify(body) : undefined,      });    } catch (error) {      throw new SeedRefusal(`${method} ${this.base}${path}: ${(error as Error).message}`);    }    const text = await r.text();    if (!r.ok) throw new SeedRefusal(`${method} ${path} → ${r.status} ${text.slice(0, 400)}`);    return (text ? JSON.parse(text) : {}) as T;  }  /** The object's database id and its film table. */  async definitions(): Promise<{ databaseId: string; film: Doc | null }> {    const answer = await this.call<{ business?: { database_id?: string | null }; tables?: Doc[] }>("GET", "/v1/definitions");    const databaseId = answer.business?.database_id;    if (!databaseId) throw new SeedRefusal("the object names no database id: it is not a personal database");    return { databaseId, film: (answer.tables ?? []).find((t) => t.id === "film") ?? null };  }  /** One Cotton MCP tool's answer. */  async tool<T = Doc>(name: string, args: Doc): Promise<T> {    const answer = await this.call<{ result?: { isError?: boolean; content?: { text?: string }[] }; error?: { message?: string } }>("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } });    const text = answer.result?.content?.[0]?.text ?? "";    if (!answer.result || answer.result.isError) throw new SeedRefusal(`${name}: ${answer.error?.message ?? text}`);    return JSON.parse(text) as T;  }  /** Every live film row. */  async films(): Promise<{ id: string; data: Doc }[]> {    const out: { id: string; data: Doc }[] = [];    let page: number | null = 0;    while (page !== null) {      const answer: { records: { id: string; data: Doc }[]; next_page: number | null } = await this.tool("list_records", { table: "film", limit: 500, page });      out.push(...answer.records);      page = answer.next_page;    }    return out;  }  async act(act: "create" | "update", args: Doc): Promise<string> {    const answer = await this.call<{ made?: { id: string } }>("POST", "/v1/act", { act, args });    return answer.made?.id ?? String(args.id);  }  private path(key: string): string {    return `/v1/media/${key.split("/").map(encodeURIComponent).join("/")}`;  }  /** A file under `key`, in parts: answers whether it was sent (false: the object held those bytes). */  async upload(key: string, file: string, size: number, type: string, partBytes = PART_BYTES): Promise<boolean> {    const started = await this.call<{ stored?: boolean; upload?: string }>("POST", `${this.path(key)}?uploads`, { size, content_type: type });    if (started.stored === false) return false;    if (!started.upload) throw new SeedRefusal(`the object started no upload for ${key}`);    const handle = await open(file, "r");    const parts: { part: number; etag: string }[] = [];    try {      for (let at = 0, part = 1; at < size; at += partBytes, part++) {        const length = Math.min(partBytes, size - at);        const bytes = new Uint8Array(length);        const { bytesRead } = await handle.read(bytes, 0, length, at);        if (bytesRead !== length) throw new SeedRefusal(`${file} is shorter than ${size} bytes`);        const sent = await this.call<{ part: number; etag: string }>("PUT", `${this.path(key)}?upload=${encodeURIComponent(started.upload)}&part=${part}`, undefined, { bytes, type: "application/octet-stream" });        parts.push({ part: sent.part, etag: sent.etag });      }    } finally {      await handle.close();    }    await this.call("POST", `${this.path(key)}?upload=${encodeURIComponent(started.upload)}`, { parts });    return true;  }  /** Bytes in hand under `key`, in one request. */  async put(key: string, bytes: Uint8Array, type: string): Promise<void> {    await this.call("PUT", this.path(key), undefined, { bytes, type });  }}/** The film table's player column: the file column its slip plays from. */export function playerOf(film: Doc | null): string {  if (!film) throw new SeedRefusal("the object has no film table: it does not hold the personal kit's Films");  const player = (film.slip as Doc | undefined)?.player;  const column = (Array.isArray(film.columns) ? (film.columns as Doc[]) : []).find((c) => c.key === player);  if (typeof player !== "string" || column?.type !== "file") {    throw new SeedRefusal(      "the film table's slip names no player column (a `file` column the viewer plays from, `slip.player`), so a film row has nowhere to hold its file; nothing was downloaded or sent",    );  }  return player;}/** What the run does about one film: make its row, give its row the file, or nothing. */export type Plan = { make: Doc } | { give: { id: string; data: Doc } } | { keep: string } | { taken: string };/** The film's row among `rows`, by its title (any case) and year; what to do about it. */export function plan(film: OpenFilm, rows: { id: string; data: Doc }[], player: string, key: string, minutes: number): Plan {  const same = (s: unknown): string => String(s ?? "").trim().toLowerCase();  const held = rows.find((r) => same(r.data.title) === same(film.title) && (same(r.data.year) === film.year || same(r.data.year) === ""));  if (!held) return { make: { title: film.title, year: film.year, kind: "film", status: "want_to_watch", director: film.director, minutes, review: notesOf(film), [player]: key } };  const file = held.data[player];  if (file === key) return { keep: held.id };  if (typeof file === "string" && file !== "") return { taken: held.id };  return { give: { id: held.id, data: { [player]: key } } };}// ── the files ────────────────────────────────────────────────────────────/** A film's prepared file: where it is, its type, size, digest and length. */export interface Prepared {  path: string;  /** `video/mp4` or `video/quicktime`, and the key's extension for it. */  type: string;  ext: "mp4" | "mov";  size: number;  sha256: string;  minutes: number;}function run(command: string, args: string[]): string {  const r = spawnSync(command, args, { encoding: "utf8", maxBuffer: 1 << 24 });  if (r.error) throw new SeedRefusal(`${command} could not run: ${r.error.message} (install it: brew install ${command === "unzip" ? "unzip" : "ffmpeg"})`);  if (r.status !== 0) throw new SeedRefusal(`${command} ${args.join(" ")} failed: ${r.stderr.slice(-600)}`);  return r.stdout;}async function download(url: string, to: string, bytes: number, say: (line: string) => void): Promise<void> {  if (existsSync(to) && statSync(to).size === bytes) return;  say(`  downloading ${url} (${(bytes / 1e6).toFixed(0)} MB)`);  const res = await fetch(url);  if (!res.ok || !res.body) throw new SeedRefusal(`${url} answered ${res.status}`);  await pipeline(Readable.fromWeb(res.body as import("node:stream/web").ReadableStream), createWriteStream(`${to}.part`));  const got = statSync(`${to}.part`).size;  if (got !== bytes) throw new SeedRefusal(`${url} came as ${got} bytes, not the ${bytes} download.blender.org lists`);  renameSync(`${to}.part`, to);}async function digest(path: string): Promise<string> {  const hash = createHash("sha256");  await pipeline(createReadStream(path), hash);  return hash.digest("hex");}/** The containers the phone's player opens, sent as Blender ships them. */const PLAYS: Record<string, { type: string; ext: "mp4" | "mov" }> = { mp4: { type: "video/mp4", ext: "mp4" }, m4v: { type: "video/mp4", ext: "mp4" }, mov: { type: "video/quicktime", ext: "mov" } };/** The film downloaded (once), unzipped where it is zipped, and remuxed to an MP4 by stream copy (once) where the phone's player cannot open it as it comes. */export async function prepare(film: OpenFilm, cache: string, say: (line: string) => void): Promise<Prepared> {  mkdirSync(cache, { recursive: true });  const downloaded = join(cache, film.url.split("/").pop()!);  const name = film.inside ?? film.url.split("/").pop()!;  const plays = PLAYS[name.split(".").pop()!.toLowerCase()];  const path = resolve(plays ? join(cache, name) : join(cache, `${film.slug}.mp4`));  if (!existsSync(path)) {    await download(film.url, downloaded, film.bytes, say);    if (film.inside) run("unzip", ["-o", "-q", downloaded, film.inside, "-d", cache]);    if (!plays) {      say(`  remuxing ${film.title} to MP4 (stream copy)`);      const source = join(cache, name);      const subtitles = run("ffprobe", ["-v", "error", "-select_streams", "s", "-show_entries", "stream=index", "-of", "csv=p=0", source]).trim() !== "";      run("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-i", source, "-map", "0:v", "-map", "0:a", ...(subtitles ? ["-map", "0:s", "-c:s", "mov_text"] : []), "-c:v", "copy", "-c:a", "copy", "-movflags", "+faststart", "-f", "mp4", `${path}.part`]);      renameSync(`${path}.part`, path);    }  }  if (!existsSync(path)) throw new SeedRefusal(`${film.title}: ${path} is not there after its download`);  const seconds = Number(run("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", path]).trim());  const { type, ext } = plays ?? PLAYS.mp4!;  return { path, type, ext, size: statSync(path).size, sha256: await digest(path), minutes: Math.round(seconds / 60) };}// ── the run ──────────────────────────────────────────────────────────────export interface FilmRun {  title: string;  id: string;  key: string;  bytes: number;  /** Whether the file was sent (false: the object held it). */  sent: boolean;  row: "made" | "given its file" | "kept" | "holds another file";  poster: "filled by the engine" | "official poster uploaded" | "was there" | "still empty";}export interface Deps {  fetch: typeof fetch;  prepare: (film: OpenFilm, cache: string, say: (line: string) => void) => Promise<Prepared>;  sleep: (ms: number) => Promise<void>;  partBytes: number;}const DEPS: Deps = { fetch, prepare, sleep: (ms) => new Promise((r) => setTimeout(r, ms)), partBytes: PART_BYTES };const PICTURES: Record<string, string> = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp" };export async function seed(args: SeedArgs, say: (line: string) => void = console.log, deps: Deps = DEPS, films: OpenFilm[] = FILMS): Promise<FilmRun[]> {  const client = new Client(args.base, args.token, deps.fetch);  const { databaseId, film: definition } = await client.definitions();  const player = playerOf(definition);  const runs: FilmRun[] = [];  for (const film of films) {    say(`${film.title} (${film.year})`);    const prepared = await deps.prepare(film, args.cache, say);    const key = `${databaseId}/videos/${prepared.sha256}.${prepared.ext}`;    const sent = await client.upload(key, prepared.path, prepared.size, prepared.type, deps.partBytes);    say(`  ${sent ? "sent" : "held already"}: ${key} (${(prepared.size / 1e6).toFixed(1)} MB)`);    const step = plan(film, await client.films(), player, key, prepared.minutes);    let id: string;    let row: FilmRun["row"];    if ("make" in step) {      id = await client.act("create", { table: "film", data: step.make });      row = "made";    } else if ("give" in step) {      id = await client.act("update", { table: "film", id: step.give.id, data: step.give.data });      row = "given its file";    } else if ("keep" in step) {      id = step.keep;      row = "kept";    } else {      id = step.taken;      row = "holds another file";    }    say(`  row ${id}: ${row}`);    runs.push({ title: film.title, id, key, bytes: prepared.size, sent, row, poster: "still empty" });  }  // The posters: the artwork engine fills each off the write that made its row; one it did not is the film's official poster.  const waiting = async (): Promise<Map<string, unknown>> => new Map((await client.films()).map((r) => [r.id, r.data.poster]));  const before = await waiting();  for (const r of runs) if (r.row !== "made" && typeof before.get(r.id) === "string" && before.get(r.id) !== "") r.poster = "was there";  const deadline = Date.now() + args.waitSeconds * 1000;  for (;;) {    const now = await waiting();    for (const r of runs) if (r.poster === "still empty" && typeof now.get(r.id) === "string" && now.get(r.id) !== "") r.poster = "filled by the engine";    if (!runs.some((r) => r.poster === "still empty") || Date.now() >= deadline) break;    await deps.sleep(3000);  }  for (const r of runs.filter((x) => x.poster === "still empty")) {    const film = films.find((f) => f.title === r.title)!;    const res = await deps.fetch(film.poster, { headers: { "user-agent": "Cotton films seed (https://cottondb.com)" } });    const type = (res.headers.get("content-type") ?? "").split(";")[0]!.trim();    if (!res.ok || !PICTURES[type]) throw new SeedRefusal(`${film.title}: the engine filled no poster and ${film.poster} answered ${res.status} ${type}`);    const bytes = new Uint8Array(await res.arrayBuffer());    const key = `${databaseId}/photos/${createHash("sha256").update(bytes).digest("hex")}.${PICTURES[type]}`;    await client.put(key, bytes, type);    await client.act("update", { table: "film", id: r.id, data: { poster: key } });    r.poster = "official poster uploaded";    say(`${film.title}: the artwork engine filled no poster in ${args.waitSeconds} s; the official poster ${film.poster} was uploaded as ${key}`);  }  return runs;}async function main(): Promise<void> {  const args = parseArgs(process.argv.slice(2));  const runs = await seed(args);  const width = Math.max(...runs.map((r) => r.title.length));  console.log(`\nOPEN FILMS · ${args.base}`);  for (const r of runs) console.log(`${r.title.padEnd(width)}  ${(r.bytes / 1e6).toFixed(1).padStart(7)} MB  ${r.sent ? "sent" : "held"}  row ${r.row}  poster ${r.poster}`);}if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {  main().catch((error: unknown) => {    console.error(error instanceof SeedRefusal ? error.message : ((error as Error).stack ?? String(error)));    process.exit(1);  });}