// A POSTS REEL (umtool/docs/report-video.md, "Post items"): a cut's timeline // built -- or extended -- from a channel's posts archive, each post a post item // (umtool-report-to-video/post-item.mjs) played like a slideshow, its // attachments with it. // // umtool posts reel --channel [--channel …] [--since YYYY-MM-DD] [--until …] // [--own] [--with-media] [--replies include|only|exclude] [--order chrono|reverse] // [--limit N] [--after ] [--dry-run] [--json] // umtool new

--from-posts [the same filters] // // THE ARCHIVE is the corpus's `channels//posts/YYYY-MM.jsonl` (the last // line with an id wins: a re-fetch appends) and its captures, // `channels//posts-media//` (capture.json and the post's own // pictures and videos). Several channels are read as one archive -- a // profile's posts and its replies are two channels -- merged in time order // and de-duplicated by post id. The corpus is the one the project reads // (its provenance.channelsDir, else CHANNELS_DIR). // // EACH POST becomes an entry that carries what it says (postEntryFrom): its // words, author, date, link and counts snapshotted from the archive row; a // repost drawn as the post it reposts, "reposted by" its reposter; a reply // with the posts it answers (from the archive, nearest first, up to // POST_PARENTS_FILL) -- else the capture's `shot-thread.png` -- else a // "replying to" line; its attachments COPIED into the project // (`posts-media///`, never a link out of it) and measured (a // video's length and whether it has sound; X serves a GIF as a silent mp4 // from `tweet_video/`). // // RE-RUNNING ADDS ONLY WHAT IS NOT THERE: a post already in the cut -- by its // id, or as the original of a repost already in it, or reposted by one -- is // skipped and counted. Everything new goes in through ONE write // (manifest.mjs insertEntries): one undo point, refused whole by the build's // checks. // // Plain ESM: the CLI runs it under bare node. import { isTrendingLibrary } from "./xTrendingMarker.mjs"; import { execFile } from "node:child_process"; import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; import { POST_MEDIA_MAX, POST_PARENTS_FILL, authorRedaction, cardAuthors, subjectsOf } from "umtool-report-to-video/post-item"; import { ARCHIVE_AVATARS_DIR, ARCHIVE_AVATARS_FILE, AVATARS_DIR, AVATAR_EXT_RE, avatarEntryOf, handleKey } from "umtool-report-to-video/post-avatars"; import { channelsDirFor, channelsLayersFor, readManifest } from "../projects/report.mjs"; import { firstLayerWith } from "umtool-report-to-video/sources"; import { withEditNotes } from "./edit-guard.mjs"; import { addArchiveAvatars, insertEntries, manifestToken } from "./manifest.mjs"; import { deckPlatformOf } from "./postsCli.mjs"; import { applyCaptureContext } from "./postContext.mjs"; const execFileP = promisify(execFile); const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe"; export const REEL_ORDERS = Object.freeze(["chrono", "reverse"]); export const REEL_REPLIES = Object.freeze(["include", "only", "exclude"]); const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; const DAY_RE = /^\d{4}-\d{2}-\d{2}$/; const IMAGE_EXT = /\.(?:jpe?g|png|webp)$/i; const VIDEO_EXT = /\.(?:mp4|m4v|mov|webm)$/i; const GIF_EXT = /\.gif$/i; const str = (v) => (typeof v === "string" ? v : ""); const same = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase(); const timeOf = (row) => { const t = Date.parse(str(row?.createdAt)); if (Number.isFinite(t)) return t; const d = str(row?.uploadDate); return /^\d{8}$/.test(d) ? Date.parse(`${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}T00:00:00Z`) : NaN; }; /** * Every row of a channel's posts archive, by id (the last line with an id * wins), each with `channelSlug` set to `slug`. A channel with no archive is []. */ export async function readPostsArchive(channelsDir, slug) { // An X trending library is private: a reel is never made from one. if (await isTrendingLibrary(channelsDir, slug)) return []; const dir = path.join(channelsDir, slug, "posts"); const names = (await readdir(dir).catch(() => [])).filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort(); const byId = new Map(); for (const name of names) { const text = await readFile(path.join(dir, name), "utf8").catch(() => ""); for (const line of text.split("\n")) { if (!line.trim()) continue; try { const row = JSON.parse(line); if (row && row.id !== undefined) byId.set(String(row.id), { ...row, id: String(row.id), channelSlug: slug }); } catch { // a torn line is not a post } } } return [...byId.values()]; } /** The channel's own account (its config's socialHandle), or null. */ export async function channelHandle(channelsDir, slug) { try { const c = JSON.parse(await readFile(path.join(channelsDir, slug, "config.json"), "utf8")); return typeof c?.socialHandle === "string" && c.socialHandle ? c.socialHandle.replace(/^@/, "") : null; } catch { return null; } } /** * The files a post's capture holds (`posts-media//`): capture.json's * `media` in its order (with each one's source url), else the folder's * pictures and videos by name. Never `shot.png` or the thread shot. And the * record's `context` (the quoted post and the parent its page showed; * postContext.mjs), or null. * * @returns {Promise<{ dir: string, media: Array<{ name: string, url: string | null }>, threadShot: string | null, context: Record | null }>} */ export async function captureOf(channelsDir, slug, postId) { const dir = path.join(channelsDir, slug, "posts-media", postId); const names = await readdir(dir).catch(() => []); let media = []; let context = null; try { const cap = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8")); if (cap?.context && typeof cap.context === "object" && !Array.isArray(cap.context)) context = cap.context; if (Array.isArray(cap?.media)) { media = cap.media.filter((m) => typeof m?.name === "string" && names.includes(m.name)).map((m) => ({ name: m.name, url: typeof m.url === "string" ? m.url : null })); } } catch { // no record: the folder's own files } if (!media.length) { media = names .filter((n) => n !== "shot.png" && n !== "shot-thread.png" && (IMAGE_EXT.test(n) || VIDEO_EXT.test(n) || GIF_EXT.test(n))) .sort() .map((name) => ({ name, url: null })); } return { dir, media: media.slice(0, POST_MEDIA_MAX), threadShot: names.includes("shot-thread.png") ? path.join(dir, "shot-thread.png") : null, context }; } /** * The SELECTION, pure: `rows` (several channels' archives, each row's * `channelSlug` set) filtered and ordered. * * since / until the post's UTC day, inclusive (YYYY-MM-DD) * own the accounts' own posts: written by one of `handles`, not a repost * replies include (default) | only | exclude * withMedia only posts whose capture holds an attachment (`hasMedia(row)`) * order chrono (oldest first, the default) | reverse * limit at most this many * * Merged across channels in time order, de-duplicated by post id (the first * channel named keeps it); a repost whose original is in the selection is * the original's, not a second item. */ export function selectPosts(rows, { since = null, until = null, own = false, replies = "include", withMedia = false, hasMedia = () => true, order = "chrono", limit = null, handles = [] } = {}) { const seen = new Set(); const list = []; for (const r of rows) { if (!r || seen.has(r.id)) continue; seen.add(r.id); list.push(r); } const day = (r) => { const t = timeOf(r); return Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : ""; }; let out = list.filter((r) => { const d = day(r); if (since && (!d || d < since)) return false; if (until && (!d || d > until)) return false; if (own && (r.isRepost === true || !handles.some((h) => same(h, r.author)))) return false; if (replies === "only" && r.isReply !== true) return false; if (replies === "exclude" && r.isReply === true) return false; if (withMedia && !hasMedia(r)) return false; return true; }); const ids = new Set(out.map((r) => r.id)); out = out.filter((r) => !(r.isRepost === true && r.repostOf?.id && ids.has(String(r.repostOf.id)))); out.sort((a, b) => (timeOf(a) - timeOf(b)) * (order === "reverse" ? -1 : 1) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) * (order === "reverse" ? -1 : 1)); return Number.isInteger(limit) && limit > 0 ? out.slice(0, limit) : out; } /** The post ids a cut already plays: each post item's own, its repost's original, and its reposter's. */ export function postsInCut(manifest) { const ids = new Set(); for (const e of manifest?.timeline ?? []) { if (e?.type !== "post") continue; const id = String(e.post ?? "").split("/")[1]; if (id) ids.add(id); if (typeof e.repostId === "string") ids.add(e.repostId); if (typeof e.originalId === "string") ids.add(e.originalId); } return ids; } /** A media file measured: its pixels, and for a video its length and whether it has sound. */ export async function probeMediaFile(file) { try { const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "json", file]); const j = JSON.parse(stdout); const v = (j.streams ?? []).find((s) => s.codec_type === "video") ?? {}; const audio = (j.streams ?? []).some((s) => s.codec_type === "audio"); const seconds = Number(j.format?.duration); return { width: Number.isInteger(v.width) ? v.width : undefined, height: Number.isInteger(v.height) ? v.height : undefined, audio, seconds: Number.isFinite(seconds) ? Math.round(seconds * 1000) / 1000 : undefined }; } catch { return {}; } } /** The kind an attachment plays as: a picture; a GIF (X's `tweet_video/` mp4, or a .gif); else a video. */ export function mediaKindOf(name, url, probe = {}) { if (IMAGE_EXT.test(name)) return "image"; if (GIF_EXT.test(name) || /\/tweet_video\//.test(str(url))) return "gif"; if (probe.audio === false && Number.isFinite(probe.seconds) && probe.seconds <= 15) return "gif"; return "video"; } /** A ref (a parent, the quoted post) from an archive row, or from what a row says of another. */ function refOf(row, fallback = {}) { const handle = str(row?.author).replace(/^@/, "") || str(fallback.author).replace(/^@/, ""); return { ...(row?.id || fallback.id ? { id: String(row?.id ?? fallback.id) } : {}), ...(str(row?.authorName) ? { author: row.authorName } : {}), ...(handle ? { handle } : {}), ...(typeof row?.badge === "string" ? { badge: row.badge } : row?.verifiedType === "Business" ? { badge: "gold" } : row?.verifiedType === "Government" ? { badge: "grey" } : {}), ...(str(row?.createdAt) ? { date: row.createdAt } : {}), ...(typeof row?.text === "string" ? { text: row.text } : {}), ...(str(row?.url) || str(fallback.url) ? { url: str(row?.url) || fallback.url } : {}), }; } const counts = (e) => { if (!e || typeof e !== "object") return undefined; const out = {}; for (const k of ["likes", "reposts", "replies", "quotes"]) if (Number.isInteger(e[k]) && e[k] >= 0) out[k] = e[k]; return Object.keys(out).length ? out : undefined; }; /** * The entry for archive row `row` (pure but for what `io` reads): `index` * finds a post by id across the channels read; `capture(slug, id)` its * capture; `copy(fromFile, toRel)` puts a file into the project and returns * its project-relative path; `probe(file)` measures it. */ export async function postEntryFrom(row, { index, io, subjects = [] }) { const slug = row.channelSlug; // A repost is drawn as the post it reposts, "reposted by" its reposter. const original = row.isRepost === true && row.repostOf?.id ? index.get(String(row.repostOf.id)) ?? null : null; const shown = row.isRepost === true ? original ?? { ...row, id: String(row.repostOf?.id ?? row.id), author: row.repostOf?.author ?? row.author, authorName: undefined, text: str(row.text).replace(/^RT @[A-Za-z0-9_]+:\s*/, ""), url: row.repostOf?.url ?? row.url, engagement: undefined } : row; const shownSlug = shown.channelSlug ?? slug; const entry = { type: "post", id: `p-${row.id}`, post: `${slug}/${row.id}`, platform: deckPlatformOf(row.platform), ...(str(shown.authorName) ? { author: shown.authorName } : {}), ...(str(shown.author) ? { handle: str(shown.author).replace(/^@/, "") } : {}), date: str(shown.createdAt) || new Date(timeOf(row)).toISOString(), text: typeof shown.text === "string" ? shown.text : "", ...(str(shown.url) ? { url: shown.url } : {}), ...(counts(shown.engagement) ? { engagement: counts(shown.engagement) } : {}), ...(typeof shown.badge === "string" ? { badge: shown.badge } : {}), // The accounts the reel is about: every other author it draws is blurred unless verified (post-item.mjs authorRedaction). ...(subjects.length ? { subjects } : {}), }; if (row.isRepost === true) { entry.repostedBy = { ...(str(row.authorName) ? { author: row.authorName } : {}), handle: str(row.author).replace(/^@/, "") }; entry.originalId = String(row.repostOf?.id ?? shown.id); } // A reply: the posts it answers, nearest first, from the archive; else the thread shot; else a line. const replyTo = shown.replyTo ?? null; if (shown.isReply === true && replyTo?.id) { const parents = []; let at = replyTo; while (at?.id && parents.length < POST_PARENTS_FILL) { const p = index.get(String(at.id)); if (!p) break; parents.push(refOf(p)); at = p.isReply === true ? p.replyTo : null; } if (parents.length) entry.parents = parents; else { const cap = await io.capture(shownSlug, String(shown.id)); if (cap.threadShot) entry.parentShot = await io.copy(cap.threadShot, `posts-media/${shownSlug}/${shown.id}/shot-thread.png`); else if (str(replyTo.author)) entry.replyingTo = str(replyTo.author).replace(/^@/, ""); } } if (shown.quoted && typeof shown.quoted === "object") { const q = index.get(String(shown.quoted.id ?? "")) ?? null; entry.quoted = refOf(q ?? { ...shown.quoted, author: shown.quoted.author ?? shown.quoted.handle, authorName: shown.quoted.authorName ?? shown.quoted.name }, shown.quoted); } // What the archive lacks of its context, from the capture's (postContext.mjs): the shown post's, else the row's. applyCaptureContext(entry, (await io.capture(shownSlug, String(shown.id))).context ?? (shown !== row ? (await io.capture(slug, row.id)).context : null)); // Its attachments: the shown post's capture (a repost's original), else the row's own. let cap = await io.capture(shownSlug, String(shown.id)); let capSlug = shownSlug; let capId = String(shown.id); if (!cap.media.length && shown !== row) { cap = await io.capture(slug, row.id); capSlug = slug; capId = row.id; } const media = []; for (const m of cap.media) { const from = path.join(cap.dir, m.name); const src = await io.copy(from, `posts-media/${capSlug}/${capId}/${m.name}`); const probe = await io.probe(from); const kind = mediaKindOf(m.name, m.url, probe); media.push({ src, 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: it is left out, and said. const kept = media.filter((m) => m.kind === "image" || Number.isFinite(m.seconds)); if (kept.length) entry.media = kept; return { entry, dropped: media.length - kept.length }; } /** Copy a file into the project (never through a link out of it); the same bytes already there are left. */ async function copyInto(projectDir, from, rel) { const to = path.join(projectDir, ...rel.split("/")); const [a, b] = await Promise.all([stat(from).catch(() => null), stat(to).catch(() => null)]); if (b && a && a.size === b.size) return rel; await mkdir(path.dirname(to), { recursive: true }); const real = await realpath(path.dirname(to)); const proj = await 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); return rel; } /** * The archive's pictures (each channel's posts-media/_avatars/avatars.json, * the editor's capture-posts store: `{ : { file, url, capturedAt } }`), * by handle key -- the handle without `@`, LOWERCASED: the store keys a * picture by the handle as X printed it ("TheQuartering"), a card or a * mention may spell it otherwise ("@thequartering") -- the newest when two * stores hold one. * * `layers` is one channels tree or the trees a project reads, in order * (projects/report.mjs channelsLayersFor: its own `.shadow-channels/` or * `provenance.channelsDir`, then the corpus behind it). EVERY tree's store of * EVERY channel is read -- not only the project's own tree, nor the first * tree that holds the channel's posts: a shadow is made by copying a * channel's `posts/` (and a capture or two), never its `_avatars/`, so the * pictures are in the corpus while the posts are in the shadow * (quartering-diet rev 9, 11 Nov: the shadow held the three channels' posts * and none of their stores, `posts avatars` read the shadow alone and copied * 0 of the two pictures the corpus had -- "no picture yet for * @thequartering, @madamsavvy"). A channel with no store in one tree -- or in * any -- is noted in `searched` and skipped, never the end of the search. * * @param {string | string[]} layers * @param {string[]} channels * @returns {Promise<{ store: Map, * searched: Array<{ channel: string, tree: string, dir: string, state: "read" | "none" | "unreadable", pictures: number }> }>} */ export async function archiveAvatarStores(layers, channels) { const trees = [...new Set((Array.isArray(layers) ? layers : [layers]).filter((d) => typeof d === "string" && d).map((d) => path.resolve(d)))]; const store = new Map(); const searched = []; for (const slug of channels) { for (const tree of trees) { const dir = path.join(tree, slug, "posts-media", ARCHIVE_AVATARS_DIR); let doc; try { doc = JSON.parse(await readFile(path.join(dir, ARCHIVE_AVATARS_FILE), "utf8")); } catch (e) { searched.push({ channel: slug, tree, dir, state: e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "none" : "unreadable", pictures: 0 }); continue; } if (!doc || typeof doc !== "object" || Array.isArray(doc)) { searched.push({ channel: slug, tree, dir, state: "unreadable", pictures: 0 }); continue; } let pictures = 0; for (const [h, a] of Object.entries(doc)) { if (!a || typeof a !== "object" || typeof a.file !== "string" || a.file.includes("/") || a.file.includes("\\") || !AVATAR_EXT_RE.test(a.file)) continue; const file = path.join(dir, a.file); if (!(await stat(file).catch(() => null))?.isFile()) continue; pictures += 1; const k = handleKey(h); const had = store.get(k); const at = typeof a.capturedAt === "string" ? a.capturedAt : null; if (had && (had.capturedAt ?? "") >= (at ?? "")) continue; store.set(k, { handle: h.replace(/^@/, ""), file, url: typeof a.url === "string" ? a.url : null, capturedAt: at }); } searched.push({ channel: slug, tree, dir, state: "read", pictures }); } } return { store, searched }; } /** The archive's pictures alone (archiveAvatarStores' `store`); `layers` one channels tree or several. */ export async function archiveAvatars(layers, channels) { return (await archiveAvatarStores(layers, channels)).store; } /** * What archiveAvatarStores searched, in words, one line per channel: each * store it read (and how many pictures it holds), and each tree that had * none -- so "no picture" says WHERE it looked. PURE. * * @param {Array<{ channel: string, tree: string, dir: string, state: string, pictures: number }>} searched * @returns {string[]} */ export function avatarStoresSaid(searched) { const by = new Map(); for (const s of searched ?? []) { if (!by.has(s.channel)) by.set(s.channel, []); by.get(s.channel).push(s); } const lines = []; for (const [channel, rows] of by) { const said = rows.filter((r) => r.state === "read").map((r) => `${r.pictures} picture(s) in ${r.dir}`); const none = rows.filter((r) => r.state !== "read"); if (none.length) said.push(`no ${ARCHIVE_AVATARS_DIR}/ in ${none.map((r) => `${r.tree}${r.state === "unreadable" ? ` (${ARCHIVE_AVATARS_FILE} unreadable)` : ""}`).join(" or ")}`); lines.push(`${channel}: ${said.join("; ")}`); } return lines; } /** Every handle an entry's card draws UNBLURRED (a redacted author never gets a picture). */ export function shownHandles(e) { const out = []; if (e?.type === "post") { const subj = subjectsOf(e); const o = { subjects: subj, redact: typeof e.redact === "boolean" ? e.redact : undefined }; if (e.handle && !authorRedaction({ handle: e.handle, badge: e.badge }, o).redact) out.push(e.handle); for (const a of cardAuthors(e)) if (!a.redact && a.handle) out.push(a.handle); } return out; } /** * The pictures to copy in for `entries` (and the cut's own, for a re-run): * every handle drawn unblurred that the archive has a picture of and the * project does not. `copy(fromFile, toRel)` puts one into the project. * * @returns {Promise>} */ export async function avatarsToCopy(manifest, entries, store, copy) { const out = {}; const handles = new Set(); for (const e of [...(manifest?.timeline ?? []), ...entries]) for (const h of shownHandles(e)) handles.add(handleKey(h)); for (const k of handles) { const a = store.get(k); if (!a || avatarEntryOf(manifest, k) || out[a.handle]) continue; const ext = path.extname(a.file).toLowerCase(); const src = await copy(a.file, `${AVATARS_DIR}/${a.handle}${ext}`); out[a.handle] = { src, ...(a.url ? { url: a.url } : {}), ...(a.capturedAt ? { capturedAt: a.capturedAt } : {}) }; } return out; } /** Parse YYYY-MM-DD (or null); throws in words. */ function dayArg(v, what) { if (v === null || v === undefined || v === "") return null; if (!DAY_RE.test(String(v)) || Number.isNaN(Date.parse(String(v)))) throw new Error(`${what} takes a day, YYYY-MM-DD (got ${v})`); return String(v); } /** * BUILD OR EXTEND THE CUT from the archive: read `channels`, select, skip what * the cut already plays, make each entry (its media copied in), and put them * all in in ONE write after `after` (null: the end). `dryRun`: nothing copied * or written -- the list of what would go in. * * @param {{ id: string, dir: string }} project * @param {{ channels: string[], since?: string|null, until?: string|null, own?: boolean, withMedia?: boolean, * replies?: string, order?: string, limit?: number|null, after?: string|null, dryRun?: boolean, channelsDir?: string|null }} o */ export async function postsReel(project, o) { const channels = [...new Set((o.channels ?? []).map((c) => String(c).trim()).filter(Boolean))]; if (!channels.length) throw new Error("name the posts channel: --channel (more than one: they are merged)"); for (const c of channels) if (!SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`); const replies = o.replies ?? "include"; if (!REEL_REPLIES.includes(replies)) throw new Error(`--replies takes ${REEL_REPLIES.join(", ")}`); const order = o.order ?? "chrono"; if (!REEL_ORDERS.includes(order)) throw new Error(`--order takes ${REEL_ORDERS.join(" or ")}`); const since = dayArg(o.since, "--since"); const until = dayArg(o.until, "--until"); if (since && until && since > until) throw new Error(`--since ${since} is after --until ${until}`); if (o.limit !== null && o.limit !== undefined && !(Number.isInteger(o.limit) && o.limit > 0)) throw new Error("--limit takes a whole number of posts"); const manifest = await readManifest(project.dir); if (!manifest) throw new Error(`${project.id} has no manifest`); const layers = o.channelsDir ? [o.channelsDir] : channelsLayersFor(project.dir, manifest); const channelsDir = layers[0] ?? channelsDirFor(project.dir, manifest); const rows = []; const handles = []; // Each channel from the first tree that holds its posts: the project's, else the corpus behind it. const rootOf = new Map(); const root = async (slug) => { if (!rootOf.has(slug)) rootOf.set(slug, layers.length > 1 ? await firstLayerWith(layers, [slug, "posts"], { kind: "posts" }) : channelsDir); return rootOf.get(slug); }; for (const c of channels) { const got = await readPostsArchive(await root(c), c); if (!got.length) throw new Error(`${c} has no posts archive under ${layers.join(" or ")} (channels/${c}/posts/*.jsonl) — is it a social channel?`); rows.push(...got); const h = await channelHandle(await root(c), c); if (h) handles.push(h); } // Every channel's rows by id, for the parents, the quoted post and a repost's original. const index = new Map(); for (const r of rows) if (!index.has(r.id)) index.set(r.id, r); const captures = new Map(); const capture = async (slug, id) => { const k = `${slug}/${id}`; if (!captures.has(k)) captures.set(k, await captureOf(await root(slug), slug, id)); return captures.get(k); }; // "With media": the post's capture (or a repost's original's) holds an attachment. const mediaIds = new Set(); if (o.withMedia) { for (const r of rows) { const shownId = r.isRepost === true && r.repostOf?.id ? String(r.repostOf.id) : r.id; const shownSlug = index.get(shownId)?.channelSlug ?? r.channelSlug; if ((await capture(shownSlug, shownId)).media.length || (await capture(r.channelSlug, r.id)).media.length) mediaIds.add(r.id); } } const picked = selectPosts(rows, { since, until, own: o.own === true, replies, withMedia: o.withMedia === true, hasMedia: (r) => mediaIds.has(r.id), order, limit: null, handles }); const inCut = postsInCut(manifest); const fresh = []; let already = 0; for (const r of picked) { const orig = r.isRepost === true ? String(r.repostOf?.id ?? "") : ""; if (inCut.has(r.id) || (orig && inCut.has(orig))) { already += 1; continue; } fresh.push(r); } const take = Number.isInteger(o.limit) ? fresh.slice(0, o.limit) : fresh; const io = { capture, copy: o.dryRun ? async (_from, rel) => rel : (from, rel) => copyInto(project.dir, from, rel), probe: probeMediaFile, }; const entries = []; let dropped = 0; for (const r of take) { const made = await postEntryFrom(r, { index, io, subjects: [...new Set(handles)] }); entries.push(made.entry); dropped += made.dropped; } // The authors' pictures: the archive's, for every author the cards draw unblurred that the cut has none of -- // from every tree's store (the project's, the corpus behind it), not only the tree its posts were read from. const store = await archiveAvatars(layers, channels); const avatars = store.size ? await avatarsToCopy(manifest, entries, store, o.dryRun ? async (_f, rel) => rel : (from, rel) => copyInto(project.dir, from, rel)) : {}; const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped, avatars: Object.keys(avatars) }; if (o.dryRun) return { ...summary, entries, dryRun: true, result: null, editNotes: null }; if (!entries.length) { // Nothing new to add -- but the cut's authors may have pictures now. if (!Object.keys(avatars).length) return { ...summary, entries, dryRun: false, result: null, editNotes: null }; const { result, editNotes } = await withEditNotes(project, async () => addArchiveAvatars(project.dir, avatars, { token: await manifestToken(project.dir) })); return { ...summary, entries, dryRun: false, result, editNotes }; } const { result, editNotes } = await withEditNotes(project, async () => insertEntries(project.dir, o.after ?? null, entries, { token: await manifestToken(project.dir), op: "posts-reel", avatars }), ); return { ...summary, entries: result.entries, dryRun: false, result, editNotes }; } /** * ONE POST ITEM from the archive (`umtool timeline

insert … post:/`): * the entry as `posts reel` makes it -- its media copied into the project -- * not yet written. The channel's archive is read whole (its parents and a * repost's original come from it); the subject is the channel's own account. * * @param {{ id: string, dir: string }} project * @param {Record} manifest * @param {string} slug * @param {string} postId * @param {{ id?: string | null, channelsDir?: string | null }} [o] */ export async function postItemFromArchive(project, manifest, slug, postId, { id = null, channelsDir = null } = {}) { if (!SLUG_RE.test(slug)) throw new Error(`"${slug}" is not a channel slug`); // The project's channels tree first, the corpus behind it for a channel it lacks (sources.mjs channelsLayersFor). const dir = channelsDir ?? await firstLayerWith(channelsLayersFor(project.dir, manifest), [slug, "posts"], { kind: "posts" }); const rows = await readPostsArchive(dir, slug); const index = new Map(rows.map((r) => [r.id, r])); const row = index.get(String(postId)); if (!row) throw new Error(`${slug} has no post ${postId} in its archive (${rows.length} read under ${path.join(dir, slug, "posts")})`); const handle = await channelHandle(dir, slug); const captures = new Map(); const io = { capture: async (s, pid) => { const k = `${s}/${pid}`; if (!captures.has(k)) captures.set(k, await captureOf(dir, s, pid)); return captures.get(k); }, copy: (from, rel) => copyInto(project.dir, from, rel), probe: probeMediaFile, }; const { entry } = await postEntryFrom(row, { index, io, subjects: handle ? [handle] : [] }); if (id) entry.id = id; return entry; } /** * The archive's pictures of the authors `entries` draw unblurred that the * cut has none of, copied into the project (`{ : { src, url?, * capturedAt? } }` for insertEntries / addArchiveAvatars). * * @param {{ id: string, dir: string }} project * @param {Record} manifest * @param {string[]} channels * @param {Array>} entries * @param {{ channelsDir?: string | null }} [o] */ export async function archiveAvatarsFor(project, manifest, channels, entries, { channelsDir = null } = {}) { // Every tree the project reads (its own, the corpus behind it): a shadow copies posts, not the stores. const store = await archiveAvatars(channelsDir ?? channelsLayersFor(project.dir, manifest), channels); if (!store.size) return {}; return avatarsToCopy(manifest, entries, store, (from, rel) => copyInto(project.dir, from, rel)); } /** The archive channels a cut's post items came from (`post: "/"`). */ export function postChannelsOf(manifest) { return [...new Set((manifest?.timeline ?? []).filter((e) => e?.type === "post" && typeof e.post === "string").map((e) => e.post.split("/")[0]).filter(Boolean))]; }