Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 418f9361809cd2e532c40f91974fdfccc4516fb2
parent f127a94fc1f29734a6966bdb0e0dcf77c7fd2fa2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 01:34:45 -0500

x-trending: a library's media comes from X's media CDN and is kept once

The parser reads where the CDN serves each post's files from the saved capture (X's two media hosts only). The capture job's media half for a library fetches them with no login, one file after another 1 to 2 s apart, under X's cooldown, a per-file cap (config.xTrending.maxVideoMb, 100 MB; none for a kept post) and a job budget of 40 files / 200 MB, the rest owed; a 429 stops the job and records the 15 minute cooldown, a 403 or 404 marks the file, nothing retries. Each file is a hardlink to its blob in trending/media-store/ (by SHA-256; media-index.json maps hash to bytes, addresses and posts), so the same bytes under two posts are one file and an address already known is linked without a fetch. removeXTrendingPostCapture removes a post's capture and only the blobs no other post carries (no door calls it yet). trending/.gitignore keeps posts-media/ and media-store/ out of the corpus repo. A media download may now be owed, name the files that landed, and stop the run.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCHANNEL.md | 2+-
Mcommon/controller/capturePosts.test.ts | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/capturePosts.ts | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/channelConfig.ts | 2+-
Mcommon/lib/xTrending/config.test.ts | 9+++++++++
Mcommon/lib/xTrending/config.ts | 13+++++++++++++
Acommon/lib/xTrending/mediaStore.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/xTrending/mediaStore.ts | 296+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/__fixtures__/xTrendingCapture.ts | 12++++++++++++
Mcommon/social/fetchers.ts | 35+++++++++++++++++++++++++++++++++++
Mcommon/social/xGalleryDlFetcher.ts | 18+++++++++++++-----
Mcommon/social/xPostCapture.test.ts | 25+++++++++++++++++++++++++
Mcommon/social/xPostCapture.ts | 13+++++++++----
Acommon/social/xTrendingMedia.test.ts | 268+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/xTrendingMedia.ts | 296+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.test.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/xTrendingParse.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 1492 insertions(+), 13 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -61,7 +61,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). | | `wayback` | config | A WAYBACK PAGES channel (platform `"webpage"`, `sourceKind` `"social"`): which Wayback Machine captures of pages that are not videos are in scope. `{targets: [{url, match, from?, to?, mime?, include?, exclude?}], collapse?: "digest", auto?: true}` — `match` is `"exact"` (one page), `"prefix"` (every URL under a path), `"host"` (one host) or `"domain"` (a host and its subdomains); `from`/`to` bound the capture time (a Wayback timestamp prefix, 4–14 digits, inclusive); `mime` the mimetypes kept (default `text/html`); `include`/`exclude` regex sources over a capture's original URL. Each capture imported (`pnpm ops import-page`, the channel page's **Import a capture**) becomes a page record in the channel's posts, its raw body kept under `pages/` (OPERATING.md, "Import from the Wayback Machine"). A target without a URL or a valid `match` is dropped; an object with no valid target is dropped. `auto: true` lets the download lane import the captures a later scan (`pnpm ops wayback-scan`, the **Captures** tab) adds, one job each at archive.org's pace; absent, nothing is imported unasked. Release 37 lane F: a target's `sources` (`["wayback", "archive.today"]`; absent = the Wayback Machine alone) says which archives hold its copies, and an archive.today copy imported into the channel is a page record like a capture (OPERATING.md, "Archived pages: the Wayback Machine and archive.today"); the form calls the kind "Archived pages". | | `xSearch` | config | An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X's search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window's span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl's search, resumable, at the older walk's pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped. | -| `xTrending` | config | An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X's trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor's own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field. | +| `xTrending` | config | An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X's trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?, maxVideoMb?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60), and the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor's own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field. | | `localMedia` | config | Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports. | #### `downloadFilter` diff --git a/common/controller/capturePosts.test.ts b/common/controller/capturePosts.test.ts @@ -513,3 +513,104 @@ test("an X trending library: its posts, captures and availability are under tren assert.equal((await readPostAvailability(path.join(root, "trending")))["7001"]?.availability, "deleted"); assert.deepEqual(await readPostAvailability(root), {}); }); + +test("an X trending library's media comes from the CDN addresses in its saved capture, kept once, and is ignored by the corpus repo", async () => { + const { fixtureTimelineBody } = await import("../social/__fixtures__/xTrendingCapture"); + const { recordXTrendingRead, trendingReadDir, writeXTrendingPosts } = await import("../lib/xTrending/store"); + const { readXTrendingMediaIndex } = await import("../lib/xTrending/mediaStore"); + const { parseTrendingCapture } = await import("../social/xTrendingParse"); + const { readFile, stat } = await import("node:fs/promises"); + const root = path.join(channelsDir, "demo-library-media"); + await mkdir(path.join(root, "trending"), { recursive: true }); + await writeFile( + path.join(root, "config.json"), + JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", postFetcher: "test-capture-x", name: "Library", xTrending: {} }), + ); + // One saved read: a post with two pictures, a post with a video, a post with none. + const READ = "tr-01JA0000000000000000000000"; + const A = "1900000000000003001"; + const B = "1900000000000003002"; + const C = "1900000000000003003"; + const line = { + n: 1, + at: "2026-11-18T10:00:00.000Z", + op: "ExampleTrendTimeline", + status: 200, + url: "u", + bytes: 1, + body: fixtureTimelineBody([ + { id: A, handle: "teapot_news", text: "Two pictures.", media: ["photo", "photo"] }, + { id: B, handle: "spout_clips", text: "A video.", media: ["video"] }, + { id: C, handle: "lid_watch", text: "Words only." }, + ]), + }; + await mkdir(trendingReadDir(root, READ), { recursive: true }); + await writeFile(path.join(trendingReadDir(root, READ), "responses.jsonl"), JSON.stringify(line) + "\n"); + const parsed = parseTrendingCapture([line], "demo-library-media"); + await writeXTrendingPosts(root, parsed.posts); + await recordXTrendingRead(root, { + readId: READ, + at: "2026-11-18T10:00:00.000Z", + ref: { trendId: "1900000000000000001", url: "https://x.com/i/trending/1900000000000000001" }, + topic: "Kettles", + postIds: parsed.posts.map((p) => p.id), + added: 3, + media: parsed.media, + }); + + // The stand-in fetcher runs the media half it was handed, as X's does. + const asked: string[] = []; + const results: Record<string, unknown> = {}; + const { getSocialFetcher } = await import("../social/fetchers"); + const fake = getSocialFetcher("test-capture-x")!; + const original = fake.captureByIds!; + fake.captureByIds = async (input) => { + calls.push(input); + assert.equal(typeof input.downloadMedia, "function"); + for (const id of input.ids) { + results[id] = await input.downloadMedia!( + { id, dir: path.join(input.outDir, id), signal: new AbortController().signal }, + async () => { + throw new Error("no logged-in download for a post nobody kept"); + }, + ); + } + return { outcomes: [] }; + }; + calls = []; + try { + const res = await run("demo-library-media", [A, B, C], { + shots: false, + articles: false, + context: false, + libraryMedia: { + deps: { + fetch: async (url: string) => { + asked.push(url); + const bytes = Buffer.from(`BYTES OF ${url.includes("video") ? "VIDEO" : "PICTURE"}`); + return { status: 200, headers: { get: () => String(bytes.length) }, body: (async function* () { yield bytes; })() }; + }, + pause: async () => {}, + cooldownMs: async () => 0, + }, + }, + }); + assert.equal(res.ok, true, res.error); + } finally { + fake.captureByIds = original; + } + assert.equal(calls[0].outDir, path.join(root, "trending", "posts-media")); + assert.deepEqual(asked, [ + "https://pbs.twimg.com/media/Fixture30010?format=jpg&name=orig", + "https://pbs.twimg.com/media/Fixture30011?format=jpg&name=orig", + `https://video.twimg.com/ext_tw_video/${B}0/vid/1280x720/high.mp4`, + ]); + assert.deepEqual((results[A] as { files: { name: string }[] }).files.map((f) => f.name), [`${A}_1.jpg`, `${A}_2.jpg`]); + assert.deepEqual(results[C], { ok: true, files: [] }); + // The two pictures had the same bytes: one blob, two names. + const one = await stat(path.join(root, "trending", "posts-media", A, `${A}_1.jpg`)); + const two = await stat(path.join(root, "trending", "posts-media", A, `${A}_2.jpg`)); + assert.equal(one.ino, two.ino); + assert.equal(Object.keys((await readXTrendingMediaIndex(root)).blobs).length, 2); + assert.match(await readFile(path.join(root, "trending", ".gitignore"), "utf8"), /^posts-media\/$/m); +}); diff --git a/common/controller/capturePosts.ts b/common/controller/capturePosts.ts @@ -34,8 +34,24 @@ import path from "node:path"; import { isXSearchChannel } from "../lib/xSearch/config"; -import { isXTrendingChannel } from "../lib/xTrending/config"; -import { xTrendingPostsRoot } from "../lib/xTrending/store"; +import { isXTrendingChannel, xTrendingMaxVideoBytes, type XTrendingConfig } from "../lib/xTrending/config"; +import { + readXTrendingMembership, + TRENDING_RESPONSES_FILENAME, + trendingReadDir, + xTrendingPostsRoot, +} from "../lib/xTrending/store"; +import { ensureXTrendingMediaIgnore } from "../lib/xTrending/mediaStore"; +import { platformCooldownRemainingMs, recordPlatformCooldown } from "../jobs/downloadBackoff"; +import type { ChromiumLike } from "../social/playwrightRuntime"; +import { + createLibraryMediaDownloader, + libraryMediaPauseMs, + type LibraryMediaDeps, + type MediaFetch, +} from "../social/xTrendingMedia"; +import { mediaSourcesInCapture, readCaptureLines, type TrendingMediaSource } from "../social/xTrendingParse"; +import { X_RATE_LIMIT_HOLD_MS } from "./readXTrending"; import { readChannelConfig } from "./channels"; import type { Paths } from "../lib/paths"; import type { Post, PostAvailability } from "../lib/posts"; @@ -115,6 +131,22 @@ export type CapturePostsOptions = { // A Wayback pages channel's render and archive (tests; default the // process's Wayback client and a headless Chromium). pageDeps?: WaybackPageCaptureDeps; + // AN X TRENDING LIBRARY'S MEDIA HALF (social/xTrendingMedia.ts): the files + // come from X's media CDN, by the addresses in the library's saved + // captures, and are kept once. + // fallback "login": a post the CDN could not serve whole is + // downloaded the logged-in way (a post marked keep). + // Default "none" (a watch never logs in for media). + // maxVideoBytes a file over this is owed, not kept; null = no cap (a + // kept post). Default: the library's `maxVideoMb`. + // deps tests and the e2e test server: the fetch and the waits. + libraryMedia?: { + fallback?: "login" | "none"; + maxVideoBytes?: number | null; + deps?: Partial<LibraryMediaDeps>; + }; + // X: the browser the profile is opened with (the e2e suite's fake). + chromium?: ChromiumLike; }; export type CapturePostsResult = { @@ -349,10 +381,19 @@ export async function capturePosts( ".", ); + // A library's media: from the CDN addresses in its saved captures. + const libraryDownload = + library && opts.media !== false && !avatarsOnly && !contextOnly + ? await libraryMediaDownloader(paths, channelDir, ids, config.xTrending, opts.libraryMedia, log) + : undefined; + if (library) await ensureXTrendingMediaIgnore(channelDir); + const controller = new AbortController(); let result; try { result = await fetcher.captureByIds({ + ...(libraryDownload ? { downloadMedia: libraryDownload } : {}), + ...(opts.chromium ? { chromium: opts.chromium } : {}), ids, handle, accountUrl, @@ -446,6 +487,74 @@ export async function capturePosts( return { ok: true, outcomes: result.outcomes, ...avatars }; } +const waitFor = (ms: number, signal: AbortSignal) => + new Promise<void>((resolve) => { + if (ms <= 0 || signal.aborted) return resolve(); + const done = () => { + clearTimeout(t); + signal.removeEventListener("abort", done); + resolve(); + }; + const t = setTimeout(done, ms); + signal.addEventListener("abort", done, { once: true }); + }); + +// The library's media half for these ids: where the CDN serves each post's +// files, read from the saved captures of the reads that showed the post +// (newest first; a read is parsed once), and the downloader over them. +async function libraryMediaDownloader( + paths: Paths, + channelDir: string, + ids: ReadonlyArray<string>, + config: XTrendingConfig | undefined, + asked: CapturePostsOptions["libraryMedia"], + log: (line: string) => void, +) { + const membership = await readXTrendingMembership(channelDir); + const sources = new Map<string, TrendingMediaSource[]>(); + const expected = new Map<string, number>(); + const parsed = new Map<string, Map<string, TrendingMediaSource[]>>(); + for (const id of ids) { + const member = membership[id]; + if (!member) continue; + if (member.media?.count) expected.set(id, member.media.count); + const reads = [...member.seen].sort((a, b) => (a.at < b.at ? 1 : -1)).map((s) => s.read); + for (const read of reads) { + let found = parsed.get(read); + if (!found) { + const file = path.join(trendingReadDir(channelDir, read), TRENDING_RESPONSES_FILENAME); + found = mediaSourcesInCapture(await readCaptureLines(file).catch(() => [])); + parsed.set(read, found); + } + const have = found.get(id); + if (have?.length) { + sources.set(id, have); + break; + } + } + } + const withMedia = [...expected.keys()].length; + if (withMedia > 0) { + log(`Media: ${sources.size} of ${withMedia} post(s) with media have CDN addresses in the saved captures (${parsed.size} read(s) looked at).`); + } + const X = "twitter"; + return createLibraryMediaDownloader({ + channelRoot: channelDir, + sources, + expected, + maxVideoBytes: asked?.maxVideoBytes === undefined ? xTrendingMaxVideoBytes(config) : asked.maxVideoBytes, + fallback: asked?.fallback ?? "none", + deps: { + fetch: (url, init) => fetch(url, init) as unknown as ReturnType<MediaFetch>, + pauseMs: () => libraryMediaPauseMs(), + pause: waitFor, + cooldownMs: () => platformCooldownRemainingMs(X, paths), + noteRateLimit: () => recordPlatformCooldown(X, X_RATE_LIMIT_HOLD_MS, paths), + ...asked?.deps, + }, + }); +} + // capture-posts on a Wayback pages channel: the records' shots from their // captures' replays (social/waybackPageCapture.ts). Only ids in the channel's // posts archive; nothing is recorded in the availability sidecar (a capture diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -402,7 +402,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { xSearch: 'An X SEARCH channel (platform `"twitter"`, `sourceKind` `"social"`, `url` the search page): a saved X search across accounts, its records the matching posts from ANY author. `{query, since?, until?, windowMonths?, lang?, exclude?}` — `query` as X\'s search box takes it (words, `"phrases"`, `OR`, `-term`, `from:`, `to:`, `@mention`, `url:`, `filter:`, `lang:` pass through; `since:`, `until:` and `max_id:` are refused — the walk adds them); `since`/`until` the days walked between (YYYY-MM-DD; `since` inclusive, `until` exclusive; absent `until` = tomorrow, and each later fetch searches what is new); `windowMonths` each search window\'s span (1–12, default 3); `lang` a language code added as `lang:<code>`; `exclude` the handles **Never archive** hid from the leads view (lower case). A fetch walks the windows newest first through gallery-dl\'s search, resumable, at the older walk\'s pace and with its login (OPERATING.md, "X search"). Never on a site. An object without a valid query is dropped.', xTrending: - 'An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X\'s trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor\'s own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field.', + 'An X TRENDING LIBRARY (platform `"twitter"`, `sourceKind` `"social"`, no `url`): a PRIVATE posts channel whose records are the posts X\'s trending pages (`x.com/i/trending/<id>`) showed, from ANY author, read one page at a time by `pnpm ops read-x-trending` and grouped into topics. Everything of it — its posts too — is kept under `channels/<slug>/trending/`, not in `channels/<slug>/posts/`, so no reader of a posts channel finds them. The marker alone makes a channel a library. `{maxScrolls?, maxPosts?, maxVideoMb?}` — the caps a read uses when the ask names none (1–20 scrolls, default 8; 1–200 posts, default 60), and the largest media file, in MB, fetched for a post nobody has kept (1–2000, default 100; a larger one is owed until the post is kept); `{}` is a library with the defaults. Never on a site (refused on create, on Configure and by every site writer), in no index build (so not in the editor\'s own search either), never synced. Set by creating a channel with platform `x-trending`; not a Configure field.', localMedia: "Opt-in external MP4 library: {sourceId, directory, playback?}. The sourceId is a stable lowercase identifier; directory is an absolute server/container path. Source files remain externally owned. Playback is off unless explicitly true, and this flag alone does not authorize public serving. Removing or changing configuration must never move or delete source files. Do not reuse an existing sourceId for a different library; reconcile references explicitly. Private configuration: never include source paths in public exports.", }; diff --git a/common/lib/xTrending/config.test.ts b/common/lib/xTrending/config.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { + xTrendingMaxVideoBytes, coerceXTrendingConfig, isXTrendingChannel, parseXTrendingUrl, @@ -76,3 +77,11 @@ test("a read's caps: the ask, else the channel's, else 8 scrolls and 60 posts; o assert.deepEqual(xTrendingLimits({}, { posts: 0 }), { ok: false, error: '"posts" is a whole number, 1–200' }); assert.deepEqual(xTrendingLimits({}, { scrolls: "8" }), { ok: false, error: '"scrolls" is a whole number, 1–20' }); }); + +test("the per-file media cap: 100 MB unless the library says otherwise, kept only in range", () => { + assert.equal(xTrendingMaxVideoBytes(undefined), 100 * 1024 * 1024); + assert.equal(xTrendingMaxVideoBytes({ maxVideoMb: 20 }), 20 * 1024 * 1024); + assert.deepEqual(coerceXTrendingConfig({ maxVideoMb: 250 }), { maxVideoMb: 250 }); + assert.deepEqual(coerceXTrendingConfig({ maxVideoMb: 0 }), {}); + assert.deepEqual(coerceXTrendingConfig({ maxVideoMb: 2001 }), {}); +}); diff --git a/common/lib/xTrending/config.ts b/common/lib/xTrending/config.ts @@ -21,6 +21,10 @@ export type XTrendingConfig = { // A read stops scrolling once it has seen this many posts. Absent: // X_TRENDING_DEFAULT_POSTS. maxPosts?: number; + // A media file larger than this many MB is not fetched for a post nobody + // has kept (a watched topic's new posts): it is owed until the post is + // kept. Absent: X_TRENDING_DEFAULT_VIDEO_MB. + maxVideoMb?: number; }; // The two job kinds, and X's platform queue they run on: one browser on the @@ -49,6 +53,8 @@ export const X_TRENDING_DEFAULT_SCROLLS = 8; export const X_TRENDING_MAX_SCROLLS = 20; export const X_TRENDING_DEFAULT_POSTS = 60; export const X_TRENDING_MAX_POSTS = 200; +export const X_TRENDING_DEFAULT_VIDEO_MB = 100; +export const X_TRENDING_MAX_VIDEO_MB = 2000; // A read ends after this many scrolls in a row that brought no new post. export const X_TRENDING_IDLE_SCROLLS = 2; @@ -66,6 +72,8 @@ export function coerceXTrendingConfig(v: unknown): XTrendingConfig | undefined { const posts = capOf(r.maxPosts, X_TRENDING_MAX_POSTS); if (scrolls !== undefined) out.maxScrolls = scrolls; if (posts !== undefined) out.maxPosts = posts; + const videoMb = capOf(r.maxVideoMb, X_TRENDING_MAX_VIDEO_MB); + if (videoMb !== undefined) out.maxVideoMb = videoMb; return out; } @@ -138,3 +146,8 @@ export function xTrendingLimits( if (typeof posts === "string") return { ok: false, error: posts }; return { ok: true, limits: { scrolls, posts } }; } + +// The per-file cap, in bytes, for media fetched before a post is kept. +export function xTrendingMaxVideoBytes(config: XTrendingConfig | undefined): number { + return (config?.maxVideoMb ?? X_TRENDING_DEFAULT_VIDEO_MB) * 1024 * 1024; +} diff --git a/common/lib/xTrending/mediaStore.test.ts b/common/lib/xTrending/mediaStore.test.ts @@ -0,0 +1,152 @@ +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + adoptXTrendingMedia, + ensureXTrendingMediaIgnore, + linkXTrendingMedia, + readXTrendingMediaIndex, + removeXTrendingPostCapture, + xTrendingBlobByUrl, + xTrendingMediaStoreDir, +} from "./mediaStore"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-media-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const sha = (s: string) => createHash("sha256").update(s).digest("hex"); +const root = (name: string) => path.join(TMP, name); +const postDir = (dir: string, id: string) => path.join(dir, "trending", "posts-media", id); + +function put(dir: string, id: string, name: string, bytes: string): string { + mkdirSync(postDir(dir, id), { recursive: true }); + const file = path.join(postDir(dir, id), name); + writeFileSync(file, bytes); + return file; +} + +const blobOf = (dir: string, bytes: string, ext: string) => path.join(xTrendingMediaStoreDir(dir), sha(bytes).slice(0, 2), `${sha(bytes)}.${ext}`); + +test("a captured file becomes the blob; the same bytes under another post are one file", async () => { + const dir = root("dedupe"); + const a = put(dir, "601", "601_1.jpg", "PICTURE-ONE"); + const first = await adoptXTrendingMedia(dir, { postId: "601", name: "601_1.jpg", url: "https://pbs.twimg.com/media/One.jpg", now: () => Date.parse("2026-11-18T10:00:00Z") }); + assert.deepEqual(first, { sha256: sha("PICTURE-ONE"), bytes: 11, deduped: false, linked: true }); + const blob = blobOf(dir, "PICTURE-ONE", "jpg"); + assert.equal(statSync(blob).ino, statSync(a).ino); + assert.equal(statSync(blob).nlink, 2); + + // The same picture on another post, in another topic: fetched again, kept once. + const b = put(dir, "602", "602_1.jpg", "PICTURE-ONE"); + assert.notEqual(statSync(b).ino, statSync(blob).ino); + const second = await adoptXTrendingMedia(dir, { postId: "602", name: "602_1.jpg", url: "https://pbs.twimg.com/media/OneAgain.jpg" }); + assert.equal(second.deduped, true); + assert.equal(statSync(b).ino, statSync(blob).ino); + assert.equal(statSync(blob).nlink, 3); + assert.equal(readFileSync(b, "utf8"), "PICTURE-ONE"); + + // Other bytes are another blob: exact duplicates only. + put(dir, "602", "602_2.jpg", "PICTURE-ONE."); + assert.equal((await adoptXTrendingMedia(dir, { postId: "602", name: "602_2.jpg" })).deduped, false); + + const index = await readXTrendingMediaIndex(dir); + assert.deepEqual(index.blobs[sha("PICTURE-ONE")], { + bytes: 11, + ext: "jpg", + addedAt: "2026-11-18T10:00:00.000Z", + urls: ["https://pbs.twimg.com/media/One.jpg", "https://pbs.twimg.com/media/OneAgain.jpg"], + posts: { "601": ["601_1.jpg"], "602": ["602_1.jpg"] }, + }); + assert.equal(Object.keys(index.blobs).length, 2); + // Adopting the same name again changes nothing. + assert.equal((await adoptXTrendingMedia(dir, { postId: "601", name: "601_1.jpg" })).linked, true); + assert.equal(statSync(blob).nlink, 3); + // No leftover link temp in the capture directory. + assert.deepEqual(readdirSync(postDir(dir, "602")).sort(), ["602_1.jpg", "602_2.jpg"]); +}); + +test("a known address is linked with no fetch; an unknown blob is not", async () => { + const dir = root("link"); + put(dir, "611", "611_1.mp4", "VIDEO-BYTES"); + await adoptXTrendingMedia(dir, { postId: "611", name: "611_1.mp4", url: "https://video.twimg.com/v/high.mp4" }); + const index = await readXTrendingMediaIndex(dir); + const known = xTrendingBlobByUrl(index, "https://video.twimg.com/v/high.mp4"); + assert.equal(known, sha("VIDEO-BYTES")); + assert.equal(xTrendingBlobByUrl(index, "https://video.twimg.com/v/other.mp4"), undefined); + // The post's directory does not exist yet: it is made. + assert.deepEqual(await linkXTrendingMedia(dir, { postId: "612", name: "612_1.mp4", sha256: known! }), { bytes: 11 }); + assert.equal(readFileSync(path.join(postDir(dir, "612"), "612_1.mp4"), "utf8"), "VIDEO-BYTES"); + assert.equal(statSync(blobOf(dir, "VIDEO-BYTES", "mp4")).nlink, 3); + assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs[known!].posts, { "611": ["611_1.mp4"], "612": ["612_1.mp4"] }); + assert.equal(await linkXTrendingMedia(dir, { postId: "613", name: "613_1.mp4", sha256: sha("nothing") }), null); + // A blob removed from the store under the index: not linked (the caller fetches). + rmSync(blobOf(dir, "VIDEO-BYTES", "mp4")); + assert.equal(await linkXTrendingMedia(dir, { postId: "614", name: "614_1.mp4", sha256: known! }), null); + // ...and adopting a file with those bytes puts the blob back. + put(dir, "614", "614_1.mp4", "VIDEO-BYTES"); + await adoptXTrendingMedia(dir, { postId: "614", name: "614_1.mp4" }); + assert.equal(existsSync(blobOf(dir, "VIDEO-BYTES", "mp4")), true); +}); + +test("deleting a post never deletes media another post still uses", async () => { + const dir = root("remove"); + put(dir, "621", "621_1.jpg", "SHARED"); + put(dir, "621", "621_2.jpg", "ONLY-621"); + put(dir, "621", "shot.png", "SHOT"); + put(dir, "621", "capture.json", "{}"); + put(dir, "622", "622_1.jpg", "SHARED"); + await adoptXTrendingMedia(dir, { postId: "621", name: "621_1.jpg" }); + await adoptXTrendingMedia(dir, { postId: "621", name: "621_2.jpg" }); + await adoptXTrendingMedia(dir, { postId: "622", name: "622_1.jpg" }); + const shared = blobOf(dir, "SHARED", "jpg"); + const only = blobOf(dir, "ONLY-621", "jpg"); + assert.equal(statSync(shared).nlink, 3); + + const removed = await removeXTrendingPostCapture(dir, "621"); + assert.deepEqual(removed, { files: 4, blobsFreed: 1, bytesFreed: 8, blobsKept: 1 }); + assert.equal(existsSync(postDir(dir, "621")), false); + // 622's picture is whole, and so is the store's copy of it. + assert.equal(readFileSync(path.join(postDir(dir, "622"), "622_1.jpg"), "utf8"), "SHARED"); + assert.equal(statSync(shared).nlink, 2); + assert.equal(existsSync(only), false); + const index = await readXTrendingMediaIndex(dir); + assert.deepEqual(Object.keys(index.blobs), [sha("SHARED")]); + assert.deepEqual(index.blobs[sha("SHARED")].posts, { "622": ["622_1.jpg"] }); + + // The last post that carries it takes the blob with it. + assert.deepEqual(await removeXTrendingPostCapture(dir, "622"), { files: 1, blobsFreed: 1, bytesFreed: 6, blobsKept: 0 }); + assert.equal(existsSync(shared), false); + assert.deepEqual((await readXTrendingMediaIndex(dir)).blobs, {}); + // A post with no capture: nothing to remove, nothing thrown. + assert.deepEqual(await removeXTrendingPostCapture(dir, "629"), { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }); +}); + +test("a blob something else still links to is kept, even when the index names no post for it", async () => { + const dir = root("stray-link"); + put(dir, "631", "631_1.jpg", "KEPT-ELSEWHERE"); + await adoptXTrendingMedia(dir, { postId: "631", name: "631_1.jpg" }); + // A second name the index never heard of (a file linked by hand). + const { linkSync } = await import("node:fs"); + mkdirSync(postDir(dir, "632"), { recursive: true }); + linkSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg"), path.join(postDir(dir, "632"), "632_1.jpg")); + const removed = await removeXTrendingPostCapture(dir, "631"); + assert.equal(removed.blobsFreed, 0); + assert.equal(removed.blobsKept, 1); + assert.equal(readFileSync(path.join(postDir(dir, "632"), "632_1.jpg"), "utf8"), "KEPT-ELSEWHERE"); + assert.equal(existsSync(blobOf(dir, "KEPT-ELSEWHERE", "jpg")), true); +}); + +test("ids and names are checked where they become paths; the media is ignored by the corpus repo", async () => { + const dir = root("checks"); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "../x", name: "a.jpg" }), /not a post id/); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: "../a.jpg" }), /not a media file's name/); + await assert.rejects(adoptXTrendingMedia(dir, { postId: "1", name: ".hidden" }), /not a media file's name/); + await assert.rejects(removeXTrendingPostCapture(dir, "_avatars"), /not a post id/); + await ensureXTrendingMediaIgnore(dir); + const ignore = readFileSync(path.join(dir, "trending", ".gitignore"), "utf8"); + assert.match(ignore, /^posts-media\/$/m); + assert.match(ignore, /^media-store\/$/m); +}); diff --git a/common/lib/xTrending/mediaStore.ts b/common/lib/xTrending/mediaStore.ts @@ -0,0 +1,296 @@ +// A LIBRARY'S MEDIA, KEPT ONCE (lane x-trending-2). +// +// channels/<lib>/trending/media-store/<aa>/<sha256>.<ext> the bytes, once +// per content hash +// channels/<lib>/trending/posts-media/<id>/<name> a HARDLINK to +// its blob +// channels/<lib>/trending/media-index.json hash → bytes, +// the addresses it came from, and the posts (and file names) that carry it +// +// EXACT DUPLICATES ONLY: two files are one when their SHA-256 is. The same +// video at another quality, or a picture re-encoded, is another file. +// +// WHY HARDLINKS. Every reader of a capture directory (the listing's +// thumbnail, the capture's own file list, umtool) opens a plain file and +// needs to know nothing. Unlinking one post's name cannot touch another +// post's bytes: the file system counts the links, and the bytes go when the +// last one does. A file system that refuses a link (another device, a link +// limit) leaves the file where it was, an ordinary copy: nothing is lost, +// that file is simply not shared. +// +// KNOWN ADDRESS, NO FETCH. The index remembers the address each blob came +// from, so a post carrying a file the library already holds is linked to it +// without asking the CDN (linkXTrendingMedia). +// +// NOT IN THE MEDIA TIER. The tier (lib/mediaTier.ts) is by name over a video +// dir, `data/<id>/`; no posts channel's `posts-media/` is in it, and a +// library's is not either: it stays on the corpus disk beside the library's +// text, like `clips/`. So nothing here is a link out of the channel, and +// removeMediaFile (the one `rm` of a media file) removes these names as the +// plain files they are. +// +// NEVER COMMITTED. `trending/.gitignore` keeps `posts-media/` and +// `media-store/` out of the corpus's own git repo: hardlinks do not survive +// git, and the bytes are big. The index is small text and is not ignored. +// +// THIS MODULE IS THE ONE WRITER of media-index.json and of the store; every +// write is under the index's lock. SERVER-ONLY (node:fs). + +import path from "node:path"; +import { link, lstat, mkdir, readFile, readdir, rename, rm, rmdir, stat } from "node:fs/promises"; +import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; +import { removeMediaFile } from "../mediaTier-server"; +import { fileDigest, postCaptureDir } from "../../social/postCapture"; +import { trendingDir, xTrendingPostsMediaDir } from "./store"; + +export const X_TRENDING_MEDIA_STORE_DIRNAME = "media-store"; +export const X_TRENDING_MEDIA_INDEX_FILENAME = "media-index.json"; + +export function xTrendingMediaStoreDir(channelRoot: string): string { + return path.join(trendingDir(channelRoot), X_TRENDING_MEDIA_STORE_DIRNAME); +} + +export function xTrendingMediaIndexPath(channelRoot: string): string { + return path.join(trendingDir(channelRoot), X_TRENDING_MEDIA_INDEX_FILENAME); +} + +export const TRENDING_MEDIA_GITIGNORE = + "# A library's captured media: hardlinked, big, never committed.\nposts-media/\nmedia-store/\n"; + +// trending/, with the .gitignore that keeps the media out of the corpus repo. +export async function ensureXTrendingMediaIgnore(channelRoot: string): Promise<void> { + const dir = trendingDir(channelRoot); + await mkdir(dir, { recursive: true }); + const file = path.join(dir, ".gitignore"); + const have = await readFile(file, "utf8").catch(() => null); + if (have !== TRENDING_MEDIA_GITIGNORE) await writeFileAtomic(file, TRENDING_MEDIA_GITIGNORE); +} + +export type XTrendingMediaBlob = { + bytes: number; + ext: string; + addedAt: string; + // The addresses this content came from (a file's identity address, as the + // capture names it), oldest first. + urls: string[]; + // Post id → its file names that are this blob. + posts: Record<string, string[]>; +}; + +export type XTrendingMediaIndex = { version: 1; blobs: Record<string, XTrendingMediaBlob> }; + +const SHA = /^[0-9a-f]{64}$/; +const POST_ID = /^\d{1,25}$/; +// A media file's name inside a capture directory: no path, no dotfile. +const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/; + +function parseIndex(raw: unknown): XTrendingMediaIndex { + const blobs = (raw as { blobs?: unknown } | null)?.blobs; + const out: XTrendingMediaIndex = { version: 1, blobs: {} }; + if (!blobs || typeof blobs !== "object" || Array.isArray(blobs)) return out; + for (const [sha, b] of Object.entries(blobs as Record<string, Partial<XTrendingMediaBlob> | null>)) { + if (!SHA.test(sha) || !b || typeof b !== "object") continue; + const posts: Record<string, string[]> = {}; + for (const [id, names] of Object.entries(b.posts && typeof b.posts === "object" ? b.posts : {})) { + if (!POST_ID.test(id) || !Array.isArray(names)) continue; + const kept = names.filter((n): n is string => typeof n === "string" && NAME.test(n)); + if (kept.length > 0) posts[id] = kept; + } + out.blobs[sha] = { + bytes: Number(b.bytes) || 0, + ext: typeof b.ext === "string" && /^[a-z0-9]{1,5}$/.test(b.ext) ? b.ext : "bin", + addedAt: typeof b.addedAt === "string" ? b.addedAt : "", + urls: Array.isArray(b.urls) ? b.urls.filter((u): u is string => typeof u === "string" && u !== "") : [], + posts, + }; + } + return out; +} + +export async function readXTrendingMediaIndex(channelRoot: string): Promise<XTrendingMediaIndex> { + const read = await readJsonFile(xTrendingMediaIndexPath(channelRoot)); + return read.ok ? parseIndex(read.value) : { version: 1, blobs: {} }; +} + +// The blob that came from this address, or undefined. +export function xTrendingBlobByUrl(index: XTrendingMediaIndex, url: string): string | undefined { + for (const [sha, b] of Object.entries(index.blobs)) if (b.urls.includes(url)) return sha; + return undefined; +} + +function extOf(name: string): string { + const ext = path.extname(name).slice(1).toLowerCase(); + return /^[a-z0-9]{1,5}$/.test(ext) ? ext : "bin"; +} + +function blobPath(channelRoot: string, sha: string, ext: string): string { + return path.join(xTrendingMediaStoreDir(channelRoot), sha.slice(0, 2), `${sha}.${ext}`); +} + +function checked(postId: string, name: string): void { + if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); + if (!NAME.test(name)) throw new Error(`"${name}" is not a media file's name`); +} + +// `target` linked at `file`, replacing what is there, atomically (a link +// beside it, renamed over it). False when the file system refuses the link. +async function linkOver(target: string, file: string): Promise<boolean> { + const tmp = path.join(path.dirname(file), `.${path.basename(file)}.link-${process.pid}`); + await rm(tmp, { force: true }); + try { + await link(target, tmp); + } catch (err) { + const code = (err as NodeJS.ErrnoException).code; + if (code === "EXDEV" || code === "EPERM" || code === "EMLINK" || code === "ENOTSUP") return false; + throw err; + } + await rename(tmp, file); + return true; +} + +const sameFile = (a: { dev: number; ino: number }, b: { dev: number; ino: number }) => a.dev === b.dev && a.ino === b.ino; + +function note(blob: XTrendingMediaBlob, postId: string, name: string, url?: string): void { + const names = (blob.posts[postId] ??= []); + if (!names.includes(name)) names.push(name); + if (url && !blob.urls.includes(url)) blob.urls.push(url); +} + +export type AdoptedMedia = { + sha256: string; + bytes: number; + // The library already held these bytes: this name is now a link to them. + deduped: boolean; + // The name shares its bytes with the store (false: the file system refused + // the link, and the file stays an ordinary copy). + linked: boolean; +}; + +// A FILE JUST CAPTURED, TAKEN INTO THE STORE: hashed, and either linked to the +// blob the library already holds for that content (its own bytes dropped) or +// made the blob. `url` is the address it came from, when known. +export async function adoptXTrendingMedia( + channelRoot: string, + o: { postId: string; name: string; url?: string; now?: () => number }, +): Promise<AdoptedMedia> { + checked(o.postId, o.name); + const file = path.join(postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId), o.name); + const { sha256, bytes } = await fileDigest(file); + await ensureXTrendingMediaIgnore(channelRoot); + return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const index = await readXTrendingMediaIndex(channelRoot); + const have = index.blobs[sha256]; + const ext = have?.ext ?? extOf(o.name); + const blob = blobPath(channelRoot, sha256, ext); + await mkdir(path.dirname(blob), { recursive: true }); + const [fileStat, blobStat] = await Promise.all([stat(file), stat(blob).catch(() => null)]); + let deduped = false; + let linked: boolean; + if (blobStat && sameFile(fileStat, blobStat)) { + linked = true; + } else if (blobStat) { + // The library holds these bytes: this name becomes a link to them. + linked = await linkOver(blob, file); + deduped = linked; + } else { + // New content (or a blob somebody removed): this file is the blob. + linked = await linkOver(file, blob); + } + const entry = (index.blobs[sha256] ??= { + bytes, + ext, + addedAt: new Date((o.now ?? Date.now)()).toISOString(), + urls: [], + posts: {}, + }); + note(entry, o.postId, o.name, o.url); + await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + return { sha256, bytes, deduped, linked }; + }); +} + +// A BLOB THE LIBRARY HOLDS, GIVEN TO ANOTHER POST: `name` in the post's +// capture directory becomes a link to it — no fetch, no copy. Null when the +// store no longer has the blob (the caller fetches), or the link is refused. +export async function linkXTrendingMedia( + channelRoot: string, + o: { postId: string; name: string; sha256: string; url?: string }, +): Promise<{ bytes: number } | null> { + checked(o.postId, o.name); + if (!SHA.test(o.sha256)) return null; + return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const index = await readXTrendingMediaIndex(channelRoot); + const entry = index.blobs[o.sha256]; + if (!entry) return null; + const blob = blobPath(channelRoot, o.sha256, entry.ext); + const blobStat = await stat(blob).catch(() => null); + if (!blobStat?.isFile()) return null; + const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId); + await mkdir(dir, { recursive: true }); + if (!(await linkOver(blob, path.join(dir, o.name)))) return null; + note(entry, o.postId, o.name, o.url); + await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + return { bytes: blobStat.size }; + }); +} + +export type RemovedCapture = { + // Names removed from the post's capture directory. + files: number; + // Blobs no other post carried, removed with it, and their size. + blobsFreed: number; + bytesFreed: number; + // Blobs this post carried that another post still does: left alone. + blobsKept: number; +}; + +// ONE POST'S CAPTURE, REMOVED: its directory's files (through removeMediaFile) +// and the directory; and each blob it carried, ONLY when no other post carries +// it and nothing else links to it. Media another post still uses is never +// deleted: its bytes stay under that post's name and in the store. +// (No door calls this in this slice; the purge button and its ops twin are a +// later one's.) +export async function removeXTrendingPostCapture(channelRoot: string, postId: string): Promise<RemovedCapture> { + if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); + const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), postId); + return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { + const out: RemovedCapture = { files: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }; + const names = await readdir(dir).catch(() => [] as string[]); + for (const name of names) { + const st = await lstat(path.join(dir, name)).catch(() => null); + if (!st) continue; + if (st.isDirectory()) await rm(path.join(dir, name), { recursive: true, force: true }); + else await removeMediaFile(dir, name); + out.files++; + } + await rmdir(dir).catch(() => {}); + const index = await readXTrendingMediaIndex(channelRoot); + let changed = false; + for (const [sha, entry] of Object.entries(index.blobs)) { + if (!entry.posts[postId]) continue; + delete entry.posts[postId]; + changed = true; + if (Object.keys(entry.posts).length > 0) { + out.blobsKept++; + continue; + } + const blob = blobPath(channelRoot, sha, entry.ext); + const st = await stat(blob).catch(() => null); + // A link the index does not know of (a name copied by hand, an index + // that lost a post): the bytes are still somebody's, so the blob stays. + if (st && st.nlink > 1) { + out.blobsKept++; + continue; + } + if (st) { + await rm(blob, { force: true }); + await rmdir(path.dirname(blob)).catch(() => {}); + out.bytesFreed += st.size; + } + delete index.blobs[sha]; + out.blobsFreed++; + } + if (changed) await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); + return out; + }); +} diff --git a/common/social/__fixtures__/xTrendingCapture.ts b/common/social/__fixtures__/xTrendingCapture.ts @@ -51,6 +51,18 @@ export function fixtureTweetResult(t: FixtureTweet): Record<string, unknown> { type, media_key: `3_${t.id}${i}`, media_url_https: `https://pbs.twimg.com/media/Fixture${t.id.slice(-4)}${i}.jpg`, + // A video or a GIF: two progressive mp4s and a playlist, as X lists them. + ...(type === "photo" + ? {} + : { + video_info: { + variants: [ + { content_type: "application/x-mpegURL", url: `https://video.twimg.com/ext_tw_video/${t.id}${i}/pl/list.m3u8` }, + { content_type: "video/mp4", bitrate: 632000, url: `https://video.twimg.com/ext_tw_video/${t.id}${i}/vid/320x180/low.mp4?tag=12` }, + { content_type: "video/mp4", bitrate: 2176000, url: `https://video.twimg.com/ext_tw_video/${t.id}${i}/vid/1280x720/high.mp4?tag=12` }, + ], + }, + }), })), }, } diff --git a/common/social/fetchers.ts b/common/social/fetchers.ts @@ -20,6 +20,7 @@ import type { XCookieSource } from "./xCookieSource"; import type { PostCaptureState } from "./postCapture"; import type { XAvatarRunSummary } from "./xAvatarCapture"; import type { XContextRunSummary } from "./xPostContext"; +import type { ChromiumLike } from "./playwrightRuntime"; export type PostFetchInput = { // The account's canonical URL as configured on the channel. @@ -235,6 +236,28 @@ export type PostAvailabilityInput = { // archived posts. The login fields are a normal fetch's; `outDir` is the // channel's `posts-media/`, one directory per post id beneath it // (postCapture.ts owns the layout). +// How one post's media download went (X). A failure may still name the files +// it did land (`files`), say the post is merely OWED the rest (`owed`: over a +// cap, past the job's budget — not an error of the post), and may stop the +// whole run with a sentence (`stop`: a rate limit, a spent budget). +export type PostMediaDownload = + | { ok: true; files: { name: string; url?: string }[] } + | { + ok: false; + error: string; + needsCookies?: boolean; + files?: { name: string; url?: string }[]; + owed?: boolean; + stop?: string; + }; + +export type PostMediaDownloadArgs = { + id: string; + dir: string; + signal: AbortSignal; + onLog?: (line: string) => void; +}; + export type PostCaptureInput = Pick< PostFetchInput, "cookies" | "cookieSource" | "browserCookies" | "signal" | "onLog" | "pagePauseMs" @@ -277,6 +300,18 @@ export type PostCaptureInput = Pick< // capture.json and the avatars the page shows saved; no shot, no media, no // article, no thread shot, no availability observation. Defaults to false. contextOnly?: boolean; + // X: the media half done by the CALLER instead of the fetcher's own + // logged-in download (an X trending library: the media CDN addresses in its + // saved captures, each file kept once — controller/capturePosts.ts). `login` + // is the fetcher's own download of that post, for the caller to fall back + // on when it may. + downloadMedia?: ( + args: PostMediaDownloadArgs, + login: (args: PostMediaDownloadArgs) => Promise<PostMediaDownload>, + ) => Promise<PostMediaDownload>; + // X: the browser the profile is opened with (the e2e suite's fake; absent: + // Playwright's). + chromium?: ChromiumLike; // What the posts archive holds for each id — its text and expanded links — // for the links a capture follows (an X Article's). Ids absent are read // from the page alone. diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -62,6 +62,7 @@ import { type OlderPostFetchResult, type PostCaptureInput, type PostCaptureResult, + type PostMediaDownloadArgs, type PostFetchInput, type PostFetchResult, type SocialFetcher, @@ -410,16 +411,23 @@ export async function captureXPostsByIds( } } let login: Promise<{ cookies?: string; cookieFile?: string }> | undefined; + // The fetcher's own media download: one logged-in gallery-dl run per post. + const loginDownload = async ({ id, dir, signal, onLog }: PostMediaDownloadArgs) => { + login ??= galleryDlLoginFor(input); + return downloadXPostMedia({ id, dir, login: await login, signal, onLog }); + }; return captureXPosts(input, { openPage: async () => { - const context = await launchXProfile(paths, { onLog: input.onLog }); + const context = await launchXProfile(paths, { + onLog: input.onLog, + ...(input.chromium ? { chromium: input.chromium } : {}), + }); const page = context.pages()[0] ?? (await context.newPage()); return { page, close: () => context.close() }; }, - downloadMedia: async ({ id, dir, signal, onLog }) => { - login ??= galleryDlLoginFor(input); - return downloadXPostMedia({ id, dir, login: await login, signal, onLog }); - }, + // A caller that does the media half itself (an X trending library) is + // handed the logged-in download to fall back on. + downloadMedia: input.downloadMedia ? (args) => input.downloadMedia!(args, loginDownload) : loginDownload, pauseMs: () => xRequestPauseMs(), pause, articleImagePauseMs: () => ARTICLE_IMAGE_PAUSE_MS + Math.floor(Math.random() * ARTICLE_IMAGE_PAUSE_MS), diff --git a/common/social/xPostCapture.test.ts b/common/social/xPostCapture.test.ts @@ -415,6 +415,31 @@ test("run: media only, or shots only, does only that half", async () => { assert.deepEqual(r2.outcomes, [{ id: "11", state: "captured", availability: "available", files: 1 }]); }); +// Lane x-trending-2: a media half that is merely OWED, and one that stops the run. +test("run: a post owed the rest of its media is not a failure, keeps the files that landed, and is owed again; a stop ends the run", async () => { + const h = harness({}); + h.deps.downloadMedia = async ({ id, dir }) => { + h.downloads.push(id); + if (id === "4") return { ok: false, owed: true, error: "X's media CDN answered 429", stop: "X's media CDN answered 429 (rate limit)." }; + await writeFile(path.join(dir, `${id}_1.jpg`), `media of ${id}`); + return { ok: false, owed: true, error: `${id}_2.mp4: over the cap: owed until the post is kept`, files: [{ name: `${id}_1.jpg` }] }; + }; + const inp = await input(["1", "2", "3", "4", "5"], { shots: false }); + const res = await captureXPosts(inp, h.deps); + // Three owed posts in a row are not three failures: the run went on to the fourth. + assert.deepEqual(res.outcomes.map((o) => [o.id, o.state, o.files]), [["1", "captured", 1], ["2", "captured", 1], ["3", "captured", 1], ["4", "captured", 0]]); + assert.match(res.stoppedEarly ?? "", /X's media CDN answered 429 \(rate limit\)\. Stopped at 4; the rest are left for a later run\./); + assert.deepEqual(h.downloads, ["1", "2", "3", "4"]); + const record = await readPostCapture(path.join(inp.outDir, "1")); + assert.equal(record?.mediaState, "error"); + assert.deepEqual(record?.media.map((m) => m.name), ["1_1.jpg"]); + assert.match(record?.error ?? "", /owed until the post is kept/); + // Owed again by the next run. + const again = harness({}); + await captureXPosts({ ...inp, ids: ["1"] }, again.deps); + assert.deepEqual(again.downloads, ["1"]); +}); + // --- the real download path, over a fake gallery-dl ------------------------- test("media download: gallery-dl's tagged lines and the files it wrote, nothing from the network", async () => { diff --git a/common/social/xPostCapture.ts b/common/social/xPostCapture.ts @@ -51,6 +51,7 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import type { PageLike } from "./playwrightRuntime"; import type { + PostMediaDownload, PostCaptureInput, PostCaptureOutcome, PostCaptureResult, @@ -348,9 +349,7 @@ export async function shootXPost( return { ...verdict, shot, ...(articleLink ? { articleLink } : {}), ...(thread ? { thread } : {}), ...found }; } -export type MediaDownloadResult = - | { ok: true; files: { name: string; url?: string }[] } - | { ok: false; error: string; needsCookies?: boolean }; +export type MediaDownloadResult = PostMediaDownload; export type XCaptureDeps = { // A page in the logged-in profile. Opened on the first shot, closed at the @@ -525,9 +524,15 @@ export async function captureXPosts( mediaState = media.length > 0 ? "ok" : "none"; state ??= "captured"; } else { + // Not settled: owed again by the next run. The files that did land + // are named all the same. mediaState = "error"; + for (const f of got.files ?? []) media.push(await describeCapturedFile(dir, f.name, f.url)); error = error ? `${error}; ${got.error}` : got.error; - state ??= "error"; + // A post merely owed the rest of its media (a cap, the job's + // budget) did not fail. + state ??= got.owed ? "captured" : "error"; + if (got.stop) stop = got.stop; if (got.needsCookies) { needsCookies = true; stop = "gallery-dl could not log in to X for the media."; diff --git a/common/social/xTrendingMedia.test.ts b/common/social/xTrendingMedia.test.ts @@ -0,0 +1,268 @@ +// The library's CDN media downloader over a stand-in fetch: no socket is +// opened (the harness runs with ARCHILYZER_NO_NETWORK=1 besides). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xTrendingMedia.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createLibraryMediaDownloader, libraryMediaPauseMs, type LibraryMediaDeps, type MediaFetch } from "./xTrendingMedia"; +import { readXTrendingMediaIndex } from "../lib/xTrending/mediaStore"; +import type { PostMediaDownload, PostMediaDownloadArgs } from "./fetchers"; +import type { TrendingMediaSource } from "./xTrendingParse"; + +const TMP = mkdtempSync(path.join(tmpdir(), "x-trending-cdn-")); +after(() => rmSync(TMP, { recursive: true, force: true })); + +const img = (key: string): TrendingMediaSource => ({ + kind: "image", + url: `https://pbs.twimg.com/media/${key}.jpg`, + fetchUrl: `https://pbs.twimg.com/media/${key}?format=jpg&name=orig`, + ext: "jpg", +}); +const vid = (key: string): TrendingMediaSource => ({ + kind: "video", + url: `https://video.twimg.com/ext_tw_video/${key}/vid/high.mp4`, + fetchUrl: `https://video.twimg.com/ext_tw_video/${key}/vid/high.mp4`, + ext: "mp4", +}); + +type Answer = { status?: number; body?: string; length?: number; throws?: string }; + +function harness(name: string, answers: Record<string, Answer>, over: Partial<LibraryMediaDeps> = {}) { + const root = path.join(TMP, name); + const asked: string[] = []; + const pauses: number[] = []; + const state = { cooldown: 0, limited: 0 }; + const fetch: MediaFetch = async (url, init) => { + asked.push(url); + assert.equal(init.redirect, "error"); + assert.equal(init.credentials, "omit"); + const a = answers[url]; + if (!a) return { status: 404, headers: { get: () => null }, body: null }; + if (a.throws) throw new Error(a.throws); + const bytes = Buffer.from(a.body ?? ""); + return { + status: a.status ?? 200, + headers: { get: (h) => (h === "content-length" ? String(a.length ?? bytes.length) : null) }, + body: (async function* () { + // Two chunks, so a cap can fall mid-stream. + yield bytes.subarray(0, Math.ceil(bytes.length / 2)); + yield bytes.subarray(Math.ceil(bytes.length / 2)); + })(), + }; + }; + const deps: LibraryMediaDeps = { + fetch, + pauseMs: () => 1500, + pause: async (ms) => void pauses.push(ms), + cooldownMs: async () => state.cooldown, + noteRateLimit: async () => { + state.limited++; + return Date.parse("2026-11-18T10:15:00Z"); + }, + now: () => Date.parse("2026-11-18T10:00:00Z"), + ...over, + }; + const dirOf = (id: string) => path.join(root, "trending", "posts-media", id); + const args = (id: string): PostMediaDownloadArgs => ({ id, dir: dirOf(id), signal: new AbortController().signal }); + const noLogin = async (): Promise<PostMediaDownload> => { + throw new Error("the logged-in download must not run"); + }; + return { root, asked, pauses, state, deps, dirOf, args, noLogin }; +} + +test("files come from the CDN one after another, 1 to 2 s apart, and each is kept once", async () => { + const h = harness("fetch", { + [img("A").fetchUrl]: { body: "PICTURE-A" }, + [img("B").fetchUrl]: { body: "PICTURE-B" }, + [vid("V").fetchUrl]: { body: "VIDEO-V" }, + // Another address, the same bytes as A. + [img("A2").fetchUrl]: { body: "PICTURE-A" }, + }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([ + ["701", [img("A"), img("B")]], + ["702", [vid("V"), img("A"), img("A2")]], + ]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + assert.deepEqual(await download(h.args("701"), h.noLogin), { + ok: true, + files: [ + { name: "701_1.jpg", url: img("A").url }, + { name: "701_2.jpg", url: img("B").url }, + ], + }); + const second = await download(h.args("702"), h.noLogin); + assert.equal(second.ok, true); + // A's address is known: 702_2.jpg is linked, never asked for again. + assert.deepEqual(h.asked, [img("A").fetchUrl, img("B").fetchUrl, vid("V").fetchUrl, img("A2").fetchUrl]); + // A gap before every fetch but the job's first. + assert.deepEqual(h.pauses, [1500, 1500, 1500]); + const a1 = statSync(path.join(h.dirOf("701"), "701_1.jpg")); + assert.equal(statSync(path.join(h.dirOf("702"), "702_2.jpg")).ino, a1.ino); + // Same bytes from another address: fetched, then one file with A. + assert.equal(statSync(path.join(h.dirOf("702"), "702_3.jpg")).ino, a1.ino); + assert.equal(readFileSync(path.join(h.dirOf("702"), "702_1.mp4"), "utf8"), "VIDEO-V"); + assert.equal(Object.keys((await readXTrendingMediaIndex(h.root)).blobs).length, 3); + // No partial left behind. + assert.deepEqual(readdirSync(h.dirOf("702")).sort(), ["702_1.mp4", "702_2.jpg", "702_3.jpg"]); + // Asked again: everything is on disk, nothing is fetched. + h.asked.length = 0; + assert.equal((await download(h.args("701"), h.noLogin)).ok, true); + assert.deepEqual(h.asked, []); + const gap = libraryMediaPauseMs(() => 0.5); + assert.ok(gap >= 1000 && gap < 2000); +}); + +test("a 429 stops the job and records the cooldown; a 403 or 404 marks the file and nothing retries", async () => { + const h = harness("refused", { + [img("Gone").fetchUrl]: { status: 404 }, + [img("Forbidden").fetchUrl]: { status: 403 }, + [img("Fine").fetchUrl]: { body: "FINE" }, + [img("Limited").fetchUrl]: { status: 429 }, + [img("Never").fetchUrl]: { body: "NEVER" }, + }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([ + ["711", [img("Gone"), img("Forbidden"), img("Fine")]], + ["712", [img("Limited"), img("Never")]], + ]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + const first = await download(h.args("711"), h.noLogin); + assert.equal(first.ok, false); + if (first.ok) return; + assert.match(first.error, /711_1\.jpg: the CDN answered 404; 711_2\.jpg: the CDN answered 403/); + assert.deepEqual(first.files, [{ name: "711_3.jpg", url: img("Fine").url }]); + // A refused file is an error of the post, not something merely owed; and it does not stop the run. + assert.equal(first.owed, undefined); + assert.equal(first.stop, undefined); + // Each address asked exactly once. + assert.deepEqual(h.asked, [img("Gone").fetchUrl, img("Forbidden").fetchUrl, img("Fine").fetchUrl]); + + const limited = await download(h.args("712"), h.noLogin); + assert.equal(limited.ok, false); + if (limited.ok) return; + assert.match(limited.stop ?? "", /answered 429 \(rate limit\) for 712_1\.jpg.*Nothing X starts before 10:15 UTC; nothing retries by itself/); + assert.equal(h.state.limited, 1); + // The file after the 429 was never asked for. + assert.equal(h.asked.includes(img("Never").fetchUrl), false); + assert.equal(existsSync(path.join(h.dirOf("712"), "712_2.jpg")), false); +}); + +test("X's cooldown holds the media: nothing is asked while it runs", async () => { + const h = harness("cooling", { [img("A").fetchUrl]: { body: "A" } }); + h.state.cooldown = 9 * 60_000; + const download = createLibraryMediaDownloader({ channelRoot: h.root, sources: new Map([["721", [img("A")]]]), maxVideoBytes: 100, fallback: "none", deps: h.deps }); + const res = await download(h.args("721"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.match(res.stop ?? "", /no media fetch starts before 10:09 UTC \(9 min from now\)/); + assert.equal(res.owed, true); + assert.deepEqual(h.asked, []); +}); + +test("a file over the cap is owed, by its declared size or mid-stream; a kept post has no cap", async () => { + const answers = { + [vid("Declared").fetchUrl]: { body: "x", length: 5000 }, + [vid("Streamed").fetchUrl]: { body: "0123456789ABCDEF", length: 4 }, + [img("Small").fetchUrl]: { body: "ok" }, + }; + const h = harness("cap", answers); + const sources = new Map([["731", [vid("Declared"), vid("Streamed"), img("Small")]]]); + const watch = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: 10, fallback: "none", deps: h.deps }); + const res = await watch(h.args("731"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.equal(res.owed, true); + assert.match(res.error, /731_1\.mp4: it is .*over the 1 MB cap: owed until the post is kept; 731_2\.mp4: it is over the 1 MB cap: owed until the post is kept/); + assert.deepEqual(res.files, [{ name: "731_3.jpg", url: img("Small").url }]); + assert.deepEqual(readdirSync(h.dirOf("731")), ["731_3.jpg"]); + // Kept: no cap, so the same files come down. + const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, maxVideoBytes: null, fallback: "login", deps: h.deps }); + const again = await kept(h.args("731"), h.noLogin); + assert.equal(again.ok, true); + assert.equal(readFileSync(path.join(h.dirOf("731"), "731_2.mp4"), "utf8"), "0123456789ABCDEF"); +}); + +test("a job's budget: past it the rest is owed and nothing more is asked", async () => { + const h = harness("budget", { + [img("A").fetchUrl]: { body: "AAAA" }, + [img("B").fetchUrl]: { body: "BBBB" }, + [img("C").fetchUrl]: { body: "CCCC" }, + }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([["741", [img("A"), img("B")]], ["742", [img("C"), img("A")]]]), + maxVideoBytes: 100, + fallback: "none", + maxFiles: 2, + deps: h.deps, + }); + assert.equal((await download(h.args("741"), h.noLogin)).ok, true); + const res = await download(h.args("742"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.equal(res.owed, true); + assert.equal(res.stop, undefined); + assert.match(res.error, /742_1\.jpg: owed \(this job's media budget of 2 files/); + // What the library already holds is still linked, budget or not. + assert.deepEqual(res.files, [{ name: "742_2.jpg", url: img("A").url }]); + assert.deepEqual(h.asked, [img("A").fetchUrl, img("B").fetchUrl]); +}); + +test("the logged-in download is the fallback for a kept post only, and what it lands is kept once too", async () => { + const h = harness("fallback", { [img("Fine").fetchUrl]: { body: "FINE" } }); + const sources = new Map([["751", [img("Fine")]]]); + const expected = new Map([["751", 2]]); + // A watch: the file the capture names no address for is owed; no login. + const watch = createLibraryMediaDownloader({ channelRoot: h.root, sources, expected, maxVideoBytes: 100, fallback: "none", deps: h.deps }); + const owed = await watch(h.args("751"), h.noLogin); + assert.equal(owed.ok, false); + if (owed.ok) return; + assert.equal(owed.owed, true); + assert.match(owed.error, /1 of its 2 media file\(s\) have no CDN address in the saved capture: owed until the post is kept/); + // Kept: the fetcher's own download runs once, and its file joins the store. + let logins = 0; + const { writeFileSync } = await import("node:fs"); + const kept = createLibraryMediaDownloader({ channelRoot: h.root, sources, expected, maxVideoBytes: null, fallback: "login", deps: h.deps }); + const res = await kept(h.args("751"), async ({ dir }) => { + logins++; + writeFileSync(path.join(dir, "751_2.mp4"), "VIA-LOGIN"); + return { ok: true, files: [{ name: "751_1.jpg" }, { name: "751_2.mp4", url: "https://video.twimg.com/x/v.mp4" }] }; + }); + assert.equal(logins, 1); + assert.equal(res.ok, true); + const index = await readXTrendingMediaIndex(h.root); + const blobs = Object.values(index.blobs); + assert.equal(blobs.length, 2); + assert.ok(blobs.some((b) => b.urls.includes("https://video.twimg.com/x/v.mp4") && b.posts["751"]?.includes("751_2.mp4"))); +}); + +test("an address off X's media CDN is never asked; a fetch that throws marks the file", async () => { + const h = harness("hosts", { "https://pbs.twimg.com/media/T?format=jpg&name=orig": { throws: "socket hang up" } }); + const download = createLibraryMediaDownloader({ + channelRoot: h.root, + sources: new Map([ + ["761", [{ kind: "image", url: "https://example.test/a.jpg", fetchUrl: "https://example.test/a.jpg", ext: "jpg" }, img("T")]], + ]), + maxVideoBytes: 100, + fallback: "none", + deps: h.deps, + }); + const res = await download(h.args("761"), h.noLogin); + assert.equal(res.ok, false); + if (res.ok) return; + assert.match(res.error, /761_1\.jpg: not an address on X's media CDN; 761_2\.jpg: the CDN did not answer \(socket hang up\)/); + assert.deepEqual(h.asked, ["https://pbs.twimg.com/media/T?format=jpg&name=orig"]); +}); diff --git a/common/social/xTrendingMedia.ts b/common/social/xTrendingMedia.ts @@ -0,0 +1,296 @@ +// A LIBRARY POST'S MEDIA, FROM X'S MEDIA CDN (lane x-trending-2) — the media +// half of `capture-posts` for an X trending library (controller/ +// capturePosts.ts hands it to the X fetcher as `downloadMedia`). +// +// An ordinary X capture runs one LOGGED-IN gallery-dl per post. A library +// already holds the answer that listed the post — the saved capture of the +// read that showed it — and that answer names where the CDN serves each +// file (xTrendingParse.ts mediaSourcesOf). So the files are asked of the CDN +// directly: no login, no page, no request to X's API. +// +// IT RIDES THE CAPTURE JOB, on X's queue (`platform:twitter`): one job at a +// time with every read and capture, X's gap between jobs, the X alert and the +// fresh-jar rule at the job's start. Inside the job: +// - X's cooldown is asked before every post: a 429 anywhere on X (a read's, +// a capture's) holds the media too; +// - one file after another, 1 to 2 s apart (the gap an article's inline +// images use), never two at once; +// - a job fetches at most `maxFiles` files or `maxBytes` (40, 200 MB): the +// rest is OWED — its posts' media is not settled, and the next capture of +// them asks again; +// - a file over `maxVideoBytes` is not kept and is owed (a watch: 100 MB by +// default; a kept post has no cap); +// - a 429 from the CDN STOPS THE JOB and records the 15-minute cooldown; a +// 403, a 404 or any other answer marks that file and moves on. NOTHING IS +// RETRIED. +// +// A FILE THE LIBRARY ALREADY HOLDS IS NOT FETCHED: one whose address the media +// index knows is linked from the store (lib/xTrending/mediaStore.ts), and one +// already in the post's directory is kept. Every file fetched is taken into +// the store, so the same bytes under two posts are one file. +// +// THE LOGGED-IN FALLBACK (`fallback: "login"`, a post marked keep) runs the +// fetcher's own gallery-dl download for a post the CDN could not serve whole — +// no address in the capture, or a file refused — and takes what it lands into +// the store too. A watch never falls back. +// +// Only X's two media hosts are ever asked (xTrendingParse.ts xMediaCdnUrl), a +// redirect is refused, and no cookie or header of the session is sent. + +// ARCHILYZER_NO_NETWORK=1 (lib/noNetwork.mjs): imported for its effect. +import "../lib/noNetwork.mjs"; +import { createWriteStream } from "node:fs"; +import { mkdir, rename, rm, stat } from "node:fs/promises"; +import path from "node:path"; +import { once } from "node:events"; +import { + adoptXTrendingMedia, + linkXTrendingMedia, + readXTrendingMediaIndex, + xTrendingBlobByUrl, +} from "../lib/xTrending/mediaStore"; +import { xRateLimitHoldSentence } from "../lib/xTrending/config"; +import type { PostMediaDownload, PostMediaDownloadArgs } from "./fetchers"; +import { listCapturedMediaFiles } from "./postCapture"; +import { xMediaCdnUrl, type TrendingMediaSource } from "./xTrendingParse"; + +export const LIBRARY_MEDIA_MAX_FILES = 40; +export const LIBRARY_MEDIA_MAX_BYTES = 200 * 1024 * 1024; +// No file is ever kept past this, cap or no cap. +export const LIBRARY_MEDIA_HARD_MAX_BYTES = 2 * 1024 * 1024 * 1024; +export const LIBRARY_MEDIA_HEADERS_TIMEOUT_MS = 60_000; +export const LIBRARY_MEDIA_FILE_TIMEOUT_MS = 10 * 60_000; + +// The gap between two files: 1 to 2 s. +export function libraryMediaPauseMs(rand: () => number = Math.random): number { + return 1000 + Math.floor(rand() * 1000); +} + +// The slice of `fetch` this needs (the global one in production; a stand-in +// that opens no socket in tests and under the e2e test server). +export type MediaFetch = ( + url: string, + init: { signal: AbortSignal; redirect: "error"; credentials: "omit" }, +) => Promise<{ + status: number; + headers: { get: (name: string) => string | null }; + body: AsyncIterable<Uint8Array> | null; +}>; + +export type LibraryMediaDeps = { + fetch: MediaFetch; + pauseMs: () => number; + pause: (ms: number, signal: AbortSignal) => Promise<void>; + // X's cooldown: how long is left of it (ms), and a rate limit recorded + // (answers when it ends, ms since the epoch). + cooldownMs: () => Promise<number>; + noteRateLimit: () => Promise<number>; + now?: () => number; +}; + +export type LibraryMediaOptions = { + // The library's channel directory (channels/<lib>). + channelRoot: string; + // Post id → where the CDN serves its media, from the saved captures. + sources: ReadonlyMap<string, ReadonlyArray<TrendingMediaSource>>; + // Post id → how many media files the post carries (the read's count): a post + // whose capture names fewer addresses than that is owed the rest. + expected?: ReadonlyMap<string, number>; + // A file over this is owed, not kept. null: no cap (a kept post). + maxVideoBytes: number | null; + fallback: "login" | "none"; + maxFiles?: number; + maxBytes?: number; + deps: LibraryMediaDeps; +}; + +const mb = (bytes: number) => `${Math.max(1, Math.round(bytes / (1024 * 1024)))} MB`; +const firstLine = (err: unknown) => ((err as Error)?.message ?? String(err)).split("\n")[0]; + +type Fetched = { ok: true; bytes: number } | { ok: false; why: string; owed?: boolean; rateLimited?: boolean }; + +// One file, streamed to `<name>.part` and renamed when whole. +async function fetchOne(o: { + source: TrendingMediaSource; + file: string; + cap: number; + capIsHard: boolean; + fetch: MediaFetch; + signal: AbortSignal; +}): Promise<Fetched> { + const part = `${o.file}.part`; + const over = (bytes: number): Fetched => + o.capIsHard + ? { ok: false, why: `it is larger than ${mb(o.cap)}, more than is ever kept` } + : { ok: false, owed: true, why: `it is ${bytes > 0 ? `${mb(bytes)}, ` : ""}over the ${mb(o.cap)} cap: owed until the post is kept` }; + const deadline = AbortSignal.any([o.signal, AbortSignal.timeout(LIBRARY_MEDIA_FILE_TIMEOUT_MS)]); + let res: Awaited<ReturnType<MediaFetch>>; + try { + res = await o.fetch(o.source.fetchUrl, { + signal: AbortSignal.any([deadline, AbortSignal.timeout(LIBRARY_MEDIA_HEADERS_TIMEOUT_MS)]), + redirect: "error", + credentials: "omit", + }); + } catch (err) { + return { ok: false, why: `the CDN did not answer (${firstLine(err)})` }; + } + if (res.status === 429) return { ok: false, rateLimited: true, why: "the CDN answered 429 (rate limit)" }; + if (res.status < 200 || res.status >= 300 || !res.body) { + return { ok: false, why: `the CDN answered ${res.status}` }; + } + const declared = Number(res.headers.get("content-length") ?? ""); + if (Number.isFinite(declared) && declared > o.cap) return over(declared); + await rm(part, { force: true }); + const out = createWriteStream(part); + let bytes = 0; + let tooBig = false; + try { + for await (const chunk of res.body) { + if (deadline.aborted) throw new Error(o.signal.aborted ? "cancelled" : "the file took too long"); + bytes += chunk.byteLength; + if (bytes > o.cap) { + tooBig = true; + break; + } + if (!out.write(chunk)) await once(out, "drain"); + } + } catch (err) { + out.destroy(); + await rm(part, { force: true }); + return { ok: false, why: `the download broke off (${firstLine(err)})` }; + } + await new Promise<void>((resolve, reject) => out.end((err?: Error | null) => (err ? reject(err) : resolve()))); + if (tooBig) { + await rm(part, { force: true }); + return over(0); + } + if (bytes === 0) { + await rm(part, { force: true }); + return { ok: false, why: "the CDN sent an empty file" }; + } + await rename(part, o.file); + return { ok: true, bytes }; +} + +// The media half of a library's capture: `(args, login) => result`, one call +// per post, sharing one job's budget. +export function createLibraryMediaDownloader( + o: LibraryMediaOptions, +): (args: PostMediaDownloadArgs, login: (args: PostMediaDownloadArgs) => Promise<PostMediaDownload>) => Promise<PostMediaDownload> { + const { deps } = o; + const now = deps.now ?? Date.now; + const maxFiles = o.maxFiles ?? LIBRARY_MEDIA_MAX_FILES; + const maxBytes = o.maxBytes ?? LIBRARY_MEDIA_MAX_BYTES; + const cap = Math.min(o.maxVideoBytes ?? LIBRARY_MEDIA_HARD_MAX_BYTES, LIBRARY_MEDIA_HARD_MAX_BYTES); + const capIsHard = o.maxVideoBytes === null || o.maxVideoBytes >= LIBRARY_MEDIA_HARD_MAX_BYTES; + const budget = { files: 0, bytes: 0 }; + let saidSpent = false; + + return async (args, login) => { + const { id, dir, signal } = args; + const log = args.onLog ?? (() => {}); + // X cooling down after a rate limit holds the media too. + const cooling = await deps.cooldownMs().catch(() => 0); + if (cooling > 0) { + const why = xRateLimitHoldSentence("media fetch", cooling, now()); + return { ok: false, owed: true, error: why, stop: why }; + } + const sources = o.sources.get(id) ?? []; + const expected = o.expected?.get(id) ?? sources.length; + const files: { name: string; url?: string }[] = []; + const problems: string[] = []; + let owed = false; + let failed = false; + let stop: string | undefined; + await mkdir(dir, { recursive: true }); + // Taken into the store; a file the store cannot share stays where it is. + const adopt = async (name: string, url?: string) => { + const got = await adoptXTrendingMedia(o.channelRoot, { postId: id, name, ...(url ? { url } : {}), now }); + if (got.deduped) log(`${id}: ${name} is a file the library already holds (kept once).`); + }; + + for (const [i, source] of sources.entries()) { + if (signal.aborted) break; + const name = `${id}_${i + 1}.${source.ext}`; + const file = path.join(dir, name); + if (!xMediaCdnUrl(source.fetchUrl)) { + problems.push(`${name}: not an address on X's media CDN`); + failed = true; + continue; + } + if ((await stat(file).catch(() => null))?.isFile()) { + await adopt(name, source.url); + files.push({ name, url: source.url }); + continue; + } + // An address the library has seen: linked from the store, nothing asked. + const known = xTrendingBlobByUrl(await readXTrendingMediaIndex(o.channelRoot), source.url); + if (known && (await linkXTrendingMedia(o.channelRoot, { postId: id, name, sha256: known, url: source.url }))) { + log(`${id}: ${name} is already in the library (same address): linked, not fetched.`); + files.push({ name, url: source.url }); + continue; + } + if (budget.files >= maxFiles || budget.bytes >= maxBytes) { + owed = true; + problems.push(`${name}: owed (this job's media budget of ${maxFiles} files / ${mb(maxBytes)} is used)`); + if (!saidSpent) { + saidSpent = true; + log(`This job's media budget (${maxFiles} files / ${mb(maxBytes)}) is used: the rest is owed to a later capture.`); + } + continue; + } + if (budget.files > 0) await deps.pause(deps.pauseMs(), signal); + if (signal.aborted) break; + const got = await fetchOne({ source, file, cap, capIsHard, fetch: deps.fetch, signal }); + budget.files++; + if (got.ok) { + budget.bytes += got.bytes; + await adopt(name, source.url); + files.push({ name, url: source.url }); + continue; + } + if (got.rateLimited) { + const until = await deps.noteRateLimit().catch(() => now() + 15 * 60_000); + stop = + `X's media CDN answered 429 (rate limit) for ${name}: the capture stopped at once and asked nothing more. ` + + `Nothing X starts before ${new Date(until).toISOString().slice(11, 16)} UTC; nothing retries by itself.`; + problems.push(`${name}: ${got.why}`); + owed = true; + break; + } + problems.push(`${name}: ${got.why}`); + if (got.owed) owed = true; + else failed = true; + } + if (signal.aborted && !stop) { + return { ok: false, owed: true, error: "cancelled", files }; + } + if (sources.length < expected && !stop) { + problems.push( + `${expected - sources.length} of its ${expected} media file(s) have no CDN address in the saved capture` + + (o.fallback === "login" ? "" : ": owed until the post is kept"), + ); + if (o.fallback === "login") failed = true; + else owed = true; + } + // A kept post the CDN could not serve whole: the fetcher's own logged-in + // download, once, and what it lands is taken into the store. + if (failed && !stop && o.fallback === "login") { + log(`${id}: ${problems.join("; ")} — falling back to the logged-in download.`); + const viaLogin = await login(args); + for (const name of await listCapturedMediaFiles(dir)) { + const url = viaLogin.ok ? viaLogin.files.find((f) => f.name === name)?.url : undefined; + await adopt(name, url ?? files.find((f) => f.name === name)?.url); + } + return viaLogin; + } + if (problems.length === 0) return { ok: true, files }; + return { + ok: false, + error: problems.join("; "), + files, + ...(owed && !failed ? { owed: true } : {}), + ...(stop ? { stop } : {}), + }; + }; +} diff --git a/common/social/xTrendingParse.test.ts b/common/social/xTrendingParse.test.ts @@ -114,3 +114,58 @@ test("an answer that failed, or whose body was not kept, yields nothing", () => assert.equal(parseTrendingCapture([line({})], "t").posts.length, 3); assert.equal(parseTrendingCapture([line({ body: { data: {} } })], "t").posts.length, 0); }); + +// Lane x-trending-2: where the CDN serves a post's media, read from the answer. +test("media sources: a picture at its original size, a video's highest-bitrate mp4, X's two hosts only", async () => { + const { mediaSourcesOf, mediaSourcesInCapture, xMediaCdnUrl } = await import("./xTrendingParse"); + const { fixtureTweetResult } = await import("./__fixtures__/xTrendingCapture"); + const { collectTimelineTweets } = await import("./xTrendingParse"); + const raw = (t: Parameters<typeof fixtureTweetResult>[0]) => collectTimelineTweets({ result: fixtureTweetResult(t) })[0]; + assert.deepEqual(mediaSourcesOf(raw({ id: "1900000000000002001", handle: "a", text: "t", media: ["photo", "video", "animated_gif"] })), [ + { + kind: "image", + url: "https://pbs.twimg.com/media/Fixture20010.jpg", + fetchUrl: "https://pbs.twimg.com/media/Fixture20010?format=jpg&name=orig", + ext: "jpg", + }, + { + kind: "video", + url: "https://video.twimg.com/ext_tw_video/19000000000000020011/vid/1280x720/high.mp4", + fetchUrl: "https://video.twimg.com/ext_tw_video/19000000000000020011/vid/1280x720/high.mp4", + ext: "mp4", + bitrate: 2176000, + }, + { + kind: "gif", + url: "https://video.twimg.com/ext_tw_video/19000000000000020012/vid/1280x720/high.mp4", + fetchUrl: "https://video.twimg.com/ext_tw_video/19000000000000020012/vid/1280x720/high.mp4", + ext: "mp4", + bitrate: 2176000, + }, + ]); + assert.deepEqual(mediaSourcesOf(raw({ id: "1900000000000002002", handle: "a", text: "no media" })), []); + // An address on another host, or not https, is no media source. + const elsewhere = { + id_str: "1", + full_text: "t", + extended_entities: { + media: [ + { type: "photo", media_url_https: "https://pbs.twimg.com.example.test/media/x.jpg" }, + { type: "photo", media_url_https: "http://pbs.twimg.com/media/x.jpg" }, + { type: "photo", media_url_https: "https://user:pw@pbs.twimg.com/media/x.jpg" }, + { type: "video", video_info: { variants: [{ content_type: "video/mp4", bitrate: 1, url: "https://example.test/v.mp4" }] } }, + { type: "video", video_info: { variants: [{ content_type: "application/x-mpegURL", url: "https://video.twimg.com/x/pl/list.m3u8" }] } }, + { type: "constructor", media_url_https: "https://pbs.twimg.com/media/y.jpg" }, + ], + }, + }; + assert.deepEqual(mediaSourcesOf(elsewhere as never), []); + assert.equal(xMediaCdnUrl("https://video.twimg.com/a.mp4")?.hostname, "video.twimg.com"); + assert.equal(xMediaCdnUrl("https://pbs.twimg.com:8443/a.jpg"), null); + assert.equal(xMediaCdnUrl(42), null); + // A capture's sources by post id: ignored operations and failed answers give none. + const body = { data: { list: [fixtureTweetResult({ id: "1900000000000002003", handle: "a", text: "t", media: ["photo"] })] } }; + const line = (op: string, status: number) => ({ n: 1, at: "x", op, status, url: "u", bytes: 1, body }); + assert.deepEqual([...mediaSourcesInCapture([line("ExampleTrendTimeline", 200)]).keys()], ["1900000000000002003"]); + assert.equal(mediaSourcesInCapture([line("HomeTimeline", 200), line("ExampleTrendTimeline", 500)]).size, 0); +}); diff --git a/common/social/xTrendingParse.ts b/common/social/xTrendingParse.ts @@ -143,6 +143,101 @@ export function mediaSummaryOf(raw: XTweetRaw): TrendingMediaSummary | undefined return { count: media.length, kinds: [...kinds].sort() }; } +// ONE MEDIA FILE OF A POST, AS THE ANSWER NAMES IT (lane x-trending-2): where +// X's media CDN serves it. Nothing is fetched here; a capture job fetches +// `fetchUrl` later, with no login (lib/xTrending/mediaStore.ts keeps it once). +// +// url the address as the answer gives it: the file's identity, what +// the library's media index remembers it by +// fetchUrl what is asked of the CDN: a picture at its original size +// (`?format=<ext>&name=orig`), a video's highest-bitrate +// progressive mp4 +// +// ONLY X's two media hosts, over https, are ever named: an address anywhere +// else in an answer is not a media source (a capture is other people's data, +// and nothing in it may point a fetch at another host). +export type TrendingMediaSource = { + kind: TrendingMediaKind; + url: string; + fetchUrl: string; + ext: string; + bitrate?: number; +}; + +export const X_MEDIA_CDN_HOSTS: readonly string[] = ["pbs.twimg.com", "video.twimg.com"]; + +// An https address on one of X's media hosts, or null. +export function xMediaCdnUrl(v: unknown): URL | null { + if (typeof v !== "string") return null; + let u: URL; + try { + u = new URL(v); + } catch { + return null; + } + if (u.protocol !== "https:" || u.username || u.password || u.port) return null; + return X_MEDIA_CDN_HOSTS.includes(u.hostname) ? u : null; +} + +const IMAGE_EXT = /\.(jpe?g|png|webp)$/i; + +// A post's media files, in the order the post carries them. A file the answer +// names no usable address for (a video with no progressive mp4, an address on +// another host) is left out: the count in mediaSummaryOf still says it exists. +export function mediaSourcesOf(raw: XTweetRaw): TrendingMediaSource[] { + const media = obj(raw.extended_entities)?.media ?? obj(raw.entities)?.media; + if (!Array.isArray(media)) return []; + const out: TrendingMediaSource[] = []; + for (const item of media) { + const m = obj(item); + if (!m) continue; + const type = String(m.type ?? ""); + if (!Object.hasOwn(MEDIA_KIND, type)) continue; + const kind = MEDIA_KIND[type]; + if (kind === "image") { + const u = xMediaCdnUrl(m.media_url_https); + const ext = u ? IMAGE_EXT.exec(u.pathname)?.[1].toLowerCase() : undefined; + if (!u || !ext || u.hostname !== "pbs.twimg.com") continue; + const base = `${u.origin}${u.pathname.replace(IMAGE_EXT, "")}`; + out.push({ kind, url: `${u.origin}${u.pathname}`, fetchUrl: `${base}?format=${ext === "jpeg" ? "jpg" : ext}&name=orig`, ext: ext === "jpeg" ? "jpg" : ext }); + continue; + } + // A video or an animated GIF: the progressive mp4 with the highest bitrate. + const variants = obj(m.video_info)?.variants; + let best: { u: URL; bitrate: number } | undefined; + for (const v of Array.isArray(variants) ? variants : []) { + const variant = obj(v); + if (!variant || variant.content_type !== "video/mp4") continue; + const u = xMediaCdnUrl(variant.url); + if (!u || u.hostname !== "video.twimg.com" || !/\.mp4$/i.test(u.pathname)) continue; + const bitrate = typeof variant.bitrate === "number" && Number.isFinite(variant.bitrate) ? variant.bitrate : 0; + if (!best || bitrate > best.bitrate) best = { u, bitrate }; + } + if (!best) continue; + const url = `${best.u.origin}${best.u.pathname}`; + out.push({ kind, url, fetchUrl: url, ext: "mp4", ...(best.bitrate ? { bitrate: best.bitrate } : {}) }); + } + return out; +} + +// Every post's media sources in a saved capture, by post id (the first answer +// that names a post's media wins). For the capture job: it reads the reads +// that showed the posts it was asked for. +export function mediaSourcesInCapture(lines: ReadonlyArray<TrendingCaptureLine>): Map<string, TrendingMediaSource[]> { + const out = new Map<string, TrendingMediaSource[]>(); + for (const line of lines) { + if (line.body === undefined || X_TRENDING_IGNORED_OPS.includes(line.op)) continue; + if (line.status < 200 || line.status >= 300) continue; + for (const raw of collectTimelineTweets(line.body)) { + const id = xIdOf(raw); + if (!id || out.has(id)) continue; + const sources = mediaSourcesOf(raw); + if (sources.length > 0) out.set(id, sources); + } + } + return out; +} + export type TrendingOperation = { op: string; responses: number; bytes: number; statuses: number[]; tweets: number }; export type ParsedTrendingCapture = {