commit d1e695e3fee12cab44835668b733dfe36e9b09b9
parent 8b91abae71cbbc10aeb38ef38e40cd6439656c5c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 23:35:47 -0400
editor: "Cut from the stored media URL" on Fetch missing evidence, and storedUrl on the single fetch-window route
The Reports and Articles tabs' Fetch missing evidence offer the option once a
preview (which now always counts the stored URLs — a dry run starts nothing) or
a refused run shows windows on a stored-URL platform; off by default, ticked it
asks "fallback". POST /api/media/fetch-window takes storedUrl
never|fallback|only with the batch's rule for one window: only cuts from the
record's stored media URL with no page request, a held or cooling platform does
not refuse a window that has one, fallback cuts from it after the clip gap when
the page lookup 429s; a Retry keeps the mode. The label and help are one pair of
constants in lib/storedMediaUrl.ts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 340 insertions(+), 26 deletions(-)
diff --git a/common/lib/storedMediaUrl.ts b/common/lib/storedMediaUrl.ts
@@ -37,6 +37,22 @@ export function isStoredUrlPlatform(v: unknown): v is StoredUrlPlatform {
return (STORED_URL_PLATFORMS as readonly unknown[]).includes(v);
}
+// THE UI'S WORDS (release 32 R6): every surface that offers the stored URL — the
+// editor's Fetch missing evidence, umtool's Fetch clip and the benches — says it
+// with this label and this help, and asks with STORED_URL_UI_MODE. A person's
+// tick asks "fallback": the page first, as always, and the stored file only when
+// the platform refuses the lookup (or is held or cooling down) — so ticking it
+// for a platform that is answering changes nothing. `only` stays for the CLI and
+// the MCP, which can say why they skip the page.
+export const STORED_URL_LABEL = "Cut from the stored media URL";
+export const STORED_URL_UI_MODE: StoredUrlMode = "fallback";
+const PLATFORM_NAMES: Readonly<Record<StoredUrlPlatform, string>> = { odysee: "Odysee" };
+export const STORED_URL_HELP =
+ `${STORED_URL_PLATFORMS.map((p) => PLATFORM_NAMES[p]).join(", ")} only. When the platform refuses ` +
+ "the page lookup (a rate limit, or it is on hold), the seconds are cut straight from the video file " +
+ "address the archive saved with the record, the way the platform's own player reads it. " +
+ "Off: the page is asked as usual, and a refusal stops the fetch.";
+
// 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).
diff --git a/editor/app/api/media/fetch-window/route.storedUrl.test.ts b/editor/app/api/media/fetch-window/route.storedUrl.test.ts
@@ -0,0 +1,154 @@
+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/api/media/fetch-window/route.storedUrl.test.ts"
+//
+// `storedUrl` on the single-window route (release 32 R6) — the fetch-windows
+// batch's rule for one window. yt-dlp and ffmpeg are fakes (YTDLP_BIN,
+// FFMPEG_BIN): an odysee.com page answers 429, a cut from an http input is
+// written. In order: a fallback with the platform answering (the page 429s, the
+// window is cut from the stored URL — and the 429 leaves Odysee cooling), then
+// the cooling platform: never refuses, fallback without a stored URL refuses,
+// only and fallback with one cut it without asking the page.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-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
+import { appendFileSync, writeFileSync } from "node:fs";
+const args = process.argv.slice(2);
+const input = args[args.indexOf("-i") + 1] ?? "";
+if (input.startsWith("http")) {
+ appendFileSync(${JSON.stringify(ARGS_LOG)}, JSON.stringify([...args, input]) + "\\n");
+ writeFileSync(args[args.length - 1], "mp4");
+}
+process.exit(0);
+`,
+);
+await chmod(YTDLP, 0o755);
+await chmod(FFMPEG, 0o755);
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+process.env.YTDLP_BIN = YTDLP;
+process.env.FFMPEG_BIN = FFMPEG;
+// The fallback's pause, as on the e2e server.
+process.env.E2E_CLIP_WINDOW_GAP_MS = "0";
+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 S1 = await video("s1", true);
+const S2 = await video("s2", true);
+await video("n1", false);
+
+const { POST } = await import("./route");
+const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+function post(body: Record<string, unknown>): Promise<Response> {
+ return POST(
+ new Request("http://localhost/api/media/fetch-window", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+}
+const ask = (videoId: string, extra: Record<string, unknown> = {}) =>
+ post({ channelSlug: SLUG, videoId, requestedBy: "test", from: 1, to: 3, ...extra });
+
+const targets = async () =>
+ (await readFile(ARGS_LOG, "utf8").catch(() => ""))
+ .trim()
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => (JSON.parse(l) as string[]).at(-1));
+
+async function settle(jobId: string): Promise<string | undefined> {
+ 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));
+ }
+ return reg.get(jobId)?.status;
+}
+
+test("a storedUrl that is not a mode is refused with 400", async () => {
+ const res = await ask("s1", { storedUrl: "always" });
+ assert.equal(res.status, 400);
+ assert.match(((await res.json()) as { error: string }).error, /storedUrl must be one of "never", "fallback", "only"/);
+});
+
+test("fallback, the platform answering: the page 429s, then the window is cut from the stored URL", async () => {
+ const res = await ask("s1", { storedUrl: "fallback" });
+ assert.equal(res.status, 202);
+ const { jobId } = (await res.json()) as { jobId: string };
+ assert.equal(await settle(jobId), "done");
+ assert.equal(getRegistry().get(jobId)?.spec?.params?.storedUrl, "fallback", "a Retry keeps the mode");
+ assert.deepEqual(await targets(), [page("s1"), cdn("s1")], "the page first, then the stored file");
+ const sidecar = JSON.parse(await readFile(path.join(S1, "clips", "1.00-3.00.json"), "utf8"));
+ assert.equal(sidecar.source, "stored-media-url");
+ assert.equal(sidecar.sourceHost, "player.odycdn.com");
+});
+
+test("never (the default), the platform cooling after that 429: refused with 409", async () => {
+ const res = await ask("s2");
+ assert.equal(res.status, 409);
+ const body = (await res.json()) as { error: string; platform: string };
+ assert.equal(body.platform, "odysee");
+ assert.match(body.error, /rate-limit cooldown/);
+});
+
+test("fallback with no stored URL, the platform cooling: refused as before", async () => {
+ const res = await ask("n1", { storedUrl: "fallback" });
+ assert.equal(res.status, 409);
+});
+
+test("only, the platform cooling: cut from the stored URL with no page request", async () => {
+ const before = (await targets()).length;
+ const res = await ask("s2", { storedUrl: "only" });
+ assert.equal(res.status, 202);
+ const { jobId } = (await res.json()) as { jobId: string };
+ assert.equal(await settle(jobId), "done");
+ assert.deepEqual((await targets()).slice(before), [cdn("s2")]);
+ const sidecar = JSON.parse(await readFile(path.join(S2, "clips", "1.00-3.00.json"), "utf8"));
+ assert.equal(sidecar.source, "stored-media-url");
+});
diff --git a/editor/app/api/media/fetch-window/route.ts b/editor/app/api/media/fetch-window/route.ts
@@ -9,6 +9,10 @@ import {
} from "yt-dlp-transcript-common/lib/clipWindow";
import { sourceVideoQualityForMaxHeight } from "yt-dlp-transcript-common/ytdlp/downloadFormat";
import {
+ STORED_URL_MODES,
+ isStoredUrlMode,
+} from "yt-dlp-transcript-common/lib/storedMediaUrl";
+import {
fetchFullSourceAction,
fetchWindowAction,
type FetchMediaOutcome,
@@ -54,6 +58,7 @@ type Body = {
pad?: unknown;
full?: unknown;
maxHeight?: unknown;
+ storedUrl?: unknown;
};
const str = (v: unknown): string | undefined =>
@@ -169,6 +174,18 @@ export async function POST(request: Request) {
);
}
+ // CUT FROM THE STORED MEDIA URL (release 32 R6): "never" (default) |
+ // "fallback" | "only" — the fetch-windows batch's rule for one window
+ // (lib/storedMediaUrl.ts). A window only: a whole recording ignores it.
+ const storedUrl =
+ body.storedUrl === undefined || body.storedUrl === null ? undefined : body.storedUrl;
+ if (storedUrl !== undefined && !isStoredUrlMode(storedUrl)) {
+ return NextResponse.json(
+ { error: `storedUrl must be one of ${STORED_URL_MODES.map((m) => `"${m}"`).join(", ")}` },
+ { status: 400 },
+ );
+ }
+
if (body.full === true) {
// A cap at or under 720 asks for "video_720"; one above it asks for
// "original" in so many words. No cap: the channel's, else the global,
@@ -221,6 +238,7 @@ export async function POST(request: Request) {
to,
provenance,
maxHeight,
+ ...(storedUrl ? { storedUrl } : {}),
}),
);
}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -86,9 +86,18 @@ import {
savedWindowSource,
} from "yt-dlp-transcript-common/lib/savedVideoWindow-server";
import {
+ FetchWindowError,
fetchWindowManaged,
type FetchWindowProvenance,
} from "yt-dlp-transcript-common/ytdlp/fetchWindowManaged";
+import {
+ isStoredUrlPlatform,
+ type StoredMediaUrl,
+ type StoredUrlMode,
+ type StoredUrlWhy,
+} from "yt-dlp-transcript-common/lib/storedMediaUrl";
+import { storedMediaUrl } from "yt-dlp-transcript-common/lib/storedMediaUrl-server";
+import { CLIP_WINDOW_MIN_GAP_SECONDS } from "yt-dlp-transcript-common/controller/fetchWindows";
import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration";
import { detectPlatform } from "yt-dlp-transcript-common/lib/platform";
import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId";
@@ -1098,6 +1107,9 @@ export async function fetchWindowAction(req: {
// Hand back the StreamActionResult instead of detaching it. Set by Retry,
// which renders the log; the HTTP route leaves it off and polls.
stream?: boolean;
+ // CUT FROM THE STORED MEDIA URL (release 32 R6; the batch's rule, release 32
+ // R5, controller/fetchWindows.ts): "never" (default) | "fallback" | "only".
+ storedUrl?: StoredUrlMode;
}): Promise<FetchMediaOutcome> {
const { slug, from, to } = req;
// THE CAP IS CHECKED HERE TOO, not only at the HTTP door. Retry re-runs from
@@ -1250,13 +1262,26 @@ export async function fetchWindowAction(req: {
// handful of seconds, but a 429 is a fact about the SOURCE, not about the
// size of the request.
const platform = detectPlatform(url) ?? "unknown";
+ // THE STORED MEDIA URL (release 32 R6), the batch's rule for one window: asked
+ // only when the request opted in, for an allowlisted platform whose page the
+ // URL is. `only` cuts from it without asking the page; a held or cooling
+ // platform does not refuse a window that has one (it asks no page); without
+ // one, the window goes the usual way.
+ const storedMode = req.storedUrl ?? "never";
+ const stored: StoredMediaUrl | null =
+ storedMode !== "never" && isStoredUrlPlatform(platform)
+ ? await storedMediaUrl(videoDir).then((s) => (s && s.platform === platform ? s : null))
+ : null;
// A held platform's refusal names the hold and the next probe (release 17).
const held = await heldPlatformRefusal(platform, "This fetch", paths);
const cooldownMs = await platformCooldownRemainingMs(platform, paths);
- if (held && cooldownMs > 0) {
+ let via: StoredUrlWhy | null = stored && storedMode === "only" ? "only" : null;
+ if (!via && stored && (held || cooldownMs > 0)) via = held ? "held" : "rate-limited";
+ if (via) {
+ // No page is asked: neither the hold nor the cooldown is this fetch's.
+ } else if (held && cooldownMs > 0) {
return { ok: false, status: 409, cooldownMs, platform, error: held };
- }
- if (cooldownMs > 0) {
+ } else if (cooldownMs > 0) {
return {
ok: false,
status: 409,
@@ -1297,29 +1322,56 @@ export async function fetchWindowAction(req: {
webpageUrl: url,
queueKey: req.queueKey,
...(req.maxHeight !== undefined ? { maxHeight: req.maxHeight } : {}),
+ // A Retry keeps the mode it was asked with.
+ ...(storedMode !== "never" ? { storedUrl: storedMode } : {}),
...req.provenance,
},
},
fn: async (onLog, signal) => {
onLog(`${requesterLine(req.provenance)}\n`);
- await fetchWindowManaged({
- channelSlug: slug,
- channelConfig: r.config,
- paths,
- videoDir,
- videoId,
- videoUrl: url,
- // The channel root, as every other yt-dlp invocation here runs.
- cwd: path.join(paths.channelsDir, slug),
- from,
- to,
- provenance: req.provenance,
- maxHeight: req.maxHeight,
- cookiePolicy: resolveCookiePolicy(settings, r.config),
- onLog,
- signal,
- onPlatformBackoff: () => recordDownloadBackoff(platform, paths),
- });
+ const once = (target: (StoredMediaUrl & { why: StoredUrlWhy }) | null) =>
+ fetchWindowManaged({
+ channelSlug: slug,
+ channelConfig: r.config,
+ paths,
+ videoDir,
+ videoId,
+ videoUrl: url,
+ ...(target ? { storedMedia: target } : {}),
+ // The channel root, as every other yt-dlp invocation here runs.
+ cwd: path.join(paths.channelsDir, slug),
+ from,
+ to,
+ provenance: req.provenance,
+ maxHeight: req.maxHeight,
+ cookiePolicy: resolveCookiePolicy(settings, r.config),
+ onLog,
+ signal,
+ onPlatformBackoff: () => recordDownloadBackoff(platform, paths),
+ });
+ if (via && stored) {
+ await once({ ...stored, why: via });
+ } else {
+ try {
+ await once(null);
+ } catch (e) {
+ // FALLBACK: the page lookup rate-limited (the backoff is already
+ // recorded) and the record stores its media URL — cut from that,
+ // after the clip gap: one stream, real gaps.
+ if (
+ !(stored && storedMode === "fallback" && e instanceof FetchWindowError && e.failureClass === "rate_limit")
+ ) {
+ throw e;
+ }
+ const gapMs = storedFallbackGapMs();
+ onLog(
+ `${platform} rate-limited the page lookup — cutting from the stored media URL ` +
+ `(${stored.host}) instead, after ${Math.round(gapMs / 1000)}s.\n`,
+ );
+ await abortableSleep(gapMs, signal);
+ await once({ ...stored, why: "rate-limited" });
+ }
+ }
safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
},
});
@@ -1342,6 +1394,31 @@ export async function fetchWindowAction(req: {
};
}
+// The pause before a single window's stored-URL fallback: the batch's clip gap
+// (CLIP_WINDOW_MIN_GAP_SECONDS), or E2E_CLIP_WINDOW_GAP_MS on the e2e server.
+function storedFallbackGapMs(): number {
+ const raw = Number(process.env.E2E_CLIP_WINDOW_GAP_MS);
+ return process.env.E2E_CLIP_WINDOW_GAP_MS !== undefined && Number.isFinite(raw) && raw >= 0
+ ? raw
+ : CLIP_WINDOW_MIN_GAP_SECONDS * 1000;
+}
+
+function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
+ if (ms <= 0) return Promise.resolve();
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) return reject(new Error("Cancelled"));
+ const t = setTimeout(() => {
+ signal.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(t);
+ reject(new Error("Cancelled"));
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
// Retry, from the /jobs page. A replayed fetch re-derives from the CURRENT
// disk: a window somebody has since fetched (or that a wider one now covers)
// replays as a neutral "already there" rather than downloading it twice.
@@ -1354,6 +1431,7 @@ export async function replayFetchWindowAction(req: {
provenance: FetchWindowProvenance;
queueKey?: string;
maxHeight?: number;
+ storedUrl?: StoredUrlMode;
}): Promise<StreamActionResult> {
const r = await fetchWindowAction({ ...req, stream: true });
if (!r.ok) return { ok: false, error: r.error, info: r.status === 409 };
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -210,6 +210,7 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
},
queueKey,
maxHeight: num(p.maxHeight),
+ ...(isStoredUrlMode(p.storedUrl) ? { storedUrl: p.storedUrl } : {}),
});
},
// A batch of windows. Replay re-runs the same list on the same queue; the
diff --git a/editor/app/sites/components/FetchMissingEvidenceButton.tsx b/editor/app/sites/components/FetchMissingEvidenceButton.tsx
@@ -1,9 +1,15 @@
"use client";
import Link from "next/link";
-import { useState, useTransition } from "react";
+import { useId, useState, useTransition } from "react";
import { Button } from "yt-dlp-transcript-common/components/ui/button";
import {
+ STORED_URL_HELP,
+ STORED_URL_LABEL,
+ STORED_URL_UI_MODE,
+ isStoredUrlPlatform,
+} from "yt-dlp-transcript-common/lib/storedMediaUrl";
+import {
fetchMissingArticleEvidenceAction,
fetchMissingEvidenceAction,
type FetchMissingEvidenceResult,
@@ -15,16 +21,29 @@ import {
// anything. It is not a streamed log because a run can start two jobs (YouTube
// and Rumble side by side); each is linked, and its log is on /jobs.
// `articles` instead of a site: the published articles' (release 26).
+//
+// "Cut from the stored media URL" (release 32 R6; fetch-windows `storedUrl`,
+// lib/storedMediaUrl.ts) is offered once a preview or a run shows windows on a
+// platform that has one (Odysee): the preview always counts them (a dry run asks
+// with the mode, which starts nothing), and a refused group of such a platform
+// offers it too. Off by default; ticked, the run asks "fallback".
export function FetchMissingEvidenceButton(props: { siteId: string } | { articles: true }) {
const [pending, start] = useTransition();
const [result, setResult] = useState<FetchMissingEvidenceResult | null>(null);
+ const [offer, setOffer] = useState(false);
+ const [stored, setStored] = useState(false);
+ const helpId = useId();
const run = (dryRun: boolean) => {
start(async () => {
- setResult(
+ // A preview counts the stored URLs whatever the box says; a run asks
+ // with them only when it is ticked.
+ const storedUrl = dryRun || (offer && stored) ? STORED_URL_UI_MODE : undefined;
+ const r =
"siteId" in props
- ? await fetchMissingEvidenceAction(props.siteId, { dryRun })
- : await fetchMissingArticleEvidenceAction({ dryRun }),
- );
+ ? await fetchMissingEvidenceAction(props.siteId, { dryRun, storedUrl })
+ : await fetchMissingArticleEvidenceAction({ dryRun, storedUrl });
+ setResult(r);
+ if (offersStoredUrl(r)) setOffer(true);
});
};
return (
@@ -37,11 +56,38 @@ export function FetchMissingEvidenceButton(props: { siteId: string } | { article
{pending ? "Working…" : "Fetch missing evidence"}
</Button>
</div>
+ {offer && (
+ <label className="flex max-w-prose items-start gap-2 text-sm" data-stored-url-option="">
+ <input
+ type="checkbox"
+ className="mt-1"
+ checked={stored}
+ onChange={(e) => setStored(e.target.checked)}
+ aria-describedby={helpId}
+ />
+ <span>
+ {STORED_URL_LABEL}
+ <span id={helpId} className="block text-xs text-muted-foreground">
+ {STORED_URL_HELP}
+ </span>
+ </span>
+ </label>
+ )}
{result && <FetchSummary result={result} />}
</div>
);
}
+// Windows on a stored-URL platform: a group with stored URLs, or a refused group
+// of such a platform (the run was asked without the box).
+function offersStoredUrl(r: FetchMissingEvidenceResult): boolean {
+ if (!r.ok) return false;
+ return (
+ r.groups.some((g) => (g.storedUrlItems ?? 0) > 0) ||
+ r.refused.some((x) => isStoredUrlPlatform(x.platform))
+ );
+}
+
function FetchSummary({ result }: { result: FetchMissingEvidenceResult }) {
if (!result.ok) {
return (
@@ -62,6 +108,7 @@ function FetchSummary({ result }: { result: FetchMissingEvidenceResult }) {
? result.groups.map((g) => (
<p key={g.queueKey} className="text-muted-foreground">
{g.platform}: {g.items.length} window(s) on {g.queueKey}
+ {(g.storedUrlItems ?? 0) > 0 && <> · {g.storedUrlItems} with a stored media URL</>}
</p>
))
: result.jobs.map((j) => (