/** * The media the brought rows name, found in the Mac's store and sent to the * object's R2 under the row's own key (src/media.ts). * * WHICH KEYS. The columns cotton-store's MEDIA_KEY_HOLDERS names (a bare key; * a JSON list of `{ key, playbackKey? }`; a meeting's `segments` of * `{ path, lost? }`), an email's attachments, a release's assets and a * feedback screenshot (`<db>/walkthroughs/<sha>.<ext>`, from its sha and * extension), plus every file under a meeting's own folder (its `full.<ext>` * is named by no column). Media a row has let go of (a story's * `media_dropped_at`, a meeting's `audio_deleted_at`) stay behind. Thumbnail * tiers (`.t256.jpg`, `.d1600.jpg`) are named by no row, so none goes: the * phone asks the object for the size it draws. * * THE STORE. `media/<key>` in the real data folder, the content type in * `.meta/<key>.json` (fs_object_store.rs), else read from the extension. */import { existsSync, readdirSync, readFileSync, statSync } from"node:fs";import { join, relative } from"node:path";importtype { ImportRow } from"./plan.ts";const TEXT: Record<string, string[]> = { photo: ["key"], video: ["key", "poster_key"], sighting: ["key"], story: ["media_key"], message_contact: ["avatar_key"], thread: ["photo_key"], person: ["avatar_key"], document: ["storage_path", "decrypted_path"], repo_bundle: ["object_key"], repo_job: ["log_key"],};const ITEMS: Record<string, string[]> = { message: ["media"], post: ["media"], session_message: ["media"], email: ["attachments"], release: ["assets_json"],};/** Every table and column a key may sit in, for the test that holds them to the package. */exportconst HOLDERS: Record<string, string[]> = { ...Object.fromEntries(Object.entries(TEXT).map(([t, c]) => [t, c])), ...Object.fromEntries(Object.entries(ITEMS).map(([t, c]) => [t, c])), meeting: ["segments", "audio_deleted_at"], story: ["media_key", "media_dropped_at"], feedback: ["image_sha256", "image_ext"],};const TYPES: Record<string, string> = { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", webp: "image/webp", gif: "image/gif", heic: "image/heic", heif: "image/heif", avif: "image/avif", mp4: "video/mp4", mov: "video/quicktime", m4v: "video/x-m4v", m4a: "audio/mp4", mp3: "audio/mpeg", aac: "audio/aac", opus: "audio/ogg", ogg: "audio/ogg", wav: "audio/wav", pdf: "application/pdf", txt: "text/plain", json: "application/json", zip: "application/zip",};/** What one upload through the Worker may weigh (src/media.ts MEDIA_MAX_BYTES). */exportconst UPLOAD_MAX_BYTES = 100 * 1024 * 1024;const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v : null);/** Every media key the rows name, each with the first row that names it. */exportfunction namedKeys(rows: ImportRow[], databaseId: string, root: string | null): Map<string, string> {const out = newMap<string, string>();const add = (key: unknown, row: ImportRow): void => {const k = str(key);if (k && !out.has(k)) out.set(k, `${row.table}/${row.id}`); };for (const row of rows) {const d = row.data;for (const c of TEXT[row.table] ?? []) {if (row.table === "story" && str(d.media_dropped_at)) continue; add(d[c], row); }for (const c of ITEMS[row.table] ?? []) {if (!Array.isArray(d[c])) continue;for (const item of d[c] asRecord<string, unknown>[]) {if (!item || typeof item !== "object") continue; add(item.key, row); add(item.playbackKey, row); } }if (row.table === "meeting" && !str(d.audio_deleted_at)) {if (Array.isArray(d.segments)) for (const s of d.segments asRecord<string, unknown>[]) if (s && typeof s === "object" && s.lost !== true) add(s.path, row);const folder = root ? join(root, databaseId, "meetings", row.id) : null;if (folder && existsSync(folder)) for (const file of walk(folder)) add(relative(root!, file).split("\\").join("/"), row); }if (row.table === "feedback" && str(d.image_sha256)) {const ext = String(d.image_ext ?? "").toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 12); add(`${databaseId}/walkthroughs/${String(d.image_sha256)}${ext ? `.${ext}` : ""}`, row); } }return out;}function walk(dir: string): string[] {const out: string[] = [];for (const entry of readdirSync(dir, { withFileTypes: true })) {const path = join(dir, entry.name);if (entry.isDirectory()) out.push(...walk(path));elseif (entry.isFile() && !entry.name.includes(".part-")) out.push(path); }return out.sort();}/** The content type the Mac's store kept for a key, else the one its extension says. */exportfunction contentType(root: string, key: string): string {const meta = join(root, ".meta", `${key}.json`);if (existsSync(meta)) {try {const said = (JSON.parse(readFileSync(meta, "utf8")) as { contentType?: unknown }).contentType;if (typeof said === "string" && said) return said; } catch {/* a sidecar that does not parse says nothing; the extension speaks */ } }const ext = key.split("/").pop()!.split(".").pop()!.toLowerCase();return TYPES[ext] ?? "application/octet-stream";}exportinterfaceMediaPlan {/** Keys under --media-root, with their size. */ found: { key: string; bytes: number }[];/** Keys rows name that the store does not hold, with a row that names each. */ lost: { key: string; row: string }[];/** Keys of another database (a row brought from elsewhere). */ foreign: { key: string; row: string }[];/** Files too big for one upload through the Worker. */ tooBig: { key: string; bytes: number }[];}exportfunction planMedia(named: Map<string, string>, databaseId: string, root: string, maxBytes: number): MediaPlan {const plan: MediaPlan = { found: [], lost: [], foreign: [], tooBig: [] };for (const [key, row] of named) {if (!key.startsWith(`${databaseId}/`)) { plan.foreign.push({ key, row });continue; }const path = join(root, key);if (!existsSync(path) || !statSync(path).isFile()) { plan.lost.push({ key, row });continue; }const bytes = statSync(path).size;if (bytes > maxBytes) plan.tooBig.push({ key, bytes });else plan.found.push({ key, bytes }); }return plan;}/** A key as a path the Worker reads back with decodeURIComponent. */exportconst keyPath = (key: string): string => key.split("/").map(encodeURIComponent).join("/");