Archilyzer · Source

archilyzer

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

commit 6792f35e4e715e1e22cdada4f9e6f6ea4d614413
parent d552cdf5a37db583e1ed19da678af50d5280548c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 19:39:57 -0400

editor: fetch-windows takes "storedUrl" (never | fallback | only) — a held or cooling platform's group still starts a job with its windows whose record stores a trusted media URL and refuses only the rest (storedUrlDoor), the dry run counts them per group (storedUrlItems), a Retry keeps the mode; the route validates it; ops help + COMMANDS.md

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/fetchWindows.ts | 19+++++++++++++++++++
Mcommon/controller/fetchWindowsStoredUrl.test.ts | 10+++++++++-
Meditor/app/api/ops/fetch-windows/route.test.ts | 9+++++++++
Meditor/app/api/ops/fetch-windows/route.ts | 31+++++++++++++++++++++++++++----
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Aeditor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 3+++
Mscripts/archilyzer-ops.mjs | 7+++++++
9 files changed, 259 insertions(+), 20 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -137,7 +137,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` | | `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. | | | `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. | `pnpm ops persist-videos --file list.json --wait` | -| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | +| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` | | `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[&lt;version&gt;\] - &lt;date&gt;": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release &lt;workspace&gt; &lt;version&gt;") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` | | `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` | | `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` | diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -283,6 +283,25 @@ const DEFAULT_DEPS: FetchWindowsDeps = { storedMediaUrl, }; +// THE DOOR FOR A GROUP whose platform is held or cooling down (release 32 R5): +// with a storedUrl mode, its items that have a stored media URL still run (they +// ask no page; the controller cuts them from the stored URL), and only the rest +// are refused. No refusal: everything runs. `never`: the whole group is +// refused, as before. +export function storedUrlDoor<T>( + items: readonly T[], + refusal: string | null, + mode: StoredUrlMode, + hasStored: (item: T) => boolean, +): { run: T[]; refused: T[] } { + if (!refusal) return { run: [...items], refused: [] }; + if (mode === "never") return { run: [], refused: [...items] }; + return { + run: items.filter((i) => hasStored(i)), + refused: items.filter((i) => !hasStored(i)), + }; +} + export function fetchWindowsItemLabel(item: FetchWindowsItem): string { const span = `${item.from.toFixed(2)}–${item.to.toFixed(2)}`; return `${item.slug}/${item.id} ${span}${item.clipId ? ` (${item.clipId})` : ""}`; diff --git a/common/controller/fetchWindowsStoredUrl.test.ts b/common/controller/fetchWindowsStoredUrl.test.ts @@ -11,7 +11,7 @@ import assert from "node:assert/strict"; import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { fetchWindows, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows"; +import { fetchWindows, storedUrlDoor, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows"; import { parseClipProvenance } from "../lib/clipWindow"; import { detectPlatform } from "../lib/platform"; import type { StoredUrlMode } from "../lib/storedMediaUrl"; @@ -311,3 +311,11 @@ test("a find-copy item (another recording's URL) never uses the stored URL", asy await go(paths, [{ ...item("j1", "o", copyUrl), copy: { from: "archive.org", url: copyUrl } }], h, "only"); assert.deepEqual((await since(m)).targets, [copyUrl]); }); + +test("the editor's door: no refusal runs all; never refuses all; a mode runs only the stored-URL items", () => { + const has = (n: number) => n % 2 === 0; + assert.deepEqual(storedUrlDoor([1, 2, 3, 4], null, "never", has), { run: [1, 2, 3, 4], refused: [] }); + assert.deepEqual(storedUrlDoor([1, 2, 3, 4], "held", "never", has), { run: [], refused: [1, 2, 3, 4] }); + assert.deepEqual(storedUrlDoor([1, 2, 3, 4], "held", "only", has), { run: [2, 4], refused: [1, 3] }); + assert.deepEqual(storedUrlDoor([1, 3], "held", "fallback", has), { run: [], refused: [1, 3] }); +}); diff --git a/editor/app/api/ops/fetch-windows/route.test.ts b/editor/app/api/ops/fetch-windows/route.test.ts @@ -79,6 +79,8 @@ test("an item list is validated at the door", async () => { [{ items: [item({ extra: 1 })], requestedBy: "t" }, /items\[0\]" has unknown key\(s\): extra/], [{ items: [item()] }, /"requestedBy" is required/], [{ items: [item()], requestedBy: "t", maxHeight: 50 }, /"maxHeight" must be a whole number of pixels/], + [{ items: [item()], requestedBy: "t", storedUrl: "always" }, /"storedUrl" must be one of "never", "fallback", "only"/], + [{ items: [item()], requestedBy: "t", storedUrl: true }, /"storedUrl" must be one of/], ]; for (const [body, re] of cases) { const r = await post(body); @@ -185,3 +187,10 @@ test("a window a queued job will already write is answered in inFlight with that reg.forceRelease("HOLDER"); } }); + +test("storedUrl is accepted and a YouTube group is not asked about it (only Odysee is allowlisted)", async () => { + const r = await post({ requestedBy: "test", dryRun: true, storedUrl: "fallback", items: [item({ from: 100, to: 110 })] }); + assert.equal(r.status, 200); + const j = r.json as { groups: { platform: string; storedUrlItems?: number }[] }; + assert.deepEqual(j.groups.map((g) => [g.platform, g.storedUrlItems]), [["youtube", undefined]]); +}); diff --git a/editor/app/api/ops/fetch-windows/route.ts b/editor/app/api/ops/fetch-windows/route.ts @@ -6,6 +6,11 @@ import { isFetchMaxHeight, } from "yt-dlp-transcript-common/lib/clipWindow"; import { isValidSiteId } from "yt-dlp-transcript-common/lib/site"; +import { + STORED_URL_MODES, + isStoredUrlMode, + type StoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows"; import { fetchMissingEvidenceAction, @@ -25,9 +30,9 @@ import { export const dynamic = "force-dynamic"; -// POST { siteId, maxHeight?, dryRun? } +// POST { siteId, maxHeight?, storedUrl?, dryRun? } // | { items: [{ slug, id, from, to, clipId?, reason?, pad?, webpageUrl?, force? }, …], -// requestedBy, manifest?, maxHeight?, dryRun? } +// requestedBy, manifest?, maxHeight?, storedUrl?, dryRun? } // dryRun -> { ok, dryRun: true, groups: [{ platform, queueKey, items }], // cached, inFlight, unresolved[, onDisk, unfetchable] } // else -> { ok, dryRun: false, jobs: [{ platform, queueKey, jobId, items }], @@ -48,6 +53,13 @@ export const dynamic = "force-dynamic"; // refused (unresolved) unless the item names a `webpageUrl` (a copy: find-copy) // or `"force": true` (the reading is stale — or check its availability again). // +// `storedUrl` (release 32 R5): "never" (the default) | "fallback" | "only". With +// "fallback" a window whose page lookup answers a rate limit is cut from the +// media URL its record's metadata.info.json stores — an allowlisted platform's +// CDN file (Odysee's odycdn) — and "only" asks no page at all. Either way a held +// or cooling platform's group still runs its windows that have one; the rest are +// refused. The dry run's group says how many have one (`storedUrlItems`). +// // A big list goes in a file: `pnpm ops fetch-windows --file list.json`. const ITEM_KEYS = ["slug", "id", "from", "to", "clipId", "reason", "pad", "webpageUrl", "force"]; @@ -120,6 +132,15 @@ function reqWindowItems(body: OpsBody): FetchWindowsItem[] { }); } +function optStoredUrl(body: OpsBody): StoredUrlMode | undefined { + const v = body.storedUrl; + if (v === undefined || v === null) return undefined; + if (!isStoredUrlMode(v)) { + throw new OpsInputError(`"storedUrl" must be one of ${STORED_URL_MODES.map((m) => `"${m}"`).join(", ")}`); + } + return v; +} + function optMaxHeight(body: OpsBody): number | undefined { const v = body.maxHeight; if (v === undefined || v === null) return undefined; @@ -135,9 +156,10 @@ function optMaxHeight(body: OpsBody): number | undefined { export async function POST(request: Request) { return ops( request, - ["siteId", "items", "requestedBy", "manifest", "maxHeight", "dryRun"], + ["siteId", "items", "requestedBy", "manifest", "maxHeight", "storedUrl", "dryRun"], async (body) => { const maxHeight = optMaxHeight(body); + const storedUrl = optStoredUrl(body); const dryRun = optBool(body, "dryRun"); if (body.siteId !== undefined && body.items !== undefined) { throw new OpsInputError('send either "siteId" or "items", not both'); @@ -156,7 +178,7 @@ export async function POST(request: Request) { `"${siteId}" is not a valid site id (lowercase letters, digits and "-"; must start with a letter or digit)`, ); } - result = await fetchMissingEvidenceAction(siteId, { dryRun, maxHeight }); + result = await fetchMissingEvidenceAction(siteId, { dryRun, maxHeight, storedUrl }); } else if (body.items !== undefined) { const items = reqWindowItems(body); // WHO ASKED IS NOT OPTIONAL, as on the single route: a window nobody @@ -167,6 +189,7 @@ export async function POST(request: Request) { requestedBy, manifest: optString(body, "manifest")?.trim() || undefined, maxHeight, + storedUrl, dryRun, }); } else { diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -33,9 +33,15 @@ import { fetchWindows, fetchWindowsItemLabel, dedupeFetchWindowsItems, + storedUrlDoor, type FetchWindowsItem, } from "yt-dlp-transcript-common/controller/fetchWindows"; import { + isStoredUrlPlatform, + type StoredUrlMode, +} from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server"; +import { missingEvidenceWindows, type UnfetchableEvidenceWindow, } from "yt-dlp-transcript-common/publish/reportMedia"; @@ -77,6 +83,12 @@ import { safeRevalidate } from "../../../lib/safeRevalidate"; // media guard's sentence, never sent to the network; one whose container ends // before the window is fetched as before. // +// WITH `storedUrl` "fallback" OR "only" (release 32 R5, lib/storedMediaUrl.ts), +// a held or cooling group is not refused whole: its windows whose record stores +// a trusted media URL (Odysee's CDN file) still start a job on the same queue — +// they ask no page — and only the rest are refused. The default, "never", +// changes nothing. +// // Like the single fetch, NOT GATED BY THE DOWNLOAD PAUSE: an operator (or a // tool they are driving) asked for these seconds by hand. @@ -92,6 +104,8 @@ export type FetchWindowsRequest = { dryRun?: boolean; // A queue override for every group (resolveQueueKey's rules). queueKey?: string; + // Cut from the stored media URL: "never" (default) | "fallback" | "only". + storedUrl?: StoredUrlMode; }; export type FetchWindowsUnresolved = { item: FetchWindowsItem; error: string }; @@ -103,6 +117,8 @@ export type FetchWindowsGroup = { platform: string; queueKey: string; items: FetchWindowsItem[]; + // With a storedUrl mode: how many of `items` have a stored media URL. + storedUrlItems?: number; }; export type FetchWindowsActionResult = @@ -151,11 +167,14 @@ async function planFetchWindows( items: FetchWindowsItem[], queueOverride: string | undefined, maxHeight: number | undefined, + storedMode: StoredUrlMode, ): Promise<{ groups: FetchWindowsGroup[]; cached: FetchWindowsItem[]; inFlight: FetchWindowsInFlight[]; unresolved: FetchWindowsUnresolved[]; + // The planned items (as grouped) whose record stores a trusted media URL. + stored: Set<FetchWindowsItem>; }> { const paths = getPaths(); const configs = new Map<string, ChannelConfig | null>(); @@ -163,6 +182,7 @@ async function planFetchWindows( const cached: FetchWindowsItem[] = []; const inFlight: FetchWindowsInFlight[] = []; const unresolved: FetchWindowsUnresolved[] = []; + const stored = new Set<FetchWindowsItem>(); const live = getRegistry().list(); for (const item of dedupeFetchWindowsItems(items)) { const problem = itemProblem(item); @@ -261,11 +281,19 @@ async function planFetchWindows( const platform = detectPlatform(url) ?? "unknown"; // One job per queue. Two platforms sharing a queue (an override) share a // job too; the controller keys the cooldown per item, so each is honoured. - const group = groups.get(queueKey) ?? { platform, queueKey, items: [] }; - group.items.push({ ...item, webpageUrl: url }); + const group: FetchWindowsGroup = groups.get(queueKey) ?? { platform, queueKey, items: [] }; + const planned = { ...item, webpageUrl: url }; + group.items.push(planned); + // The controller's rule (controller/fetchWindows.ts): an allowlisted + // platform's own page, never a copy, and a stored URL of that platform. + if (storedMode !== "never" && !item.copy && isStoredUrlPlatform(platform)) { + const s = await storedMediaUrl(videoDir); + if (s && s.platform === platform) stored.add(planned); + group.storedUrlItems = (group.storedUrlItems ?? 0) + (stored.has(planned) ? 1 : 0); + } groups.set(queueKey, group); } - return { groups: [...groups.values()], cached, inFlight, unresolved }; + return { groups: [...groups.values()], cached, inFlight, unresolved, stored }; } // The door each group passes before its job is queued: the platform's hold, @@ -296,6 +324,7 @@ export async function fetchWindowsJobAction(req: { siteId?: string; maxHeight?: number; queueKey: string; + storedUrl?: StoredUrlMode; }): Promise<StreamActionResult> { if (req.items.length === 0) return { ok: false, error: "No windows to fetch." }; if (req.maxHeight !== undefined && !isFetchMaxHeight(req.maxHeight)) { @@ -330,6 +359,8 @@ export async function fetchWindowsJobAction(req: { ...(req.manifest ? { manifest: req.manifest } : {}), ...(req.siteId ? { siteId: req.siteId } : {}), ...(req.maxHeight !== undefined ? { maxHeight: req.maxHeight } : {}), + // A Retry keeps the mode it was asked with. + ...(req.storedUrl && req.storedUrl !== "never" ? { storedUrl: req.storedUrl } : {}), }, }, fn: async (onLog, signal, setProgress, ctx) => { @@ -342,6 +373,7 @@ export async function fetchWindowsJobAction(req: { requestedAt, }, maxHeight: req.maxHeight, + storedUrl: req.storedUrl, onLog, signal, drainSignal: ctx.drainSignal, @@ -380,10 +412,12 @@ export async function fetchWindowsAction( error: `maxHeight ${req.maxHeight} is not a source height to cap a fetch at.`, }; } - const { groups, cached, inFlight, unresolved } = await planFetchWindows( + const storedMode = req.storedUrl ?? "never"; + const { groups, cached, inFlight, unresolved, stored } = await planFetchWindows( req.items, req.queueKey, req.maxHeight, + storedMode, ); const base = { groups, cached, inFlight, unresolved, jobs: [], refused: [] }; if (req.dryRun) return { ok: true, dryRun: true, ...base }; @@ -410,26 +444,36 @@ export async function fetchWindowsAction( const refused: { platform: string; error: string; items: number }[] = []; for (const g of groups) { const refusal = await groupRefusal(g.platform); - if (refusal) { - refused.push({ platform: g.platform, error: refusal, items: g.items.length }); - continue; + const door = storedUrlDoor(g.items, refusal, storedMode, (i) => stored.has(i)); + if (door.refused.length > 0) { + refused.push({ + platform: g.platform, + error: + door.run.length > 0 + ? `${refusal} (${door.refused.length} window(s) with no stored media URL; ` + + `${door.run.length} cut from the stored URL)` + : refusal!, + items: door.refused.length, + }); } + if (door.run.length === 0) continue; let res: StreamActionResult; try { res = await fetchWindowsJobAction({ - items: g.items, + items: door.run, requestedBy, manifest: req.manifest, siteId: req.siteId, maxHeight: req.maxHeight, queueKey: g.queueKey, + storedUrl: storedMode, }); } catch (e) { - refused.push({ platform: g.platform, error: (e as Error).message, items: g.items.length }); + refused.push({ platform: g.platform, error: (e as Error).message, items: door.run.length }); continue; } if (!res.ok) { - refused.push({ platform: g.platform, error: res.error, items: g.items.length }); + refused.push({ platform: g.platform, error: res.error, items: door.run.length }); continue; } // Nobody reads the stream: the job's log is on disk. @@ -438,7 +482,7 @@ export async function fetchWindowsAction( platform: g.platform, queueKey: g.queueKey, jobId: res.jobId, - items: g.items.length, + items: door.run.length, }); } if (jobs.length === 0 && refused.length > 0) { @@ -465,7 +509,7 @@ export type FetchMissingEvidenceResult = // {"siteId": …}` both run. export async function fetchMissingEvidenceAction( siteId: string, - opts: { dryRun?: boolean; maxHeight?: number } = {}, + opts: { dryRun?: boolean; maxHeight?: number; storedUrl?: StoredUrlMode } = {}, ): Promise<FetchMissingEvidenceResult> { const id = siteId.trim(); if (!isValidSiteId(id)) return { ok: false, error: `"${id}" is not a valid site id` }; @@ -477,7 +521,7 @@ export async function fetchMissingEvidenceAction( // The same for the ARTICLES (release 26: transcripts/reports/, every // published article): the Articles tab's "Fetch missing evidence". export async function fetchMissingArticleEvidenceAction( - opts: { dryRun?: boolean; maxHeight?: number } = {}, + opts: { dryRun?: boolean; maxHeight?: number; storedUrl?: StoredUrlMode } = {}, ): Promise<FetchMissingEvidenceResult> { const paths = getPaths(); let host; @@ -492,7 +536,7 @@ export async function fetchMissingArticleEvidenceAction( async function fetchMissingFor( need: Awaited<ReturnType<typeof missingEvidenceWindows>>, id: string, - opts: { dryRun?: boolean; maxHeight?: number; siteId?: string }, + opts: { dryRun?: boolean; maxHeight?: number; siteId?: string; storedUrl?: StoredUrlMode }, ): Promise<FetchMissingEvidenceResult> { const extra = { siteId: id, onDisk: need.onDisk, unfetchable: need.unfetchable }; if (need.missing.length === 0) { @@ -522,6 +566,7 @@ async function fetchMissingFor( ...(opts.siteId ? { siteId: opts.siteId } : {}), maxHeight: opts.maxHeight, dryRun: opts.dryRun, + ...(opts.storedUrl ? { storedUrl: opts.storedUrl } : {}), }); if (!r.ok) return r; return { ...r, ...extra }; diff --git a/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts b/editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts @@ -0,0 +1,125 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/channels/*/videos/fetchWindowsStoredUrl.test.ts" +// +// The batch's door with `storedUrl` (release 32 R5): Odysee is in a rate-limit +// cooldown throughout. "never" refuses its group whole, as before; "only" starts +// a job with the window whose record stores a CDN URL and refuses the one +// without; the job cuts it from that URL. yt-dlp and ffmpeg are fakes (YTDLP_BIN, +// FFMPEG_BIN): an odysee.com target answers 429, anything else is written. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-windows-stored-")); +const SLUG = "demo-odysee"; +const ARGS_LOG = path.join(ROOT, "argv.jsonl"); +const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); +await writeFile( + YTDLP, + `#!/usr/bin/env node +import { appendFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify(args) + "\\n"); +const url = args[args.length - 1]; +if (url.startsWith("https://odysee.com/")) { process.stderr.write("ERROR: [lbry] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n"); process.exit(1); } +writeFileSync(args[args.indexOf("-o") + 1], "mp4"); +`, +); +await writeFile(FFMPEG, "#!/usr/bin/env node\nprocess.exit(0);\n"); +await chmod(YTDLP, 0o755); +await chmod(FFMPEG, 0o755); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.YTDLP_BIN = YTDLP; +process.env.FFMPEG_BIN = FFMPEG; +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); +await writeFile( + path.join(ROOT, "channels", SLUG, "config.json"), + JSON.stringify({ name: "Demo", handling: "youtube", url: "https://odysee.com/@demo", platform: "odysee" }), +); +const page = (id: string) => `https://odysee.com/@demo:1/stream-${id}:${id}`; +const cdn = (id: string) => `https://player.odycdn.com/v6/streams/${id}/f0.mp4`; +async function video(id: string, withStored: boolean): Promise<string> { + const dir = path.join(ROOT, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ + id, + webpage_url: page(id), + ...(withStored ? { formats: [{ format_id: "original", url: cdn(id), protocol: "https", ext: "mp4" }] } : {}), + }), + ); + return dir; +} +const STORED = await video("s1", true); +await video("n1", false); + +const { fetchWindowsAction } = await import("./fetchWindowsAction"); +const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); +const { recordDownloadBackoff } = await import("yt-dlp-transcript-common/jobs/downloadBackoff"); +const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); +await recordDownloadBackoff("odysee", getPaths()); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const items = [ + { slug: SLUG, id: "s1", from: 1, to: 3, clipId: "r#1" }, + { slug: SLUG, id: "n1", from: 1, to: 3, clipId: "r#2" }, +]; +const targets = async () => + (await readFile(ARGS_LOG, "utf8").catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + .map((l) => (JSON.parse(l) as string[]).at(-1)); + +test("a dry run says how many of a group's windows have a stored media URL", async () => { + const r = await fetchWindowsAction({ items, requestedBy: "test", dryRun: true, storedUrl: "only" }); + assert.ok(r.ok); + if (!r.ok) return; + assert.deepEqual( + r.groups.map((g) => [g.platform, g.queueKey, g.items.length, g.storedUrlItems]), + [["odysee", "clips:odysee", 2, 1]], + ); + const plain = await fetchWindowsAction({ items, requestedBy: "test", dryRun: true }); + assert.ok(plain.ok); + if (!plain.ok) return; + assert.equal(plain.groups[0].storedUrlItems, undefined, "never: not even asked"); +}); + +test("never (the default): the cooling platform's group is refused whole", async () => { + const r = await fetchWindowsAction({ items, requestedBy: "test" }); + assert.ok(!r.ok); + if (r.ok) return; + assert.match(r.error, /^odysee: odysee is in a rate-limit cooldown/); + assert.deepEqual(await targets(), []); +}); + +test("only: the window with a stored URL runs on clips:odysee and is cut from it; the other is refused", async () => { + const r = await fetchWindowsAction({ items, requestedBy: "test", manifest: "m", storedUrl: "only" }); + assert.ok(r.ok, JSON.stringify(r)); + if (!r.ok) return; + assert.deepEqual(r.jobs.map((j) => [j.platform, j.queueKey, j.items]), [["odysee", "clips:odysee", 1]]); + assert.equal(r.refused.length, 1); + assert.equal(r.refused[0].items, 1); + assert.match(r.refused[0].error, /cooldown.*\(1 window\(s\) with no stored media URL; 1 cut from the stored URL\)/); + const jobId = r.jobs[0].jobId; + const reg = getRegistry(); + for (let i = 0; i < 200; i++) { + const s = reg.get(jobId)?.status; + if (s !== "queued" && s !== "running") break; + await new Promise((res) => setTimeout(res, 50)); + } + assert.equal(reg.get(jobId)?.status, "done", `job ${jobId}: ${reg.get(jobId)?.status}`); + assert.equal(reg.get(jobId)?.spec?.params?.storedUrl, "only", "a Retry keeps the mode"); + assert.deepEqual(await targets(), [cdn("s1")], "no page request"); + const sidecar = JSON.parse(await readFile(path.join(STORED, "clips", "1.00-3.00.json"), "utf8")); + assert.equal(sidecar.source, "stored-media-url"); + assert.equal(sidecar.sourceHost, "player.odycdn.com"); + assert.equal(sidecar.manifest, "m"); +}); diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -9,6 +9,7 @@ // so it is never bundled to the client. import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow"; +import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot"; import type { JobSpec, ReplayBucket } from "yt-dlp-transcript-common/jobs/jobSpec"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; @@ -229,6 +230,8 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { siteId: str(p.siteId), maxHeight: num(p.maxHeight), queueKey, + // Release 32 R5: a replay keeps the stored-URL mode it was asked with. + ...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}), }); }, // Both digest lanes replay through one action; the lane comes from params so a diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1219,6 +1219,13 @@ export function usage() { ' "inFlight" with that job, whose id joins "jobIds" (so --wait follows it)', ' and no second job is queued. Windows run on the platform\'s clip queue', ' (clips:youtube), never behind its long downloads.', + ' "storedUrl": "fallback" | "only" (default "never") cuts a window from the', + " media URL its record's metadata.info.json stores — Odysee's CDN file", + ' (*.odycdn.com), the only platform allowed — when the page lookup is', + ' rate-limited ("fallback": after a 429) or without asking the page at all', + ' ("only"). A held or cooling platform still runs its windows that have', + ' one; the rest are refused or left for a later run. Same queue, same gaps;', + ' the window\'s provenance says source "stored-media-url".', "", '"preview": "<branch>" on deploy-site or build-deploy makes it a Cloudflare', " Pages PREVIEW instead of production: the same bundle goes to a branch",