// videoDir-server — the disk half of ./videoDirId.mjs: which `data//` a // record's id lives in ON THIS DISK (release 23 F1, the Twitch join, option // (b)). Plain JS for umtool's bare-node scripts; server-only (node:fs). It // never computes a path from the cwd: every root arrives as an argument. import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs"; import { open, readdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; import { channelConfigPlatform, pickVideoDirId, twitchVodDirId } from "./videoDirId.mjs"; // ---- Rumble's two ids (lane one-clock) ----------------------------------------- // // A Rumble video has two ids (AGENTS.md). yt-dlp's `id` — what the archive // serves, what every report and manifest cites — is the EMBED id (`v7drc5w`); // a channel downloaded from its page URLs names the DIRECTORY for the URL slug // (`v7fxp3e`, from https://rumble.com/v7fxp3e-title.html). An embed id has no // directory, so every fetch asked by it went to a `data//` that did not // exist: no saved video found, no metadata, the URL guessed as the embed page // (a 403 on 6 Nov), the persist "unknown". So on a RUMBLE channel an id with // no directory of its own is looked up in the channel's metadata: the // directory whose metadata.info.json `id` is that id. The index is built once // per process from the head of each file (yt-dlp writes `id` first) and grows // by the directories it has not read when `data/` changes; an id it does not // know stays as it is. const RUMBLE_ID_RE = /^v[0-9a-z]{4,9}$/; const HEAD_BYTES = 512; const ID_IN_HEAD_RE = /"id"\s*:\s*"([^"]+)"/; /** @type {Map, byId: Map }>} */ const rumbleIndexes = new Map(); /** @param {string} head @returns {string | null} */ function idOfHead(head) { const m = ID_IN_HEAD_RE.exec(head); return m ? m[1] : null; } /** @param {string} file */ async function readHead(file) { let fh; try { fh = await open(file, "r"); const buf = Buffer.alloc(HEAD_BYTES); const { bytesRead } = await fh.read(buf, 0, HEAD_BYTES, 0); return buf.subarray(0, bytesRead).toString("utf8"); } catch { return ""; } finally { await fh?.close().catch(() => {}); } } /** @param {string} file */ function readHeadSync(file) { let fd = -1; try { fd = openSync(file, "r"); const buf = Buffer.alloc(HEAD_BYTES); const n = readSync(fd, buf, 0, HEAD_BYTES, 0); return buf.subarray(0, n).toString("utf8"); } catch { return ""; } finally { if (fd >= 0) closeSync(fd); } } /** * The directory of a Rumble channel holding the record `id` (its embed id), or * null when no directory's metadata names it. * @param {string} dataDir * @param {string} id * @returns {Promise} */ export async function rumbleDirIdByMetadata(dataDir, id) { let st; try { st = await stat(dataDir); } catch { return null; } let idx = rumbleIndexes.get(dataDir); if (!idx) { idx = { mtimeMs: -1, seen: new Set(), byId: new Map() }; rumbleIndexes.set(dataDir, idx); } if (idx.mtimeMs !== st.mtimeMs) { const names = await readdir(dataDir).catch(() => /** @type {string[]} */ ([])); for (const name of names) { if (idx.seen.has(name)) continue; idx.seen.add(name); const metaId = idOfHead(await readHead(path.join(/* turbopackIgnore: true */ dataDir, name, "metadata.info.json"))); if (metaId && metaId !== name && !idx.byId.has(metaId)) idx.byId.set(metaId, name); } idx.mtimeMs = st.mtimeMs; } return idx.byId.get(id) ?? null; } /** * `rumbleDirIdByMetadata`, synchronously. * @param {string} dataDir * @param {string} id * @returns {string | null} */ export function rumbleDirIdByMetadataSync(dataDir, id) { let st; try { st = statSync(dataDir); } catch { return null; } let idx = rumbleIndexes.get(dataDir); if (!idx) { idx = { mtimeMs: -1, seen: new Set(), byId: new Map() }; rumbleIndexes.set(dataDir, idx); } if (idx.mtimeMs !== st.mtimeMs) { let names = /** @type {string[]} */ ([]); try { names = readdirSync(dataDir); } catch {} for (const name of names) { if (idx.seen.has(name)) continue; idx.seen.add(name); const metaId = idOfHead(readHeadSync(path.join(/* turbopackIgnore: true */ dataDir, name, "metadata.info.json"))); if (metaId && metaId !== name && !idx.byId.has(metaId)) idx.byId.set(metaId, name); } idx.mtimeMs = st.mtimeMs; } return idx.byId.get(id) ?? null; } /** @param {string} p */ async function isDir(p) { try { return (await stat(p)).isDirectory(); } catch { return false; } } /** * A channel's platform, read from its config.json; null when unreadable. * @param {string} channelsDir * @param {string} slug * @returns {Promise} */ export async function readChannelPlatform(channelsDir, slug) { try { const raw = JSON.parse( await readFile(path.join(/* turbopackIgnore: true */ channelsDir, slug, "config.json"), "utf8"), ); return channelConfigPlatform(raw); } catch { return null; } } /** * The directory id a record lives in, on this disk. Only a `v` id * (Twitch) or a Rumble-shaped `v<5-10 of a-z0-9>` id costs a read (the * channel's config when no platform is given, then stats; a Rumble embed id * with no directory, the channel's metadata index); every other id is returned * as it is. * @param {string} channelsDir * @param {string} slug * @param {string} recordId * @param {{ platform?: string | null }} [opts] the record's (or channel's) * platform, when the caller already knows it. * @returns {Promise} */ export async function resolveVideoDirId(channelsDir, slug, recordId, opts = {}) { const rumbleShaped = RUMBLE_ID_RE.test(recordId); if (twitchVodDirId(recordId) === null && !rumbleShaped) return recordId; const platform = opts.platform !== undefined ? opts.platform : await readChannelPlatform(channelsDir, slug); if (platform === "rumble" && rumbleShaped) { const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); if (await isDir(path.join(/* turbopackIgnore: true */ dataDir, recordId))) return recordId; return (await rumbleDirIdByMetadata(dataDir, recordId)) ?? recordId; } if (platform !== "twitch" || twitchVodDirId(recordId) === null) return recordId; const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); const n = /** @type {string} */ (twitchVodDirId(recordId)); const [hasN, hasV] = await Promise.all([ isDir(path.join(/* turbopackIgnore: true */ dataDir, n)), isDir(path.join(/* turbopackIgnore: true */ dataDir, recordId)), ]); return pickVideoDirId(recordId, { platform, exists: (id) => (id === n ? hasN : id === recordId ? hasV : false), }); } /** * THE OTHER WAY ROUND: the id the ARCHIVE serves a recording under, from the * directory it lives in on this disk (`resolveVideoDirId`'s inverse, for * Rumble). On a Rumble channel a directory named for the URL slug holds a * record whose id -- its metadata.info.json `id`, the EMBED id the archive * keys by -- is another: that id is returned (a QR, a share line, an inserted * clip's `siteVideo` must name it; 4 and 8 Nov the QR named the folder id). * Every other directory, and a Rumble one whose metadata names itself or * nothing, is its own id. Only a Rumble-shaped id costs a read. * @param {string} channelsDir * @param {string} slug * @param {string} dirId * @param {{ platform?: string | null }} [opts] * @returns {Promise} */ export async function recordIdOfVideoDir(channelsDir, slug, dirId, opts = {}) { if (!RUMBLE_ID_RE.test(dirId)) return dirId; const platform = opts.platform !== undefined ? opts.platform : await readChannelPlatform(channelsDir, slug); if (platform !== "rumble") return dirId; const id = idOfHead(await readHead(path.join(/* turbopackIgnore: true */ channelsDir, slug, "data", dirId, "metadata.info.json"))); return id && RUMBLE_ID_RE.test(id) ? id : dirId; } /** * The directory a record lives in: `//data/`. * @param {string} channelsDir * @param {string} slug * @param {string} recordId * @param {{ platform?: string | null }} [opts] * @returns {Promise} */ export async function resolveVideoDir(channelsDir, slug, recordId, opts = {}) { const dirId = await resolveVideoDirId(channelsDir, slug, recordId, opts); return path.join(/* turbopackIgnore: true */ channelsDir, slug, "data", dirId); } // ---- the same, synchronously ------------------------------------------------ // For a caller that is synchronous and shared too widely to turn async // (umtool's cuePathFor). The rule is pickVideoDirId's; only a `v` id // costs a read. /** @param {string} p */ function isDirSync(p) { try { return statSync(p).isDirectory(); } catch { return false; } } /** * `resolveVideoDirId`, synchronously. * @param {string} channelsDir * @param {string} slug * @param {string} recordId * @param {{ platform?: string | null }} [opts] * @returns {string} */ export function resolveVideoDirIdSync(channelsDir, slug, recordId, opts = {}) { const rumbleShaped = RUMBLE_ID_RE.test(recordId); if (twitchVodDirId(recordId) === null && !rumbleShaped) return recordId; let platform = opts.platform; if (platform === undefined) { try { platform = channelConfigPlatform( JSON.parse(readFileSync(path.join(/* turbopackIgnore: true */ channelsDir, slug, "config.json"), "utf8")), ); } catch { platform = null; } } if (platform === "rumble" && rumbleShaped) { const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); if (isDirSync(path.join(/* turbopackIgnore: true */ dataDir, recordId))) return recordId; return rumbleDirIdByMetadataSync(dataDir, recordId) ?? recordId; } if (platform !== "twitch" || twitchVodDirId(recordId) === null) return recordId; const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); return pickVideoDirId(recordId, { platform, exists: (id) => isDirSync(path.join(/* turbopackIgnore: true */ dataDir, id)), }); } /** * `resolveVideoDir`, synchronously. * @param {string} channelsDir * @param {string} slug * @param {string} recordId * @param {{ platform?: string | null }} [opts] * @returns {string} */ export function resolveVideoDirSync(channelsDir, slug, recordId, opts = {}) { return path.join( /* turbopackIgnore: true */ channelsDir, slug, "data", resolveVideoDirIdSync(channelsDir, slug, recordId, opts), ); }