Archilyzer · Source

archilyzer

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

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

common: a clip window from the stored media URL when the platform's lookup is limited — storedMediaUrl (an allowlisted platform's single direct format on its CDN: odysee, *.odycdn.com), fetchWindows `storedUrl: never | fallback | only` (default never: nothing changes; fallback cuts from the stored URL on a page rate_limit; only asks no page; a held or limited platform's stored-URL items go on, the rest are left), fetchWindowManaged's storedMedia target (the copy path's selector, the player's Referer, the audio check keyed on the page URL), provenance source "stored-media-url" + sourceHost

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

Diffstat:
Mcommon/controller/fetchWindows.ts | 321++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Acommon/controller/fetchWindowsStoredUrl.test.ts | 313+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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++++++++++++++++++++++++++++++---
7 files changed, 799 insertions(+), 93 deletions(-)

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,6 +280,7 @@ const DEFAULT_DEPS: FetchWindowsDeps = { gapRemainingMs: (key) => platformGapRemainingMs(key), noteGap: (key, gapMs) => notePlatformGap(key, gapMs), recordFailedCopy, + storedMediaUrl, }; export function fetchWindowsItemLabel(item: FetchWindowsItem): string { @@ -280,6 +310,7 @@ export async function fetchWindows({ provenance, maxHeight, gapMs, + storedUrl: storedMode = "never", onLog, signal, drainSignal, @@ -293,6 +324,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 +346,7 @@ export async function fetchWindows({ cut: [], failed: [], notAttempted: [], + storedUrl: [], }; log( `Fetch windows: ${work.length} window(s) for ${provenance.requestedBy}` + @@ -356,6 +390,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 +540,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 +585,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,313 @@ +// 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, 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]); +}); 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 {