Archilyzer · Source

archilyzer

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

commit ce175222b293d7fc4e2175ab746b3b17252741cb
parent dff3fcffe4971302ad2153f60f6941e416481bc5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 19:41:37 -0400

Merge r32/stored-url: fetch-windows storedUrl never|fallback|only — a clip window cut from the media URL the record already stores (Odysee's CDN only) when the platform's lookup is rate-limited; a held platform's windows with a stored URL still run, on the same queue and pacing, the audio check keyed on the page

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

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/fetchWindows.ts | 340+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------
Acommon/controller/fetchWindowsStoredUrl.test.ts | 321+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/clipWindow.ts | 14++++++++++----
Acommon/lib/storedMediaUrl-server.ts | 16++++++++++++++++
Acommon/lib/storedMediaUrl.test.ts | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/storedMediaUrl.ts | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/fetchWindowManaged.ts | 33++++++++++++++++++++++++++++++---
Meditor/CHANGELOG.md | 1+
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+++
Mplans/FACTS.md | 30++++++++++++++++++++++++++++++
Aplans/release-32/stored-url.md | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 7+++++++
17 files changed, 1143 insertions(+), 112 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 @@ -40,6 +40,13 @@ import { platformMinGapSeconds, staticSleepRequestsSeconds, } from "../ytdlp/platformArgs.mjs"; +import { + isStoredUrlPlatform, + type StoredMediaUrl, + type StoredUrlMode, + type StoredUrlWhy, +} from "../lib/storedMediaUrl"; +import { storedMediaUrl } from "../lib/storedMediaUrl-server"; import { readChannelConfig } from "./channels"; import { findVideoSourceUrl } from "./undownloadedVideos"; @@ -83,6 +90,19 @@ import { findVideoSourceUrl } from "./undownloadedVideos"; // RESUMABLE BY RE-RUNNING, as persistVideos: nothing is remembered between // runs, and a re-run's cache check skips every window the last one fetched. // +// THE STORED MEDIA URL (release 32 R5, opt-in per request: `storedUrl`, +// lib/storedMediaUrl.ts). `never` (the default) is everything above, unchanged. +// `fallback`: an item whose page lookup answers rate_limit is cut from the media +// URL its metadata.info.json stores (an allowlisted platform's CDN — Odysee's +// odycdn), after the gap. `only`: such an item goes straight to the stored URL, +// no page or API request. Either way a HELD or cooling platform, or one that +// rate-limited earlier in the run, does not stop its stored-URL items — they do +// not touch the limited endpoint — while its items without one are left +// `notAttempted` (and the run reports the stop). The backoff is still recorded +// (the lookup IS limited); a stored-URL success never records the platform +// clean; a 429 from the stored URL itself stops the run as any 429 does. Same +// queue, same gaps. +// // A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's per-channel text // guard has no channel to ask. It is asked here instead, once per channel: an // item on a channel whose text is not readable fails as `unreachable` (its @@ -170,8 +190,12 @@ export type FetchWindowsResult = { // Cut from the video's saved container, not fetched (release 21 D2). cut: FetchWindowsItem[]; failed: FetchWindowsFailure[]; - // Due a fetch but not attempted because the run stopped first. + // Due a fetch but not attempted because the run stopped first (or, with a + // storedUrl mode, because the platform's lookup was limited and the item has + // no stored media URL). notAttempted: FetchWindowsItem[]; + // Of `fetched`: the ones fetched from the stored media URL (release 32 R5). + storedUrl: FetchWindowsItem[]; stopped?: FetchWindowsStop; }; @@ -214,8 +238,13 @@ export type FetchWindowsDeps = { noteGap: (key: string, gapMs: number) => void; // A find-copy copy whose fetch failed (lib/copyAttempts-server.ts). recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise<void>; + // The record's stored media URL (lib/storedMediaUrl-server.ts). + storedMediaUrl: (videoDir: string) => Promise<StoredMediaUrl | null>; }; +// Why a platform's page is not asked again in this run. +type PageLimit = { stop: "held" | "cooldown" | "rate-limit"; text: string }; + function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> { if (ms <= 0 || signal?.aborted) return Promise.resolve(); return new Promise((resolve) => { @@ -251,8 +280,28 @@ const DEFAULT_DEPS: FetchWindowsDeps = { gapRemainingMs: (key) => platformGapRemainingMs(key), noteGap: (key, gapMs) => notePlatformGap(key, gapMs), recordFailedCopy, + 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})` : ""}`; @@ -280,6 +329,7 @@ export async function fetchWindows({ provenance, maxHeight, gapMs, + storedUrl: storedMode = "never", onLog, signal, drainSignal, @@ -293,6 +343,8 @@ export async function fetchWindows({ // The pause between two network fetches. Absent = the platform's batch gap, // floored at CLIP_WINDOW_MIN_GAP_SECONDS. gapMs?: number; + // Cut from the stored media URL: never (default) | fallback | only (above). + storedUrl?: StoredUrlMode; onLog?: (line: string) => void; signal?: AbortSignal; drainSignal?: AbortSignal; @@ -313,6 +365,7 @@ export async function fetchWindows({ cut: [], failed: [], notAttempted: [], + storedUrl: [], }; log( `Fetch windows: ${work.length} window(s) for ${provenance.requestedBy}` + @@ -356,6 +409,29 @@ export async function fetchWindows({ result.stopped = why; result.notAttempted.push(...work.slice(from)); }; + // Platforms whose page lookup this run will not ask again (stored modes). + const limited = new Map<string, PageLimit>(); + // The platform's hold, then its cooldown — the sentences the batch has + // always stopped with. + const pageLimit = async (platform: string): Promise<PageLimit | null> => { + const held = await deps.heldRefusal(platform, paths); + if (held) return { stop: "held", text: held }; + const cooldownMs = await deps.cooldownRemainingMs(platform, paths); + if (cooldownMs > 0) { + return { + stop: "cooldown", + text: `${platform} is in a rate-limit cooldown (${Math.ceil(cooldownMs / 1000)}s remaining)`, + }; + } + return null; + }; + // An item left for a later run because its platform's lookup is limited and + // it has no stored media URL; the run goes on to the next. + const skip = (item: FetchWindowsItem, label: string, lim: PageLimit) => { + result.notAttempted.push(item); + result.stopped ??= lim.stop; + log(` ${label}: not attempted — ${lim.text}, and it has no stored media URL.`); + }; const interrupted = (): FetchWindowsStop | null => signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null; @@ -483,8 +559,36 @@ export async function fetchWindows({ }, ); const gapKey = `clip-window:${platform}`; + + // THE STORED MEDIA URL (release 32 R5, lib/storedMediaUrl.ts): asked only + // when the request opted in, for an allowlisted platform whose page this + // item is, and never for a copy (find-copy's URL is another recording). + const stored = + storedMode !== "never" && !item.copy && isStoredUrlPlatform(platform) + ? await deps.storedMediaUrl(videoDir).then( + (s) => (s && s.platform === platform ? s : null), + () => null, + ) + : null; + // Set when the page is NOT asked: `only`, or the platform's lookup is + // limited (held, cooling down, rate-limited earlier in this run). + let via: StoredUrlWhy | null = stored && storedMode === "only" ? "only" : null; + const viaFor = (lim: PageLimit): StoredUrlWhy => (lim.stop === "held" ? "held" : "rate-limited"); + if (!via && storedMode !== "never") { + const lim = limited.get(platform) ?? (await pageLimit(platform)); + if (lim) { + limited.set(platform, lim); + if (stored) via = viaFor(lim); + else { + skip(item, label, lim); + continue; + } + } + } + // Between this run's own fetches, the gap; before its first, whatever is - // left of the gap the last run on this platform set. + // left of the gap the last run on this platform set. A fetch from the + // stored URL is paced like any other: one stream, real gaps. const wait = networkAttempts > 0 ? gap : deps.gapRemainingMs(gapKey); if (wait > 0) { log( @@ -500,106 +604,170 @@ export async function fetchWindows({ } } - // ASKED BEFORE EVERY NETWORK FETCH: another job (or the lane) may have - // backed this platform off while this one slept. - const held = await deps.heldRefusal(platform, paths); - if (held) { - log(` ${label}: ${held} — stopping; the rest are left for a later run.`); - stop("held", i); - break; + // ASKED BEFORE EVERY PAGE FETCH: another job (or the lane) may have backed + // this platform off while this one slept. A stored-URL fetch does not ask + // the page, so the hold does not stop it. + if (!via) { + const lim = await pageLimit(platform); + if (lim) { + if (storedMode === "never") { + log(` ${label}: ${lim.text} — stopping; the rest are left for a later run.`); + stop(lim.stop, i); + break; + } + limited.set(platform, lim); + if (stored) via = viaFor(lim); + else { + skip(item, label, lim); + continue; + } + } } - const cooldownMs = await deps.cooldownRemainingMs(platform, paths); - if (cooldownMs > 0) { + + const attempt = async ( + target: (StoredMediaUrl & { why: StoredUrlWhy }) | null, + ): Promise<{ ok: true; r: FetchWindowResult } | { ok: false; e: unknown }> => { + networkAttempts += 1; + try { + const r = await deps.fetchWindow({ + channelSlug: item.slug, + channelConfig: config, + paths, + videoDir, + videoId: dirId, + videoUrl: url, + ...(target ? { storedMedia: target } : {}), + cwd: path.join(paths.channelsDir, item.slug), + from: item.from, + to: item.to, + provenance: { + requestedBy: provenance.requestedBy, + manifest: provenance.manifest, + clipId: item.clipId, + reason: item.reason, + pad: item.pad, + requestedAt, + ...(item.copy ? { copy: item.copy } : {}), + }, + cookiePolicy: resolveCookiePolicy(settings, config), + maxHeight, + onLog: fetchLog, + signal: fetchSignal, + onPlatformBackoff: () => deps.recordBackoff(platform, paths, "rate_limit"), + }); + return { ok: true, r }; + } catch (e) { + return { ok: false, e }; + } finally { + // Settled, refused or not: the next fetch on this platform, in this + // run or the next one, starts no sooner than the gap from now. + deps.noteGap(gapKey, gap); + } + }; + const classOf = (e: unknown): FetchWindowsFailureClass => + e instanceof FetchWindowError ? e.failureClass : "unknown"; + + log( + via && stored + ? ` ${label}: fetching from the stored media URL (${stored.host})…` + : ` ${label}: fetching…`, + ); + let usedStored = via !== null; + let out = await attempt(via && stored ? { ...stored, why: via } : null); + + // FALLBACK: the page lookup rate-limited this item (fetchWindowManaged + // recorded the platform's backoff before it threw), and the record stores + // its media URL — cut from that, after the gap. + if (!out.ok && !usedStored && stored && storedMode === "fallback" && classOf(out.e) === "rate_limit") { + limited.set(platform, { stop: "rate-limit", text: `${platform} rate-limited this run` }); log( - ` ${label}: ${platform} is in a rate-limit cooldown ` + - `(${Math.ceil(cooldownMs / 1000)}s remaining) — stopping; the rest are ` + - `left for a later run.`, + ` ${label}: ${platform} rate-limited the page lookup — cutting from the stored ` + + `media URL (${stored.host}) instead.`, ); - stop("cooldown", i); - break; + if (gap > 0) { + log(`Sleeping ${Math.round(gap / 1000)}s before the next fetch...`); + await deps.sleep(gap, signal); + } + const after = interrupted(); + if (after) { + fail(item, "rate_limit", (out.e as Error).message); + done += 1; + progress(); + stop(after, i + 1); + break; + } + usedStored = true; + out = await attempt({ ...stored, why: "rate-limited" }); } - log(` ${label}: fetching…`); - networkAttempts += 1; - try { - const r = await deps.fetchWindow({ - channelSlug: item.slug, - channelConfig: config, - paths, - videoDir, - videoId: dirId, - videoUrl: url, - cwd: path.join(paths.channelsDir, item.slug), - from: item.from, - to: item.to, - provenance: { - requestedBy: provenance.requestedBy, - manifest: provenance.manifest, - clipId: item.clipId, - reason: item.reason, - pad: item.pad, - requestedAt, - ...(item.copy ? { copy: item.copy } : {}), - }, - cookiePolicy: resolveCookiePolicy(settings, config), - maxHeight, - onLog: fetchLog, - signal: fetchSignal, - onPlatformBackoff: () => deps.recordBackoff(platform, paths, "rate_limit"), - }); + if (out.ok) { networkStreak = 0; - (r.cached ? result.cached : result.fetched).push(item); - const clean = await deps.recordClean(platform, paths).catch(() => null); - if (clean) log(clean); - } catch (e) { - const message = (e as Error).message; - const cls: FetchWindowsFailureClass = - e instanceof FetchWindowError ? e.failureClass : "unknown"; - fail(item, cls, message); - // A COPY THAT FAILED AT ITS SOURCE (find-copy's, release 29 review) is - // recorded beside the recording, so the next find-copy falls through to - // another copy. Only a source-side failure (isSourceSideCopyFailure): a - // rate limit, a cancel, our own selector or ffmpeg say nothing about it. - if (item.copy && cls !== "rate_limit" && !fetchSignal.aborted && isSourceSideCopyFailure(cls, message)) { - await deps - .recordFailedCopy(videoDir, { ...item.copy, at: new Date().toISOString(), error: message }) - .catch(() => {}); - log(` ${label}: the ${item.copy.from} copy failed — find-copy will not pick it again.`); + (out.r.cached ? result.cached : result.fetched).push(item); + if (usedStored && !out.r.cached) result.storedUrl.push(item); + // A FETCH FROM THE STORED URL SAYS NOTHING ABOUT THE LOOKUP, which is + // what the backoff is about: only a page fetch records the platform + // clean. + if (!usedStored) { + const clean = await deps.recordClean(platform, paths).catch(() => null); + if (clean) log(clean); } done += 1; progress(); - if (cls === "rate_limit") { - // fetchWindowManaged recorded the backoff before it threw. - log(` ${platform} rate-limited this run — stopping; the rest are left for a later run.`); - stop("rate-limit", i + 1); - break; - } - if (cls === "network") { - networkStreak += 1; - if (networkStreak >= 2) { - await deps.recordBackoff(platform, paths, "network").catch(() => {}); - log( - ` ${platform} refused ${networkStreak} fetches in a row — backing it ` + - `off and stopping; the rest are left for a later run.`, - ); - stop("network", i + 1); - break; - } - } else { - networkStreak = 0; - } continue; - } finally { - // Settled, refused or not: the next fetch on this platform, in this run - // or the next one, starts no sooner than the gap from now. - deps.noteGap(gapKey, gap); + } + + const e = out.e; + const message = (e as Error).message; + const cls = classOf(e); + fail(item, cls, message); + // A COPY THAT FAILED AT ITS SOURCE (find-copy's, release 29 review) is + // recorded beside the recording, so the next find-copy falls through to + // another copy. Only a source-side failure (isSourceSideCopyFailure): a + // rate limit, a cancel, our own selector or ffmpeg say nothing about it. + if (item.copy && cls !== "rate_limit" && !fetchSignal.aborted && isSourceSideCopyFailure(cls, message)) { + await deps + .recordFailedCopy(videoDir, { ...item.copy, at: new Date().toISOString(), error: message }) + .catch(() => {}); + log(` ${label}: the ${item.copy.from} copy failed — find-copy will not pick it again.`); } done += 1; progress(); + if (cls === "rate_limit") { + if (storedMode !== "never" && !usedStored) { + // The LOOKUP is limited (the backoff is recorded); this run's windows + // with a stored media URL do not touch it and go on. + limited.set(platform, { stop: "rate-limit", text: `${platform} rate-limited this run` }); + log( + ` ${platform} rate-limited this run — its windows with a stored media URL go on; ` + + `the rest are left for a later run.`, + ); + continue; + } + // fetchWindowManaged recorded the backoff before it threw. + log(` ${platform} rate-limited this run — stopping; the rest are left for a later run.`); + stop("rate-limit", i + 1); + break; + } + if (cls === "network") { + networkStreak += 1; + if (networkStreak >= 2) { + await deps.recordBackoff(platform, paths, "network").catch(() => {}); + log( + ` ${platform} refused ${networkStreak} fetches in a row — backing it ` + + `off and stopping; the rest are left for a later run.`, + ); + stop("network", i + 1); + break; + } + } else { + networkStreak = 0; + } } log( - `Fetch windows: ${result.fetched.length} fetched, ` + + `Fetch windows: ${result.fetched.length} fetched` + + (result.storedUrl.length ? ` (${result.storedUrl.length} from stored media URLs)` : "") + + ", " + (result.cut.length ? `${result.cut.length} cut from saved videos, ` : "") + `${result.cached.length} cached, ` + `${result.failed.length} failed` + diff --git a/common/controller/fetchWindowsStoredUrl.test.ts b/common/controller/fetchWindowsStoredUrl.test.ts @@ -0,0 +1,321 @@ +// fetchWindows with `storedUrl` (release 32 R5) against a fake yt-dlp that 429s +// for an Odysee PAGE URL and serves the CDN URL, through the real +// fetchWindowManaged and the real stored-URL reader (each video dir gets a +// synthetic metadata.info.json). ffmpeg is a fake too: the audio check's probe +// counts its runs. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchWindowsStoredUrl.test.ts + +import { test } from "node:test"; +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, storedUrlDoor, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows"; +import { parseClipProvenance } from "../lib/clipWindow"; +import { detectPlatform } from "../lib/platform"; +import type { StoredUrlMode } from "../lib/storedMediaUrl"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { SiteSettings } from "../lib/settings"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetchwindows-stored-")); +const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); +const ARGS_LOG = path.join(ROOT, "argv.jsonl"); +const PROBES = path.join(ROOT, "probes"); +process.env.FAKE_ARGS_LOG = ARGS_LOG; +process.env.FAKE_PROBES = PROBES; + +// The target decides: an odysee.com page (the lookup) answers 429, as the live +// lbry extractor did; a CDN file named `cdn429` answers 429 too; anything else +// writes the window. +await writeFile( + YTDLP, + `#!/usr/bin/env node +import { appendFileSync, writeFileSync } from "node:fs"; +const args = process.argv.slice(2); +appendFileSync(process.env.FAKE_ARGS_LOG, JSON.stringify(args) + "\\n"); +const url = args[args.length - 1]; +const fail = (msg) => { process.stderr.write(msg + "\\n"); process.exit(1); }; +if (url.startsWith("https://odysee.com/")) fail("ERROR: [lbry] stream: Unable to download webpage: HTTP Error 429: Too Many Requests (caused by <HTTPError 429: Too Many Requests>)"); +if (url.includes("cdn429")) fail("ERROR: [generic] x: Unable to download webpage: HTTP Error 429: Too Many Requests"); +writeFileSync(args[args.indexOf("-o") + 1], "mp4"); +`, +); +await writeFile( + FFMPEG, + `#!/usr/bin/env node +import { appendFileSync } from "node:fs"; +appendFileSync(process.env.FAKE_PROBES, "p\\n"); +process.exit(0); +`, +); +await chmod(YTDLP, 0o755); +await chmod(FFMPEG, 0o755); + +const ODYSEE: ChannelConfig = { url: "https://odysee.com/@synthetic", platform: "odysee" } as unknown as ChannelConfig; +const YOUTUBE: ChannelConfig = { url: "https://www.youtube.com/@synthetic", platform: "youtube" } as unknown as ChannelConfig; +const page = (id: string) => `https://odysee.com/@synthetic:1/stream-${id}:${id}`; +const cdn = (id: string, file = "f0") => `https://player.odycdn.com/v6/streams/${id}/${file}.mp4`; + +let run = 0; +async function corpus(): Promise<Paths> { + const channelsDir = path.join(ROOT, `corpus-${++run}`, "channels"); + await mkdir(channelsDir, { recursive: true }); + return { ytdlpBin: YTDLP, ffmpegBin: FFMPEG, channelsDir } as unknown as Paths; +} + +// A record's metadata.info.json: its page and ONE stored format (or none). +async function record(paths: Paths, slug: string, id: string, info: Record<string, unknown> | null) { + const dir = path.join(paths.channelsDir, slug, "data", id); + await mkdir(dir, { recursive: true }); + if (info) await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(info)); + return dir; +} +const odyseeInfo = (id: string, url = cdn(id)) => ({ + webpage_url: page(id), + extractor: "lbry", + formats: [{ format_id: "original", url, protocol: "https", ext: "mp4", http_headers: { Referer: "https://odysee.com/" } }], +}); + +const argv = async (): Promise<string[][]> => + (await readFile(ARGS_LOG, "utf8").catch(() => "")) + .trim() + .split("\n") + .filter(Boolean) + .map((l) => JSON.parse(l) as string[]); +const probes = async () => (await readFile(PROBES, "utf8").catch(() => "")).split("\n").filter(Boolean).length; +async function marks() { + return { argv: (await argv()).length, probes: await probes() }; +} +async function since(m: { argv: number; probes: number }) { + const all = await argv(); + const spawned = all.slice(m.argv); + return { spawned, targets: spawned.map((a) => a[a.length - 1]), probes: (await probes()) - m.probes }; +} + +function harness(over: Partial<FetchWindowsDeps> = {}) { + const rec = { sleeps: [] as number[], backoffs: [] as [string, string][], cleans: [] as string[], logs: [] as string[] }; + const deps: Partial<FetchWindowsDeps> = { + sleep: async (ms) => { + rec.sleeps.push(ms); + }, + getSettings: () => ({ sleepBetweenDownloadsSeconds: 0 }) as unknown as SiteSettings, + readChannelConfig: async (_p, slug) => (slug === "o" ? ODYSEE : slug === "y" ? YOUTUBE : null), + findVideoSourceUrl: async () => null, + assertTextReadable: async () => undefined, + cooldownRemainingMs: async () => 0, + heldRefusal: async () => null, + recordBackoff: async (platform, _p, cls) => { + rec.backoffs.push([platform, cls]); + }, + recordClean: async (platform) => { + rec.cleans.push(platform); + return null; + }, + gapRemainingMs: () => 0, + noteGap: () => {}, + ...over, + }; + return { rec, deps }; +} + +const item = (id: string, slug = "o", webpageUrl = page(id)): FetchWindowsItem => ({ slug, id, from: 10, to: 20, webpageUrl }); + +async function go(paths: Paths, items: FetchWindowsItem[], h: ReturnType<typeof harness>, storedUrl?: StoredUrlMode) { + return fetchWindows({ + paths, + items, + provenance: { requestedBy: "test" }, + gapMs: 1000, + ...(storedUrl ? { storedUrl } : {}), + onLog: (l) => h.rec.logs.push(l), + deps: h.deps, + }); +} + +const provenanceOf = async (dir: string) => + parseClipProvenance(JSON.parse(await readFile(path.join(dir, "clips", "10.00-20.00.json"), "utf8"))); + +test("never (the default): the page's 429 fails the window and stops the run, as today", async () => { + const paths = await corpus(); + await record(paths, "o", "a1", odyseeInfo("a1")); + await record(paths, "o", "a2", odyseeInfo("a2")); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("a1"), item("a2")], h); + const s = await since(m); + assert.deepEqual(s.targets, [page("a1")], "only the page, once; the CDN never asked"); + assert.equal(r.failed[0]?.class, "rate_limit"); + assert.equal(r.stopped, "rate-limit"); + assert.equal(r.notAttempted.length, 1); + assert.deepEqual(r.storedUrl, []); + assert.deepEqual(h.rec.backoffs, [["odysee", "rate_limit"]]); +}); + +test("fallback: the page 429s, the window is cut from the stored CDN URL after the gap; the audio probe ran, keyed on the page", async () => { + const paths = await corpus(); + const dir = await record(paths, "o", "b1", odyseeInfo("b1")); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("b1")], h, "fallback"); + const s = await since(m); + assert.deepEqual(s.targets, [page("b1"), cdn("b1")]); + const cdnArgs = s.spawned[1]; + assert.equal(cdnArgs[cdnArgs.indexOf("--add-headers") + 1], "Referer:https://odysee.com/"); + assert.match(cdnArgs[cdnArgs.indexOf("-f") + 1], /\/b$/, "the copy path's lenient selector"); + assert.equal(cdnArgs[cdnArgs.indexOf("--download-sections") + 1], "*10.00-20.00"); + assert.equal(r.fetched.length, 1); + assert.deepEqual(r.storedUrl.map((i) => i.id), ["b1"]); + assert.equal(r.failed.length, 0); + assert.equal(r.stopped, undefined, "nothing left over: the run did what it was asked"); + // The CDN URL is no platform's: the probe ran because the PAGE is Odysee's. + assert.equal(detectPlatform(cdn("b1")), null); + assert.equal(s.probes, 1); + const p = await provenanceOf(dir); + assert.equal(p?.source, "stored-media-url"); + assert.equal(p?.sourceHost, "player.odycdn.com"); + assert.deepEqual(p?.audioCheck, { verdict: "clean", attempts: 1 }); + assert.deepEqual(h.rec.backoffs, [["odysee", "rate_limit"]], "the lookup's backoff is still signalled"); + assert.deepEqual(h.rec.cleans, [], "a stored-URL success does not record the platform clean"); + assert.deepEqual(h.rec.sleeps, [1000], "the gap before the fallback fetch"); + assert.match(h.rec.logs.join(""), /cut from the stored media URL \(player\.odycdn\.com\) — odysee lookup rate-limited/); +}); + +test("fallback, after the 429: stored-URL items go straight to the CDN; one without a stored URL is left for later", async () => { + const paths = await corpus(); + await record(paths, "o", "c1", odyseeInfo("c1")); + await record(paths, "o", "c2", odyseeInfo("c2")); + await record(paths, "o", "c3", null); + await record(paths, "o", "c4", odyseeInfo("c4")); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("c1"), item("c2"), item("c3"), item("c4")], h, "fallback"); + const s = await since(m); + assert.deepEqual(s.targets, [page("c1"), cdn("c1"), cdn("c2"), cdn("c4")], "the page asked once, never again"); + assert.deepEqual(r.storedUrl.map((i) => i.id), ["c1", "c2", "c4"]); + assert.deepEqual(r.notAttempted.map((i) => i.id), ["c3"]); + assert.equal(r.stopped, "rate-limit"); + assert.deepEqual(h.rec.sleeps, [1000, 1000, 1000], "the same gaps between fetches"); +}); + +test("fallback: a page 429 on an item with no stored URL fails it; the stored-URL items after it go on", async () => { + const paths = await corpus(); + await record(paths, "o", "d1", null); + await record(paths, "o", "d2", odyseeInfo("d2")); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("d1"), item("d2")], h, "fallback"); + const s = await since(m); + assert.deepEqual(s.targets, [page("d1"), cdn("d2")]); + assert.deepEqual(r.failed.map((f) => [f.item.id, f.class]), [["d1", "rate_limit"]]); + assert.deepEqual(r.storedUrl.map((i) => i.id), ["d2"]); +}); + +test("only: no page request at all", async () => { + const paths = await corpus(); + const dir = await record(paths, "o", "e1", odyseeInfo("e1")); + await record(paths, "o", "e2", odyseeInfo("e2")); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("e1"), item("e2")], h, "only"); + const s = await since(m); + assert.deepEqual(s.targets, [cdn("e1"), cdn("e2")]); + assert.ok(!s.targets.some((t) => t.startsWith("https://odysee.com/"))); + assert.equal(r.fetched.length, 2); + assert.equal(s.probes, 2); + assert.deepEqual(h.rec.backoffs, []); + assert.deepEqual(h.rec.cleans, []); + assert.deepEqual(h.rec.sleeps, [1000], "one gap between the two"); + assert.match(h.rec.logs.join(""), /cut from the stored media URL \(player\.odycdn\.com\) \(asked: only\)/); + assert.equal((await provenanceOf(dir))?.source, "stored-media-url"); +}); + +for (const mode of ["only", "fallback"] as const) { + test(`a held platform + ${mode}: items with a stored URL run; one without is left, and the run says held`, async () => { + const paths = await corpus(); + await record(paths, "o", "f1", odyseeInfo("f1")); + await record(paths, "o", "f2", null); + await record(paths, "o", "f3", odyseeInfo("f3")); + const h = harness({ heldRefusal: async (p) => (p === "odysee" ? "odysee is held (test)" : null) }); + const m = await marks(); + const r = await go(paths, [item("f1"), item("f2"), item("f3")], h, mode); + const s = await since(m); + assert.deepEqual(s.targets, [cdn("f1"), cdn("f3")], "no page request while held"); + assert.deepEqual(r.notAttempted.map((i) => i.id), ["f2"]); + assert.equal(r.stopped, "held"); + assert.match(h.rec.logs.join(""), /f2 10\.00–20\.00: not attempted — odysee is held \(test\), and it has no stored media URL/); + if (mode === "fallback") { + assert.match(h.rec.logs.join(""), /— odysee lookup held/); + } + }); +} + +test("never + a held platform: stopped at the door, as today", async () => { + const paths = await corpus(); + await record(paths, "o", "g1", odyseeInfo("g1")); + const h = harness({ heldRefusal: async () => "odysee is held (test)" }); + const m = await marks(); + const r = await go(paths, [item("g1")], h); + assert.deepEqual((await since(m)).targets, []); + assert.equal(r.stopped, "held"); +}); + +test("a 429 from the stored URL itself stops the run", async () => { + const paths = await corpus(); + await record(paths, "o", "h1", odyseeInfo("h1", cdn("h1", "cdn429"))); + await record(paths, "o", "h2", odyseeInfo("h2")); + const h = harness(); + const r = await go(paths, [item("h1"), item("h2")], h, "only"); + assert.equal(r.stopped, "rate-limit"); + assert.deepEqual(r.notAttempted.map((i) => i.id), ["h2"]); + assert.deepEqual(h.rec.backoffs, [["odysee", "rate_limit"]]); +}); + +test("an off-allowlist platform's stored URL is ignored: fetched from its page", async () => { + const paths = await corpus(); + const yt = "https://www.youtube.com/watch?v=synthetic01"; + const dir = await record(paths, "y", "synthetic01", { + webpage_url: yt, + formats: [{ url: cdn("synthetic01"), protocol: "https" }], + }); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("synthetic01", "y", yt)], h, "only"); + assert.deepEqual((await since(m)).targets, [yt]); + assert.equal(r.fetched.length, 1); + assert.deepEqual(r.storedUrl, []); + assert.equal((await provenanceOf(dir))?.source, undefined); + assert.deepEqual(h.rec.cleans, ["youtube"]); +}); + +test("a stored URL off the platform's CDN host is ignored: the page is asked (and 429s)", async () => { + const paths = await corpus(); + await record(paths, "o", "i1", odyseeInfo("i1", "https://cdn.example.net/v6/streams/i1/f0.mp4")); + const h = harness(); + const m = await marks(); + const r = await go(paths, [item("i1")], h, "only"); + assert.deepEqual((await since(m)).targets, [page("i1")]); + assert.equal(r.failed[0]?.class, "rate_limit"); + assert.deepEqual(r.storedUrl, []); +}); + +test("a find-copy item (another recording's URL) never uses the stored URL", async () => { + const paths = await corpus(); + await record(paths, "o", "j1", odyseeInfo("j1")); + const h = harness(); + const m = await marks(); + // On the allowlisted platform itself, so only the copy guard keeps it off the CDN. + const copyUrl = "https://odysee.com/@mirror:2/stream-j1:j1"; + 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/common/lib/clipWindow.ts b/common/lib/clipWindow.ts @@ -152,10 +152,14 @@ export type ClipProvenance = { // The argv the fetch actually ran, minus the binary. For the case where a // window looks wrong and the question is which format selector produced it. ytdlp?: { args: string[] }; - // WHERE THE BYTES CAME FROM, when it was not the network: "saved-video" for - // a window cut from the video's saved container (release 21 D2, - // lib/savedVideoWindow-server.ts). Absent on every fetched window. + // WHERE THE BYTES CAME FROM, when it was not the recording's page: + // "saved-video" for a window cut from the video's saved container (release 21 + // D2, lib/savedVideoWindow-server.ts); "stored-media-url" for one fetched from + // the media URL its metadata.info.json stores (release 32 R5, + // lib/storedMediaUrl.ts), with that URL's host in `sourceHost`. Absent on a + // window fetched through the page. source?: ClipWindowSource; + sourceHost?: string; // WHICH COPY a window of a gone recording was fetched from (release 29 E2, // publish/findCopy.ts): a Wayback Machine capture of its page, or an // archive.org mirror's file — and its URL. Absent when the window came from @@ -182,7 +186,7 @@ export function coerceClipCopy(v: unknown): ClipCopy | undefined { return { from: r.from as ClipCopy["from"], url: r.url }; } -export const CLIP_WINDOW_SOURCES = ["saved-video"] as const; +export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url"] as const; export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number]; const str = (v: unknown): string | undefined => @@ -222,6 +226,8 @@ export function parseClipProvenance(raw: unknown): ClipProvenance | null { if ((CLIP_WINDOW_SOURCES as readonly unknown[]).includes(r.source)) { out.source = r.source as ClipWindowSource; } + const sourceHost = str(r.sourceHost); + if (sourceHost) out.sourceHost = sourceHost; const copy = coerceClipCopy(r.copy); if (copy) out.copy = copy; const ac = r.audioCheck as { verdict?: unknown; attempts?: unknown } | undefined; diff --git a/common/lib/storedMediaUrl-server.ts b/common/lib/storedMediaUrl-server.ts @@ -0,0 +1,16 @@ +// The filesystem half of lib/storedMediaUrl.ts: a record's stored media URL, read +// from its metadata.info.json. No file, an unreadable or malformed one, or a URL +// the allowlist does not trust → null (the caller fetches from the page as always). + +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import { storedMediaUrlFromInfo, type StoredMediaUrl } from "./storedMediaUrl"; + +export async function storedMediaUrl(videoDir: string): Promise<StoredMediaUrl | null> { + try { + const raw = await readFile(path.join(videoDir, "metadata.info.json"), "utf8"); + return storedMediaUrlFromInfo(JSON.parse(raw)); + } catch { + return null; + } +} diff --git a/common/lib/storedMediaUrl.test.ts b/common/lib/storedMediaUrl.test.ts @@ -0,0 +1,89 @@ +// The stored media URL (release 32 R5): only an allowlisted platform's single +// direct format on its CDN host; anything else is null. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedMediaUrl.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + STORED_URL_PLATFORMS, + isStoredUrlMode, + storedMediaUrlFromInfo, + storedUrlWhyText, +} from "./storedMediaUrl"; +import { storedMediaUrl } from "./storedMediaUrl-server"; + +const PAGE = "https://odysee.com/@synthetic:1/stream-one:abc123"; +const CDN = "https://player.odycdn.com/v6/streams/abc123/def456.mp4"; +const odysee = (formats: unknown, extra: Record<string, unknown> = {}) => ({ + webpage_url: PAGE, + extractor: "lbry", + ...(formats === undefined ? {} : { formats }), + ...extra, +}); + +test("an Odysee record's single CDN format is its stored media URL", () => { + assert.deepEqual(STORED_URL_PLATFORMS, ["odysee"]); + assert.deepEqual( + storedMediaUrlFromInfo(odysee([{ format_id: "original", url: CDN, protocol: "https", ext: "mp4" }])), + { url: CDN, host: "player.odycdn.com", platform: "odysee", referer: "https://odysee.com/" }, + ); +}); + +test("no formats: the top-level url, on the same terms", () => { + assert.equal(storedMediaUrlFromInfo(odysee(undefined, { url: CDN }))?.url, CDN); + assert.equal(storedMediaUrlFromInfo(odysee([], { url: CDN }))?.host, "player.odycdn.com"); +}); + +test("a host off the platform's CDN is ignored", () => { + for (const url of [ + "https://cdn.example.net/v6/streams/abc123/def456.mp4", + "https://odycdn.com.example.net/x.mp4", + "https://odysee.com/$/stream/abc123", + "https://player.odycdn.com.evil/x.mp4", + ]) { + assert.equal(storedMediaUrlFromInfo(odysee([{ url, protocol: "https" }])), null, url); + } +}); + +test("an off-allowlist platform's stored URL is ignored, CDN-shaped or not", () => { + for (const page of ["https://www.youtube.com/watch?v=abcdefghijk", "https://rumble.com/v1-x.html"]) { + assert.equal(storedMediaUrlFromInfo({ webpage_url: page, formats: [{ url: CDN, protocol: "https" }] }), null, page); + } + // No page at all: no platform, no trust. + assert.equal(storedMediaUrlFromInfo({ formats: [{ url: CDN }] }), null); +}); + +test("more than one format, a manifest protocol, credentials or a non-http scheme: null", () => { + assert.equal(storedMediaUrlFromInfo(odysee([{ url: CDN }, { url: CDN.replace("def456", "ghi789") }])), null); + assert.equal(storedMediaUrlFromInfo(odysee([{ url: CDN.replace(".mp4", ".m3u8"), protocol: "m3u8_native" }])), null); + assert.equal(storedMediaUrlFromInfo(odysee([{ url: "https://u:p@player.odycdn.com/x.mp4" }])), null); + assert.equal(storedMediaUrlFromInfo(odysee([{ url: "ftp://player.odycdn.com/x.mp4" }])), null); + assert.equal(storedMediaUrlFromInfo(odysee([{ url: 42 }])), null); + assert.equal(storedMediaUrlFromInfo(null), null); + assert.equal(storedMediaUrlFromInfo([]), null); +}); + +test("the reader: the file's URL, or null for no file or a malformed one", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "storedurl-")); + const good = path.join(dir, "good"); + const bad = path.join(dir, "bad"); + await mkdir(good); + await mkdir(bad); + await writeFile(path.join(good, "metadata.info.json"), JSON.stringify(odysee([{ url: CDN, protocol: "https" }]))); + await writeFile(path.join(bad, "metadata.info.json"), "{ not json"); + assert.equal((await storedMediaUrl(good))?.url, CDN); + assert.equal(await storedMediaUrl(bad), null); + assert.equal(await storedMediaUrl(path.join(dir, "absent")), null); +}); + +test("modes and the log's words", () => { + assert.ok(isStoredUrlMode("never") && isStoredUrlMode("fallback") && isStoredUrlMode("only")); + assert.ok(!isStoredUrlMode("always") && !isStoredUrlMode(undefined)); + assert.equal(storedUrlWhyText("only", "odysee"), "(asked: only)"); + assert.equal(storedUrlWhyText("rate-limited", "odysee"), "— odysee lookup rate-limited"); + assert.equal(storedUrlWhyText("held", "odysee"), "— odysee lookup held"); +}); diff --git a/common/lib/storedMediaUrl.ts b/common/lib/storedMediaUrl.ts @@ -0,0 +1,106 @@ +// A CLIP WINDOW FROM THE STORED MEDIA URL (release 32 R5). +// +// Odysee answers 429 to yt-dlp's page/API lookup (`[lbry] … HTTP Error 429`) on +// the first request of a run, hours apart, with cookies — and a fetch-windows job +// then stops and the platform is held. But every Odysee record's +// metadata.info.json already names its media: ONE format whose `url` is on the +// platform's CDN (`player.odycdn.com`), a different endpoint from the lookup. The +// operator approved cutting a window from that URL instead, for this case, opt-in +// per request (`storedUrl` on a fetch-windows body): +// +// never the default: nothing changes. +// fallback the page first, as always; on a rate limit (or a held / cooling +// platform) the window is cut from the stored URL. +// only straight to the stored URL: no page or API request at all. +// +// TRUSTED ONLY ON A NAMED ALLOWLIST. A stored URL is a string a platform handed +// yt-dlp months ago; fetching it bypasses the extractor. So it is used only for a +// platform in STORED_URL_PLATFORMS, only on that platform's CDN hosts, only when +// the record names exactly one http(s) format (or none and a top-level `url`) — +// never a manifest, never a host off the list, never credentials in the URL. +// +// Pure: the reader of the file is storedMediaUrl-server.ts. + +import { detectPlatform } from "./platform"; + +export const STORED_URL_MODES = ["never", "fallback", "only"] as const; +export type StoredUrlMode = (typeof STORED_URL_MODES)[number]; + +export function isStoredUrlMode(v: unknown): v is StoredUrlMode { + return (STORED_URL_MODES as readonly unknown[]).includes(v); +} + +export const STORED_URL_PLATFORMS = ["odysee"] as const; +export type StoredUrlPlatform = (typeof STORED_URL_PLATFORMS)[number]; + +export function isStoredUrlPlatform(v: unknown): v is StoredUrlPlatform { + return (STORED_URL_PLATFORMS as readonly unknown[]).includes(v); +} + +// Per platform: which hosts are its CDN, and the Referer its player sends (the +// stored format's own `http_headers.Referer`, pinned here rather than read from +// the file). +const CDN: Readonly<Record<StoredUrlPlatform, { host: (h: string) => boolean; referer: string }>> = { + odysee: { host: (h) => h.endsWith(".odycdn.com"), referer: "https://odysee.com/" }, +}; + +export type StoredMediaUrl = { + url: string; + host: string; + platform: StoredUrlPlatform; + referer: string; +}; + +// Why a window was cut from the stored URL: the page lookup rate-limited (this +// run, or a cooldown), the platform is held, or the request said `only`. +export type StoredUrlWhy = "rate-limited" | "held" | "only"; + +export function storedUrlWhyText(why: StoredUrlWhy, platform: string): string { + if (why === "only") return "(asked: only)"; + return `— ${platform} lookup ${why === "held" ? "held" : "rate-limited"}`; +} + +const DIRECT_PROTOCOLS = new Set(["http", "https"]); + +function directUrl(raw: unknown, protocol: unknown): URL | null { + if (typeof raw !== "string") return null; + // yt-dlp's `protocol` names how the format is fetched: anything but a plain + // http(s) GET (m3u8, dash, …) is not "one direct file". + if (protocol !== undefined && !(typeof protocol === "string" && DIRECT_PROTOCOLS.has(protocol))) { + return null; + } + let u: URL; + try { + u = new URL(raw); + } catch { + return null; + } + if (u.protocol !== "https:" && u.protocol !== "http:") return null; + if (u.username || u.password) return null; + return u; +} + +// The stored media URL of a record's parsed metadata.info.json, or null. +export function storedMediaUrlFromInfo(info: unknown): StoredMediaUrl | null { + if (!info || typeof info !== "object" || Array.isArray(info)) return null; + const r = info as Record<string, unknown>; + const page = typeof r.webpage_url === "string" ? r.webpage_url : typeof r.original_url === "string" ? r.original_url : null; + const platform = page ? detectPlatform(page) : null; + if (!isStoredUrlPlatform(platform)) return null; + let u: URL | null; + if (Array.isArray(r.formats) && r.formats.length > 0) { + // A SINGLE FORMAT: more than one is a ladder of variants, and picking among + // them is the extractor's job. + if (r.formats.length !== 1) return null; + const f = r.formats[0] as Record<string, unknown> | null; + if (!f || typeof f !== "object") return null; + u = directUrl(f.url, f.protocol); + } else { + u = directUrl(r.url, r.protocol); + } + if (!u) return null; + const host = u.hostname.toLowerCase(); + const cdn = CDN[platform]; + if (!cdn.host(host)) return null; + return { url: u.href, host, platform, referer: cdn.referer }; +} diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts @@ -50,6 +50,7 @@ import { channelExtraArgs, configForVideoUrl } from "./channelArgs"; import { runOneYtdlp } from "./runOneYtdlp"; import { FULL_LOG_PROGRESS_ARGS } from "./downloadOneManaged"; import { clipFormatSelector, copyClipFormatSelector } from "./downloadFormat"; +import { storedUrlWhyText, type StoredMediaUrl, type StoredUrlWhy } from "../lib/storedMediaUrl"; // The source height a clip is worth fetching at. 720 is umtool's number and the // reason is the render: the deliverable is 1080p with a clip inset, so pixels @@ -109,7 +110,14 @@ export type FetchWindowOpts = { // channels/<slug>/data/<id> — the window lands in its `clips/` subdirectory. videoDir: string; videoId: string; + // The recording's PAGE URL. What every policy keys on (the platform args, the + // audio check) even when the bytes come from `storedMedia`. videoUrl: string; + // CUT FROM THE STORED MEDIA URL instead of the page (release 32 R5, + // lib/storedMediaUrl.ts): yt-dlp is given the stored direct file (the generic + // extractor, the copy path's lenient selector, the platform player's + // Referer) and no page or API request is made. `why` is for the log. + storedMedia?: StoredMediaUrl & { why: StoredUrlWhy }; // Working directory for the yt-dlp process. Nothing it writes is // cwd-relative (`-o` is absolute and `--ignore-config` stops the operator's // own config redirecting anything), so this only decides where yt-dlp's own @@ -254,6 +262,13 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< await rm(part, { force: true }); const maxHeight = opts.maxHeight ?? DEFAULT_CLIP_MAX_HEIGHT; + const stored = opts.storedMedia; + if (stored && attempt === 1) { + opts.onLog( + `Window ${from.toFixed(2)}–${to.toFixed(2)}: cutting from the stored media URL ` + + `(${stored.host}) ${storedUrlWhyText(stored.why, stored.platform)}; no page request.\n`, + ); + } const argsWith = (cookies: string | undefined, retryArgs: string[] = []): string[] => [ // The operator's own yt-dlp config redirects output and attaches thumbnail // and metadata post-processors; without this the window lands elsewhere — @@ -271,7 +286,12 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< // citation. "--force-keyframes-at-cuts", "-f", - opts.provenance.copy ? copyClipFormatSelector(maxHeight) : clipFormatSelector(maxHeight), + // A copy's file and a stored media URL are both "one direct file of unknown + // height": the lenient selector. + opts.provenance.copy || stored + ? copyClipFormatSelector(maxHeight) + : clipFormatSelector(maxHeight), + ...(stored ? ["--add-headers", `Referer:${stored.referer}`] : []), "--merge-output-format", "mp4", ...FULL_LOG_PROGRESS_ARGS, @@ -303,7 +323,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< "-o", part, "--", - opts.videoUrl, + stored ? stored.url : opts.videoUrl, ]; const run = async (cookies: string | undefined, retryArgs: string[] = []) => @@ -401,6 +421,8 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< st = await stat(produced); } let audioCheck: ClipAudioCheck | undefined; + // Keyed on the PAGE URL (`videoUrl`), never the bytes' URL: a window cut from + // an Odysee record's CDN file is an Odysee window (release 32 R5). if (audioCheckApplies(opts.channelConfig, opts.videoUrl)) { const probe = await probeAudioStream({ ffmpegBin: opts.paths.ffmpegBin, @@ -429,6 +451,7 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< ? { pad: opts.provenance.pad } : {}), ...(opts.provenance.copy ? { copy: opts.provenance.copy } : {}), + ...(stored ? { source: "stored-media-url" as const, sourceHost: stored.host } : {}), ...(audioCheck ? { audioCheck } : {}), bytes: st.size, fetchedAt: new Date().toISOString(), @@ -437,7 +460,11 @@ async function fetchWindowOnce(opts: FetchWindowOpts, attempt: number): Promise< await writeClipProvenance(videoDir, from, to, provenance); opts.onLog( `Fetched ${from.toFixed(2)}–${to.toFixed(2)} of ${opts.videoId} into ` + - `clips/${clipWindowFile(from, to)} (${st.size} bytes).\n`, + `clips/${clipWindowFile(from, to)} (${st.size} bytes)` + + (stored + ? `: cut from the stored media URL (${stored.host}) ${storedUrlWhyText(stored.why, stored.platform)}` + : "") + + ".\n", ); return { diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A clip window can be cut from the media URL an Odysee record already stores, when Odysee's lookup is rate-limited.** `pnpm ops fetch-windows` takes `"storedUrl"`: `"fallback"` tries the page as before and, when the lookup answers 429, cuts the window from the file the record's `metadata.info.json` names on Odysee's CDN (`*.odycdn.com`) instead; `"only"` goes straight to that file and asks the page nothing. A held or cooling Odysee no longer refuses those windows — only the ones with no stored file are refused or left for a later run. Same queue, same gaps between fetches, the audio check still applies, and the window's provenance says `source: "stored-media-url"` with the host. The default, `"never"`, changes nothing; only Odysee is allowed. Needs a restart of the editor. - **umtool's drafts review is an audition deck: hear the cited moment, then keep it or cut it.** `/projects/<project>/review` shows one card per drafted field still waiting for a verdict: the drafted value large, the cited span of its clip playing (video when a window or saved video holds it, else audio marked "audio only"), and the quote under it lighting word by word as it is spoken. Swipe right, → or `k` keeps it (approves); left, ← or `x` cuts it (rejects — tap a reason chip or write a few words, never required); up, ↑ or `e` edits it on the card (on-screen text, narration, teaser lines and the YouTube title; Enter keeps it as edited); down, ↓ or `s` skips it to the back; space replays the span; `z` undoes the last keep, cut or skip. Tap a word to mark it misheard: the note says so. Every action is also a button (a bar under the thumb on a phone). The next card's media is already loading, and the deck ends with what was cut and skipped. Verdicts are the same `drafts.review.json` as before; **List** (`?view=list`) is the old list, whose reader now plays the span too. No model is needed for any of it. - **Fetch clip wherever a citation is shown in umtool.** When nothing on disk holds a cited span — on the deck, in the list's reader, on an article's evidence panel and its evidence walk — **Fetch clip** asks the editor for those seconds exactly as the MCP's `fetch_clip` does, shows its progress, and plays the window when it lands. A rate limit says the platform is rate-limiting; a window the audio check refused says the source served corrupt audio. The evidence panel plays video first and has **Play span** (from the span's start to its end). - **Verify quotes and Check report on an article's page.** The Article tab has **Verify quotes** (what `archilyzer reports verify-quotes --article <id>` prints: each quote's status — ok, fragment, inexact, drift, en-orig-drift — its score and track, with **Play** to hear it) and **Check report** (what `archilyzer reports check --article <id>` says: compose would pass, or each problem in its own sentence, with **Play** where it names a citation; **allow missing media** as `--allow-missing-media`). The article's respellings apply. Needs a restart of umtool. 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/plans/FACTS.md b/plans/FACTS.md @@ -10056,3 +10056,33 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **Cookie spec `file:<path>`** (`cookiePolicy.ts` `cookieArgs`, `cookieFileOf`; gallery-dl's login args) → `--cookies <path>`; any other spec stays `--cookies-from-browser <spec>`. `file:` with no path → no flag. - **First run:** the dashboard's `FirstRunPanel` renders only while the actionable summary has zero channels. + +## Release 32 lane R5: a clip window from the stored media URL (verified 2026-10-16, branch `r32/stored-url`) + +- **`lib/storedMediaUrl.ts`** (pure) + **`lib/storedMediaUrl-server.ts`** (`storedMediaUrl(videoDir)`, reads + `metadata.info.json`, null on any failure). Trusted only when the record's `webpage_url` (else `original_url`) is a + platform in `STORED_URL_PLATFORMS = ["odysee"]`, the record has exactly ONE format (or no `formats` and a top-level + `url`), its `protocol` is absent or `http`/`https`, the URL is http(s) with no credentials, and its host passes the + platform's CDN test (Odysee: hostname ends `.odycdn.com`). The Referer sent is pinned per platform + (`https://odysee.com/`), not read from the file. Live shape (cornbreadman, 2026-10-16): one format `original`, + `https://player.odycdn.com/v6/streams/<claim>/<hash>.mp4`, height 720, `protocol: https`. +- **`storedUrl: "never" | "fallback" | "only"`** on the fetch-windows body (route, `fetchWindowsAction`, + `fetchMissingEvidenceAction`, the job spec's `params.storedUrl` for Retry, `fetchWindows({storedUrl})`). Default + `never` = the old code path exactly. Never used for an item with `copy` (find-copy's URL is another recording). +- **The controller's rules (stored modes):** `only` + a stored URL → no page request. A platform held, cooling, or + rate-limited earlier in the run goes into a per-run `limited` map: its stored-URL items run via the stored URL + (`why` held | rate-limited), the rest go to `notAttempted` and `result.stopped ??= held | cooldown | rate-limit` + (the job then ends failed "Stopped (…)"). `fallback`: a page `rate_limit` on an item with a stored URL → the gap → + the stored-URL fetch (the page's backoff is already recorded by fetchWindowManaged). A stored-URL success never + calls `recordPlatformClean`; a 429 from the stored URL itself stops the run as before. Gaps and the gap key + (`clip-window:<platform>`) are unchanged. `result.storedUrl` lists the items fetched that way (a subset of `fetched`). +- **The editor's door** (`storedUrlDoor` in `controller/fetchWindows.ts`): a refused group (held/cooldown) with a stored + mode starts its job with the items whose record stores a trusted URL and refuses the rest (`refused[].items` = the + rest). The dry run's group carries `storedUrlItems` only when a stored mode was asked. +- **`fetchWindowManaged({storedMedia})`**: the yt-dlp target is the stored URL, `-f copyClipFormatSelector`, + `--add-headers Referer:<referer>`, everything else as a page fetch; `videoUrl` stays the PAGE URL, so the platform + args and `audioCheckApplies` key on it (`detectPlatform(<odycdn url>)` is null). Provenance gains + `source: "stored-media-url"` (`CLIP_WINDOW_SOURCES`) and `sourceHost`; the log says + `cut from the stored media URL (<host>) — <platform> lookup rate-limited|held` or `(asked: only)`. +- Not wired: the single `/api/media/fetch-window` route and the MCP's `fetch_clip` (which posts to that route, not to + fetch-windows), and any UI toggle. diff --git a/plans/release-32/stored-url.md b/plans/release-32/stored-url.md @@ -0,0 +1,55 @@ +# Release 32 lane R5 — a clip window from the stored media URL when the lookup is rate-limited (as shipped) + +Live (2026-10-16): Odysee answers 429 to yt-dlp's page/API lookup (`[lbry] … HTTP Error 429`) on the first request of a +run, hours apart, with cookies; the fetch-windows job stops (`stopped: rate-limit`) and the platform is held, so later +runs are refused at the door. Every held Odysee record's `metadata.info.json` already stores its media: one format on +`player.odycdn.com`, a different endpoint. Ruling (operator): for this case, cut the window from that stored URL; +opt-in per request. + +## What + +- `common/lib/storedMediaUrl.ts` (pure) + `storedMediaUrl-server.ts`: `storedMediaUrl(videoDir)` → `{url, host, + platform, referer}` or null. Allowlist `STORED_URL_PLATFORMS = ["odysee"]`; CDN hosts `*.odycdn.com`; one format + (or the top-level `url` when there are none), http(s) only, no manifest protocol, no credentials. +- `fetchWindows({storedUrl})`, `"never" | "fallback" | "only"`, default `never` (the old path). `fallback`: the page + first; on a page `rate_limit` the window is cut from the stored URL after the gap. `only`: no page request. A platform + held, cooling or rate-limited earlier in the run does not stop its stored-URL items; its items without one are + `notAttempted` and the run reports the stop. The backoff is still recorded; a stored-URL success never records the + platform clean; a 429 from the stored URL itself stops the run. Same queue, same gaps. `result.storedUrl` lists them. +- `fetchWindowManaged({storedMedia})`: yt-dlp gets the stored URL, `copyClipFormatSelector`, `--add-headers + Referer:https://odysee.com/`, `--download-sections` as before; `videoUrl` stays the page URL, so the audio check + (`audioCheckApplies(config, pageUrl)`) and its final probe + one re-fetch still apply. +- Provenance: `source: "stored-media-url"` (`CLIP_WINDOW_SOURCES`, parsed tolerantly) and `sourceHost`. The log: + `cut from the stored media URL (player.odycdn.com) — odysee lookup rate-limited` | `— odysee lookup held` | + `(asked: only)`. +- Editor: `fetchWindowsAction` / the ops route take `storedUrl` (validated; siteId bodies too); a held or cooling + group with a stored mode starts its job with the windows that have a stored URL and refuses the rest + (`storedUrlDoor`); the dry run's group carries `storedUrlItems`; the job spec keeps `storedUrl` for Retry. +- `pnpm ops fetch-windows` help, COMMANDS.md regenerated. + +## Files + +`common/lib/storedMediaUrl.ts`, `common/lib/storedMediaUrl-server.ts`, `common/lib/clipWindow.ts`, +`common/ytdlp/fetchWindowManaged.ts`, `common/controller/fetchWindows.ts`, +`editor/app/channels/[slug]/videos/fetchWindowsAction.ts`, `editor/app/api/ops/fetch-windows/route.ts`, +`editor/app/jobs/jobReplayRegistry.ts`, `scripts/archilyzer-ops.mjs`, `COMMANDS.md`. Tests: +`common/lib/storedMediaUrl.test.ts` (7), `common/controller/fetchWindowsStoredUrl.test.ts` (13), +`editor/app/channels/[slug]/videos/fetchWindowsStoredUrl.test.ts` (3), `editor/app/api/ops/fetch-windows/route.test.ts` +(+1 test, +2 cases). + +## Gates + +tsc clean. common 4488 → 4508 (4507 pass + 1 skipped); editor 327 → 331; scripts 1052 (1048 + 4 skipped); docs cli, +env, files and settings example checks clean. mcp not touched (its `fetch_clip` posts to the single fetch-window +route, not to fetch-windows). No e2e named for this lane (no UI). + +## Rulings followed + +Opt-in per request, default `never`; allowlist of one platform and its CDN hosts; one stream, real gaps (the gap key +and the gap are the page fetch's); the audio check keys on the page URL; no model, no live network in any test. + +## Owed + +- A UI toggle (the operator's UI-without-AI rule): "Cut from the stored media URL" on the Reports tab's Fetch missing + evidence and the video page's window fetch. +- `storedUrl` on the single `/api/media/fetch-window` route and the MCP's `fetch_clip`. 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",