// `umtool posts repeats` / `umtool posts combo` (report-to-video/post-combo.mjs): // the COMBO COUNTER from a terminal -- which attachments the cut plays more // than once, and the badge's knobs. // // umtool posts repeats [--match id|file|audio] [--json] // umtool posts combo [k=v …] [--json] the cut's (render.posts.combo) // umtool posts combo off|on|auto|k=v … [--json] one item's (`combo`) // umtool posts scenes [on|off] [--json] the media scenes (post-media-scene.mjs) // // `repeats` lists each repeated attachment with its posts in the cut's order // (their dates, the tier that matched) and the badge each draws; a post item // whose CAPTURE holds the same file but whose entry carries no attachment (it // was captured after it went in) is listed too, marked, with how to bring it // in -- it draws no badge and does not count until it plays the attachment. // // Plain ESM: the CLI runs it under bare node. import { COMBO_DEFAULTS, COMBO_ITEM_KEYS, comboKnobs, repeatGroups } from "umtool-report-to-video/post-combo"; import { captureOnlyMedia, projectCombos } from "umtool-report-to-video/post-combo-prints"; import { channelsDirFor, channelsLayersFor, hasShadowChannels, readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { copyFile, mkdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { attachPostMedia, manifestToken, updatePostCombo, updatePostComboRender, updatePostSceneRender } from "./manifest.mjs"; import { mediaScenes, sceneKnobs, sceneLines } from "umtool-report-to-video/post-media-scene"; import { mediaKindOf, probeMediaFile } from "./postReel.mjs"; export class ComboError extends Error {} export const REPEATS_USAGE = [ "usage: umtool posts repeats [--match id|file|audio] [--json]", " every attachment the cut's post items play more than once, its posts in the cut's order (dates, the tier", " that matched: the X media id, the file's sha256, or -- --match audio -- the sound's fingerprint), and the", " combo badge each draws (×2 from the second use; render.posts.combo). A post whose capture holds the same", " file but whose entry has no attachment yet is listed too, marked: it counts once it plays it.", " umtool posts combo [on=on|off] [label=COMBO] [position=top-right|top-left|bottom-right|bottom-left|center]", " [color=#rrggbb] [scale=0.4-2.5] [sfx=off|hit|coin] [minCount=2-20] [match=id|file|audio] [--json]", " the cut's badge (render.posts.combo; k= back to the default); no knobs prints them.", " umtool posts combo off|on|auto [label=…] [position=…] [color=…] [scale=…] [sfx=…] [--json]", " one post item's: off draws no badge on it (it still counts), on/auto the cut's again; its own label, …", " umtool posts scenes [on|off] [--json]", " the MEDIA SCENES: neighbouring post items that carry the same attachment (matched as above), each scene's", " items in order and its anchor (the first to carry it: its crop and censor are the scene's). The attachment", " stays put through a scene; each message stacks in beside it. on|off: the cut's (render.posts.scene.on,", " default on). One item: umtool posts set-item scene=off|join|auto.", " umtool posts attach [ … | --all] [--dry-run] [--json]", " a post item with no attachment whose capture holds one (captured after it went in): its media copied in and", " set, as posts reel would have made it -- nothing else of the entry changes. One write (one undo point).", " The capture is looked for in the project's channels tree, then the archive's (read only: the files are", " copied into the project); --dry-run prints the tree each file would come from.", ].join("\n"); const OFF = new Set(["off", "no", "false", "0"]); const ON = new Set(["on", "yes", "true", "1"]); /** `k=v` words into a combo patch (null: the default / the cut's). */ export function comboPatchOf(pairs, { item = false } = {}) { const keys = item ? COMBO_ITEM_KEYS : Object.keys(COMBO_DEFAULTS); /** @type {Record} */ const out = {}; for (const pair of pairs) { const eq = pair.indexOf("="); if (eq < 1) throw new ComboError(`${pair}: a knob is key=value`); const k = pair.slice(0, eq); const raw = pair.slice(eq + 1); if (!keys.includes(k)) throw new ComboError(`${k}= is not a ${item ? "post item's " : ""}combo knob (${keys.join(", ")})`); if (raw === "") out[k] = null; else if (k === "on") { if (!ON.has(raw.toLowerCase()) && !OFF.has(raw.toLowerCase())) throw new ComboError("on= takes on or off"); out.on = ON.has(raw.toLowerCase()); } else if (k === "scale" || k === "minCount") { const v = Number(raw); if (!Number.isFinite(v)) throw new ComboError(`${k}= takes a number`); out[k] = v; } else out[k] = raw; } return out; } async function projectOf(projectArg, root) { const { resolveProject } = await import("../projects/core.mjs"); const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new ComboError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new ComboError(`no project matches "${projectArg}"`); return r.project; } /** * THE REPEATS VIEW: the cut's groups with the capture-only posts folded in. * * @param {{ id: string, dir: string }} project * @param {{ match?: string | null, cacheDir?: string | null, channelsDir?: string | null }} [o] */ export async function repeatsView(project, { match = null, cacheDir = undefined, channelsDir = null } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new ComboError(`${project.id} has no manifest`); const corpus = channelsDir ?? channelsDirFor(project.dir, manifest); const opts = { channelsDir: corpus, ...(match ? { match } : {}), ...(cacheDir !== undefined ? { cacheDir } : {}) }; const cut = await projectCombos(project.dir, manifest, opts); // The posts whose capture has a file their entry does not carry: in the cut's order, as if they played it. const captured = await captureOnlyMedia(manifest, { channelsDirs: await captureTrees(project, manifest, channelsDir) }); const tl = (manifest.timeline ?? []).map((e) => (captured[e?.id] ? { ...e, media: captured[e.id].map((m) => ({ src: `@capture/${m.slug}/${m.name}`, kind: "capture" })) } : e)); const prints = (id, i) => (captured[id] ? { mediaId: captured[id][i]?.mediaId ?? null, sha256: captured[id][i]?.sha256 ?? null } : cut.prints[`${id}:${i}`]); const all = repeatGroups(tl, prints, { match: cut.match }); const byId = new Map((manifest.timeline ?? []).map((e) => [e?.id, e])); const ids = (manifest.timeline ?? []).map((e) => e?.id); const afterOf = (id) => (ids.indexOf(id) > 0 ? ids[ids.indexOf(id) - 1] : "-"); const groups = all.map((g) => { const first = g.members.find((m) => !captured[m.id]) ?? g.members[0]; const att = byId.get(first.id)?.media?.[first.i]; return { key: g.key, tiers: g.tiers, kind: att?.kind ?? "?", src: att?.src ?? first.src, members: g.members.map((m) => { const c = cut.combos[m.id]; const cap = captured[m.id]?.[m.i]; return { id: m.id, n: m.n, post: m.post, date: m.date, tier: m.tier, attached: !cap, ...(cap ? { capture: `${cap.slug}/posts-media/${String(m.post ?? "").split("/")[1] ?? ""}/${cap.name}`, captureSlug: cap.slug, after: afterOf(m.id) } : {}), badge: c && c.media === m.i ? c.count : null, show: !!(c && c.media === m.i && c.show), }; }), }; }).filter((g) => g.members.some((m) => m.attached)); groups.forEach((g, k) => (g.key = `g${k + 1}`)); return { project: project.id, match: cut.match, knobs: comboKnobs(manifest.render), groups, combos: cut.combos }; } /** * THE MEDIA SCENES VIEW (post-media-scene.mjs): the cut's scenes over the * combo counter's groups -- `{ project, on, scenes: [{ key, ids, anchor, * members }], lines }`. Off for the cut: none, `on` false. * * @param {{ id: string, dir: string }} project */ export async function scenesView(project, { channelsDir = null } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new ComboError(`${project.id} has no manifest`); const cut = await projectCombos(project.dir, manifest, { channelsDir: channelsDir ?? channelsDirFor(project.dir, manifest) }); const { scenes } = mediaScenes(manifest.timeline, cut.groups, manifest.render); return { project: project.id, on: sceneKnobs(manifest.render).on, scenes: scenes.map((s) => ({ key: s.key, ids: s.ids, anchor: s.anchor.id, group: s.group, members: s.members.map((m) => ({ id: m.id, media: m.media, joins: m.media === null })) })), lines: sceneLines(scenes, manifest.timeline), }; } const TIER_WORDS = { "media-id": "X media id", sha256: "same file", audio: "same sound" }; const MATCH_WORDS = { id: "the X media id", file: "the X media id, then the file's bytes", audio: "the X media id, the bytes, then the sound" }; /** * Is this ONE path segment -- a capture's file name, a post id, a channel slug as a capture or a manifest gives them? * Not empty, not `.` or `..`, no separator (either slash) and no NUL: a name is joined into a path in a channels tree * and in the project, and `../../x` would read, and write, outside both. */ export const isPathSegment = (v) => typeof v === "string" && v !== "" && v !== "." && v !== ".." && !/[/\\\0]/.test(v); /** Copy a capture's file into the project (never through a link out of it); the same size already there is left. */ async function copyIn(projectDir, from, rel) { // Before anything is made: every segment a plain name (attachFromCaptures checks them too -- this is the writer's own). if (!rel.split("/").every(isPathSegment)) throw new ComboError(`${JSON.stringify(rel)} is not a path inside the project — not copying`); const to = path.join(projectDir, ...rel.split("/")); const [a, b] = await Promise.all([stat(from).catch(() => null), stat(to).catch(() => null)]); if (a && b && a.size === b.size) return; await mkdir(path.dirname(to), { recursive: true }); const [real, proj] = await Promise.all([realpath(path.dirname(to)), realpath(projectDir)]); if (real !== proj && !real.startsWith(proj + path.sep)) throw new Error(`${path.dirname(rel)} leads out of the project (a link) — not copying through it`); await copyFile(from, to); } /** * THE CHANNELS TREES A CAPTURE IS LOOKED FOR IN (12 Nov: a project with a `.shadow-channels` tree saw only that, and * the captures in the real archive's `channels//posts-media//` were invisible): the project's own tree * first, then the archive behind it -- as the other readers resolve them (projects/report.mjs channelsLayersFor; * `provenance.channelsFallback: false` or CHANNELS_FALLBACK=0 keeps it to the project's). READ ONLY toward both: * attach copies into the project. * @returns {Promise} */ async function captureTrees(project, manifest, channelsDir = null, channelsDirs = null) { if (Array.isArray(channelsDirs) && channelsDirs.length) return channelsDirs; if (channelsDir) return [channelsDir]; return channelsLayersFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) }); } /** A tree in words: the first is the project's own, any after it the archive's. */ const treeKindOf = (trees, tree) => (trees.indexOf(tree) <= 0 ? "project" : "archive"); /** * ATTACH WHAT THE CAPTURES HOLD (`umtool posts attach`): each post item with no * attachment whose capture has one (captured after it went in) gets its media * as `posts reel` would have made it -- the files copied into the project's * posts-media/, measured -- and nothing else of the entry changes (its * paraphrases, narration, knobs kept). One write. `ids` narrows it. * A capture is looked for in the project's channels tree, then the archive's (captureTrees); each planned item * says which it came from (`tree`, `treeKind`: project | archive), and `--dry-run` prints it per file. * * @param {{ id: string, dir: string }} project * @param {{ ids?: string[] | null, dryRun?: boolean, channelsDir?: string | null, channelsDirs?: string[] | null }} [o] * `channelsDirs`: the trees to look in, in order (default: the project's, then the archive's) */ export async function attachFromCaptures(project, { ids = null, dryRun = false, channelsDir = null, channelsDirs = null } = {}) { const manifest = await readManifest(project.dir); if (!manifest) throw new ComboError(`${project.id} has no manifest`); const trees = await captureTrees(project, manifest, channelsDir, channelsDirs); const captured = await captureOnlyMedia(manifest, { channelsDirs: trees }); const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; const want = ids ? ids.map((r) => tl.find((e) => e?.type === "post" && (e.id === r || String(e.post ?? "").split("/")[1] === r))?.id ?? r) : null; if (want) for (const id of want) if (!tl.some((e) => e?.id === id && e.type === "post")) throw new ComboError(`no post item ${id} in ${project.id}`); const patches = {}; const plan = []; for (const [id, list] of Object.entries(captured)) { if (want && !want.includes(id)) continue; const postId = String(tl.find((e) => e?.id === id)?.post ?? "").split("/")[1]; const media = []; for (const m of list) { // A capture's names are data: refused before any file is looked at, in whichever tree it was found. for (const [what, v] of [["file name", m.name], ["post id", postId], ["channel", m.slug]]) { if (!isPathSegment(v)) throw new ComboError(`${id}: its capture's ${what} ${JSON.stringify(v ?? null)} is not a plain name (a path separator, "." or "..", or empty) — nothing attached`); } const from = path.join(m.tree, m.slug, "posts-media", postId, m.name); if (!(await stat(from).catch(() => null))) continue; const rel = `posts-media/${m.slug}/${postId}/${m.name}`; const probe = await probeMediaFile(from); const kind = mediaKindOf(m.name, m.url, probe); const item = { src: rel, kind, ...(probe.width ? { width: probe.width } : {}), ...(probe.height ? { height: probe.height } : {}), ...(kind !== "image" && probe.seconds ? { seconds: probe.seconds } : {}), ...(kind === "video" ? { audio: probe.audio === true } : {}), }; // A timed attachment that could not be measured cannot be planned. if (kind !== "image" && !Number.isFinite(item.seconds)) continue; media.push({ item, from }); } if (!media.length) continue; patches[id] = media.map((x) => x.item); plan.push({ id, tree: list[0].tree, treeKind: treeKindOf(trees, list[0].tree), media: media.map((x) => ({ src: x.item.src, kind: x.item.kind, from: x.from })) }); } if (dryRun || !plan.length) return { dryRun, attached: plan, result: null, editNotes: null }; for (const p of plan) for (const m of p.media) await copyIn(project.dir, m.from, m.src); const { result, editNotes } = await withEditNotes(project, async () => attachPostMedia(project.dir, patches, { token: await manifestToken(project.dir) })); return { dryRun, attached: plan.filter((p) => result.ids.includes(p.id)), result, editNotes }; } /** What `posts attach` prints: each item's media, and the channels tree each file is read from (a dry run: per file). */ export function attachLines(r, projectId) { const out = [`${r.dryRun ? "would attach" : "attached"} the capture's media to ${r.attached.length} post item(s) in ${projectId}`]; for (const a of r.attached) { const whose = a.treeKind === "archive" ? "the archive's" : "the project's"; out.push(` ${a.id} ${a.media.map((m) => `${m.kind} ${m.src}`).join(", ")}`); if (r.dryRun) for (const m of a.media) out.push(` from ${whose} channels tree: ${m.from}`); else out.push(` from ${whose} channels tree (${a.tree})`); } if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out.push(` undo point: ${r.result.snapshot.rel} (umtool timeline ${projectId} undo)`); return out; } /** The repeats view as lines. */ export function repeatsLines(v) { const out = []; const shown = v.groups.filter((g) => g.members.filter((m) => m.attached).length >= 2); out.push(`${shown.length} attachment(s) played more than once in ${v.project} (matched by ${MATCH_WORDS[v.match] ?? v.match}; the badge ${v.knobs.on === false ? "OFF for the cut" : `from ×${v.knobs.minCount}`})`); for (const g of v.groups) { const uses = g.members.filter((m) => m.attached).length; out.push(` ${g.key} ${uses}× ${g.kind} ${g.src}${g.members.length > uses ? ` (+${g.members.length - uses} not attached yet)` : ""}`); for (const m of g.members) { const day = typeof m.date === "string" ? m.date.slice(0, 10) : "?"; const badge = !m.attached ? " - " : m.badge && m.badge >= 2 ? (m.show ? `×${m.badge}`.padEnd(5) : `(×${m.badge})`.padEnd(5)) : " 1 "; const how = m.tier ? TIER_WORDS[m.tier] ?? m.tier : "first"; out.push(` ${badge} ${m.id} ${day} ${m.post ?? ""} [${how}]${m.attached ? "" : ` NOT ATTACHED: its capture ${m.capture} is the same file`}`); } } const missing = v.groups.flatMap((g) => g.members.filter((m) => !m.attached)); if (missing.length) { out.push(` ${missing.length} post(s) above carry no attachment in the cut (captured after they went in); each counts once it plays it:`); out.push(` umtool posts attach ${v.project} ${missing.map((m) => m.id).join(" ")} (their capture's media, nothing else of the entry changed)`); } return out; } /** * @param {"repeats" | "combo"} verb * @param {string[]} words the words after the verb (project first) * @param {Map} flags * @param {{ root: string, json: boolean, out: (s: string) => void, err: (s: string) => void }} o */ export async function comboCommand(verb, words, flags, o) { try { return await comboRun(verb, words, flags, o); } catch (e) { if (!(e instanceof ComboError)) throw e; o.err(`umtool posts ${verb}: ${e.message}`); return 2; } } async function comboRun(verb, words, flags, { root, json, out, err }) { const [projectArg, ...rest] = words; if (!projectArg || flags.has("--help")) { err(REPEATS_USAGE); return 2; } const project = await projectOf(projectArg, root); if (verb === "attach") { const items = rest.filter((w) => !w.startsWith("--")); if (!items.length && !flags.has("--all")) throw new ComboError("name the items to attach, or --all"); const r = await attachFromCaptures(project, { ids: items.length ? items : null, dryRun: flags.has("--dry-run") }); if (json) out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2)); else { for (const l of attachLines(r, project.id)) out(l); } return 0; } if (verb === "scenes") { const word = rest.find((w) => !w.startsWith("--")); if (word !== undefined) { const w = word.toLowerCase(); if (!ON.has(w) && !OFF.has(w) && w !== "auto") throw new ComboError(`posts scenes takes on, off or auto (the default), not ${word}`); const { result, editNotes } = await withEditNotes(project, async () => updatePostSceneRender(project.dir, { on: w === "auto" ? null : ON.has(w) }, { token: await manifestToken(project.dir) })); out(json ? JSON.stringify({ ok: true, scene: result.scene, token: result.token, editNotes }, null, 2) : `the cut's media scenes: ${result.scene?.on === false ? "off" : "on"}`); return 0; } const v = await scenesView(project); if (json) out(JSON.stringify({ ok: true, ...v }, null, 2)); else { out(`${v.scenes.length} media scene(s) in ${project.id}${v.on ? "" : " (OFF for the cut: render.posts.scene.on false)"}`); for (const l of v.lines) out(` ${l}`); } return 0; } if (verb === "repeats") { const m = flags.get("--match"); if (m !== undefined && !["id", "file", "audio"].includes(String(m))) throw new ComboError("--match takes id, file or audio"); const v = await repeatsView(project, { match: m === undefined ? null : String(m) }); out(json ? JSON.stringify({ ok: true, ...v }, null, 2) : repeatsLines(v).join("\n")); return 0; } // combo: the cut's (no item), or one item's. const manifest = await readManifest(project.dir); if (!manifest) throw new ComboError(`${project.id} has no manifest`); const isPair = (w) => w.includes("="); if (!rest.length || isPair(rest[0])) { if (!rest.length) { const k = comboKnobs(manifest.render); out(json ? JSON.stringify({ ok: true, combo: manifest.render?.posts?.combo ?? null, knobs: k }, null, 2) : `the cut's combo badge: ${Object.entries(k).map(([a, b]) => `${a}=${b}`).join(" ")}`); return 0; } const patch = comboPatchOf(rest); const { result, editNotes } = await withEditNotes(project, async () => updatePostComboRender(project.dir, patch, { token: await manifestToken(project.dir) })); out(json ? JSON.stringify({ ok: true, combo: result.combo, token: result.token, editNotes }, null, 2) : `the cut's combo badge: ${JSON.stringify(result.combo ?? "the defaults")}`); return 0; } const [ref, ...pairs] = rest; const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref)); if (!hit) throw new ComboError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); let value; const word = pairs.length === 1 && !isPair(pairs[0]) ? pairs[0].toLowerCase() : null; if (!pairs.length) { out(json ? JSON.stringify({ ok: true, id: hit.id, combo: hit.combo ?? null, knobs: comboKnobs(manifest.render, hit) }, null, 2) : `${hit.id}: ${hit.combo === false ? "no badge (off)" : hit.combo ? JSON.stringify(hit.combo) : "the cut's badge"}`); return 0; } if (word !== null) { if (OFF.has(word)) value = false; else if (ON.has(word) || word === "auto") value = hit.combo === false || !hit.combo ? null : { on: null }; else throw new ComboError(`${pairs[0]}: off, on, auto or key=value`); } else { if (pairs.some((p) => !isPair(p))) throw new ComboError("off / on go alone; knobs are key=value"); value = comboPatchOf(pairs, { item: true }); } const { result, editNotes } = await withEditNotes(project, async () => updatePostCombo(project.dir, hit.id, value, { token: await manifestToken(project.dir) })); out(json ? JSON.stringify({ ok: true, id: hit.id, combo: result.combo, token: result.token, editNotes }, null, 2) : `${hit.id}: ${result.combo === false ? "no badge on this item (it still counts)" : result.combo ? `its own: ${JSON.stringify(result.combo)}` : "the cut's badge"}`); return 0; }