commit 4aa03f6959a510808f06cc38077abd18c2ea24aa parent 41339c006609cab14a8f5a536450433ac99341e8 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 17 Oct 2026 01:38:58 -0400 editor: the browser lookup in the UI and over ops — the video page's "Read from the page" (Odysee channels), the Playlist stage's "List from the page" and "Read records from their pages", the Configure form's Browser lookup checkbox, POST /api/ops/browser-lookup {slug, ids?, listing?, scrolls?}, Retry; e2e browser-lookup.spec.ts over recorded page reads; ops help, COMMANDS.md Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
16 files changed, 465 insertions(+), 0 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md @@ -108,6 +108,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` | | `metadata-scan` | metadata-scan reads every listed video's title, date and description into the channel's scan file, fetching no media: {"slug"}. Not held by the download pause and needs no disk floor; one request per video, so it respects the platform's cooldown and records one when pushed back. | `pnpm ops metadata-scan --json '{"slug":"the-quartering"}'` | | `refresh-metadata` | refresh-metadata re-reads ONE video's metadata.info.json from its source (no subtitles, no media) on the platform's queue: {"slug", "id"}. The job's log ends with what the source now says — live\_status, formats, audio-only formats and whether any is non-fragmented, English captions, the keys that changed. An id with no data/<id>/ is refused (a refresh re-reads a video already archived), as are archive.org and Wayback records. | `pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait` | +| `browser-lookup` | browser-lookup reads Odysee records from their pages in a headless browser, for when yt-dlp's lookup answers 429: {"slug", "ids": \[...\]} (at most 50) writes each record (none yet: whole, `_source: "browser"`) or completes it (the keys it lacks, and the one media file the page's player asked for); "listing": true (with "scrolls", default 5, at most 40) adds the uploads the channel page shows to the playlist, newest first, through the title match filter. One page a minute; not refused for a held platform. The log ends with a `summary: {...}` line. | `pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait`<br>`pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait` | | `import-video` | import-video imports one video by URL into a channel: {"slug", "url"}. An archive.org URL becomes its canonical item or file (an item of several media files is refused — see import-archive-org); a BitChute or Odysee URL runs on that platform's queue at its pace, refused while it is held or cooling down, and refused when already on disk; a Wayback capture is named by what it copies. | `pnpm ops import-video --json '{"slug":"demo-archive","url":"https://archive.org/details/example-item"}'` | | `import-archive-org` | import-archive-org imports archive.org media into a channel, as one job on archive.org's queue: {"slug", "item", "files": \[...\] \| "match": "<regex>"} for one item; {"slug", "items": \["<id>" \| {"item", "files"? \| "match"?}, ...\]} for many (a bare id takes "match", else every media original); or {"slug", "query": "<archive.org search>", "limit"?: 100} for the first items a search finds (at most 500). One file at a time, a jittered pause between files and between items; a record already held (on disk, or in the saved-video store) is skipped. "dryRun": true lists each file as held, RESTRICTED (archive.org marks it not for download: a fetch would answer 401/403) or would get, and fetches nothing. A 401/403 skips the rest of its item; three such items in a row, a 429 or three failures in a row stop the job. The log ends with a summary: line; a re-run resumes. | `pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait`<br>`pnpm ops import-archive-org --json '{"slug":"demo-archive","query":"collection:example-collection","dryRun":true}' --wait` | | `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | | diff --git a/editor/app/api/ops/browser-lookup/route.test.ts b/editor/app/api/ops/browser-lookup/route.test.ts @@ -0,0 +1,104 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + cdnUrlOf, + channelPageRead, + channelUrlOf, + pageUrlOf, + syntheticChannel, + syntheticClaim, + videoPageRead, +} from "yt-dlp-transcript-common/testing/web/fakeOdyseePage.mjs"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/browser-lookup/route.test.ts" +// +// `/api/ops/browser-lookup` (release 32 R9) end to end: the body's checks, the +// door, and the job over recorded page reads (E2E_ODYSEE_PAGE_FIXTURE — no +// browser, no network): a record completed with the file its page named, and +// a listing added to the top of the playlist. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "browser-lookup-route-")); +const SLUG = "demo-odysee"; +const FIXTURE = path.join(ROOT, "pages.json"); +const ch = syntheticChannel({ name: "@demo", title: "Demo" }); +const v1 = syntheticClaim({ name: "stream-one", title: "Stream One", channel: ch, releaseTime: 1700000000 }); +const v2 = syntheticClaim({ name: "stream-two", title: "Stream Two", channel: ch, releaseTime: 1700300000 }); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.E2E_ODYSEE_PAGE_FIXTURE = FIXTURE; +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +await writeFile( + FIXTURE, + JSON.stringify({ + [pageUrlOf(v1)]: videoPageRead({ claim: v1 }), + [channelUrlOf(ch)]: channelPageRead({ channel: ch, pages: [[v2, v1]] }), + }), +); +const CHANNEL = path.join(ROOT, "channels", SLUG); +await mkdir(path.join(CHANNEL, "data", v1.claim_id), { recursive: true }); +await writeFile( + path.join(CHANNEL, "config.json"), + JSON.stringify({ name: "Demo", handling: "transcribe", url: channelUrlOf(ch), platform: "odysee" }), +); +await writeFile(path.join(CHANNEL, "playlist"), `${pageUrlOf(v1)}\n`); +await writeFile( + path.join(CHANNEL, "data", v1.claim_id, "metadata.info.json"), + JSON.stringify({ id: v1.claim_id, title: "Stream One", webpage_url: pageUrlOf(v1), extractor: "lbry" }), +); + +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/ops/browser-lookup", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); +} + +async function settle(jobId: string): Promise<string | undefined> { + const reg = getRegistry(); + for (let i = 0; i < 400; 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("the body: ids or listing, scrolls bounded", async () => { + assert.equal((await post({ slug: SLUG })).status, 400); + assert.equal((await post({ slug: SLUG, listing: true, scrolls: 41 })).status, 400); + assert.equal((await post({ slug: SLUG, ids: [] })).status, 400); +}); + +test("ids: the record is completed with the file its page named", async () => { + const res = await post({ slug: SLUG, ids: [v1.claim_id] }); + assert.equal(res.status, 200, await res.clone().text()); + const { jobId } = (await res.json()) as { jobId: string }; + assert.equal(await settle(jobId), "done"); + assert.deepEqual(getRegistry().get(jobId)?.spec?.params?.videoIds, [v1.claim_id], "a Retry keeps the ids"); + const info = JSON.parse(await readFile(path.join(CHANNEL, "data", v1.claim_id, "metadata.info.json"), "utf8")); + assert.equal(info.formats[0].url, cdnUrlOf(v1)); + assert.equal(info.title, "Stream One"); + const history = JSON.parse(await readFile(path.join(CHANNEL, "data", v1.claim_id, "metadata.history.json"), "utf8")); + assert.equal(history.entries.at(-1).by, "browser-lookup"); +}); + +test("listing: the page's new uploads go to the top of the playlist", async () => { + const res = await post({ slug: SLUG, listing: true, scrolls: 2 }); + assert.equal(res.status, 200, await res.clone().text()); + const { jobId } = (await res.json()) as { jobId: string }; + assert.equal(await settle(jobId), "done"); + const playlist = (await readFile(path.join(CHANNEL, "playlist"), "utf8")).trim().split("\n"); + assert.deepEqual(playlist, [pageUrlOf(v2), pageUrlOf(v1)]); +}); diff --git a/editor/app/api/ops/browser-lookup/route.ts b/editor/app/api/ops/browser-lookup/route.ts @@ -0,0 +1,48 @@ +import { browserLookupAction } from "../../../channels/[slug]/browserLookupActions"; +import { + OpsInputError, + jobResponse, + ops, + optBool, + optPositiveInt, + optString, + reqSlug, + reqStringArray, +} from "../_lib"; +import { PAGE_READ_MAX_SCROLLS } from "yt-dlp-transcript-common/ytdlp/odyseePageReader"; + +export const dynamic = "force-dynamic"; + +// POST { slug, ids?: ["<videoId>", …], listing?: true, scrolls?, queueKey? } +// -> { ok: true, jobId } +// +// An Odysee record read from its page in a headless browser (release 32 R9), +// for when yt-dlp's lbry lookup is refused: each named video's page is opened +// and played, its claim and the file the player asks for are read out of the +// page's own API answers, and its metadata.info.json is written (none yet: +// whole, `_source: "browser"`) or completed (only what it lacks, and the one +// stored format; in metadata.history.json as `browser-lookup`). `listing: +// true` opens the channel's page, scrolls it `scrolls` times (default 5, at +// most 40) and adds the uploads its playlist lacks at the top, newest first, +// through the channel's title match filter. One page a minute, on the +// platform's queue; not refused for a held platform. The log ends with a +// `summary: {…}` line. At most 50 ids. +export async function POST(request: Request) { + return ops(request, ["slug", "ids", "listing", "scrolls", "queueKey"], async (body) => { + const ids = body.ids === undefined ? undefined : reqStringArray(body, "ids"); + const listing = optBool(body, "listing"); + if (!ids && !listing) throw new OpsInputError('Send "ids" (videos to look up) or "listing": true'); + const scrolls = optPositiveInt(body, "scrolls"); + if (scrolls !== undefined && scrolls > PAGE_READ_MAX_SCROLLS) { + throw new OpsInputError(`"scrolls" must be at most ${PAGE_READ_MAX_SCROLLS}`); + } + return jobResponse( + await browserLookupAction(reqSlug(body, "slug"), { + ...(ids ? { ids } : {}), + ...(listing ? { listing: true } : {}), + ...(scrolls !== undefined ? { scrolls } : {}), + ...(optString(body, "queueKey") ? { queueKey: optString(body, "queueKey") } : {}), + }), + ); + }); +} diff --git a/editor/app/channels/[slug]/browserLookupActions.ts b/editor/app/channels/[slug]/browserLookupActions.ts @@ -0,0 +1,41 @@ +"use server"; + +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; +import { runBrowserLookupJob } from "yt-dlp-transcript-common/controller/browserLookupJob"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; + +// THE BROWSER LOOKUP (release 32 R9): an Odysee video's record, or the +// channel's listing, read from its page in a headless browser when yt-dlp's +// lookup is refused — the `browser-lookup` job, as the video page's "Read from +// the page", the Playlist stage's "List from the page" and `pnpm ops +// browser-lookup` (`/api/ops/browser-lookup`) ask for it. The work and its +// refusals are common/controller/browserLookupJob.ts. +export async function browserLookupAction( + slug: string, + req: { ids?: string[]; listing?: boolean; scrolls?: number; queueKey?: string }, +): Promise<StreamActionResult> { + const paths = getPaths(); + const channelConfig = await readChannelConfig(paths, slug); + if (!channelConfig) return { ok: false, error: `Channel "${slug}" not found` }; + const ids = (req.ids ?? []).map((s) => s.trim()).filter(Boolean); + return runBrowserLookupJob({ + paths, + slug, + channelConfig, + ...(ids.length ? { videoIds: ids } : {}), + ...(req.listing ? { listing: true } : {}), + ...(req.scrolls !== undefined ? { scrolls: req.scrolls } : {}), + skipLiveDownloads: getSettings().skipLiveDownloads, + ...(req.queueKey ? { queueKey: req.queueKey } : {}), + requestedBy: "editor", + afterRun: () => { + safeRevalidate([ + `/channels/${slug}`, + ...ids.map((id) => `/channels/${slug}/videos/${id}`), + ]); + }, + }); +} diff --git a/editor/app/channels/[slug]/components/BrowserLookupSection.tsx b/editor/app/channels/[slug]/components/BrowserLookupSection.tsx @@ -0,0 +1,77 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../jobs/actions"; +import { browserLookupAction } from "../browserLookupActions"; + +// THE BROWSER LOOKUP ON THE PLAYLIST STAGE (release 32 R9), for an Odysee +// channel: the listing and a list of records read from the pages in a +// headless browser, for when yt-dlp's lookup answers 429. Both are the +// `browser-lookup` job (common/controller/browserLookupJob.ts). +export function BrowserLookupSection({ slug }: { slug: string }) { + const [scrolls, setScrolls] = useState("5"); + const [ids, setIds] = useState(""); + const idList = ids + .split(/[\s,]+/) + .map((s) => s.trim()) + .filter(Boolean); + const scrollCount = Math.min(40, Math.max(1, Math.floor(Number(scrolls) || 5))); + return ( + <> + <div className="flex flex-col gap-2" data-browser-listing> + <div> + <h3 className="text-base font-semibold">List from the page</h3> + <p className="text-sm text-muted-foreground"> + Open the channel's Odysee page in a headless browser and add the uploads it shows to the + playlist, newest first — for when Store playlist and Sync are refused. Nothing is removed and + nothing is downloaded; the channel's title match filter applies. + </p> + </div> + <label className="flex items-center gap-2 text-sm"> + <span>Scroll the page</span> + <input + type="number" + min={1} + max={40} + value={scrolls} + onChange={(e) => setScrolls(e.target.value)} + aria-label="page scrolls" + className="w-20 rounded border border-border bg-card px-2 py-1 text-sm" + /> + <span className="text-muted-foreground">times</span> + </label> + <StreamActionLog + trigger={() => browserLookupAction(slug, { listing: true, scrolls: scrollCount })} + cancelAction={cancelJobAction} + buttonLabel="List from the page" + runningLabel="Reading the channel page…" + /> + </div> + <div className="flex flex-col gap-2" data-browser-records> + <div> + <h3 className="text-base font-semibold">Read records from their pages</h3> + <p className="text-sm text-muted-foreground"> + Each video's Odysee page, one a minute: its record is written (or completed) with the media + file the page's player asks for, which a stored-URL download then reads. Up to 50 ids. + </p> + </div> + <textarea + value={ids} + onChange={(e) => setIds(e.target.value)} + rows={3} + aria-label="video ids to read from their pages" + placeholder="one claim id per line" + className="rounded border border-border bg-card px-2 py-1 font-mono text-xs" + /> + <StreamActionLog + trigger={() => browserLookupAction(slug, { ids: idList })} + cancelAction={cancelJobAction} + buttonLabel={idList.length ? `Read ${idList.length} from the pages` : "Read from the pages"} + runningLabel="Reading the pages…" + disabled={idList.length === 0 || idList.length > 50} + /> + </div> + </> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/PlaylistStage.tsx b/editor/app/channels/[slug]/components/stages/PlaylistStage.tsx @@ -12,6 +12,7 @@ import { } from "../../pipelineActions"; import type { MetadataScanRun } from "yt-dlp-transcript-common/controller/metadataScanStore"; import type { MetadataScanView } from "../../lib/metadataScanView"; +import { BrowserLookupSection } from "../BrowserLookupSection"; type Props = { slug: string; @@ -19,6 +20,8 @@ type Props = { defaultQueueKey: string; existingQueues: string[]; metadataScan: MetadataScanView; + // Release 32 R9: an Odysee channel offers the browser lookup. + browserLookup?: boolean; }; export function PlaylistStage({ @@ -27,6 +30,7 @@ export function PlaylistStage({ defaultQueueKey, existingQueues, metadataScan, + browserLookup, }: Props) { const [storeQueue, setStoreQueue] = useState(defaultQueueKey); const [syncQueue, setSyncQueue] = useState(defaultQueueKey); @@ -119,6 +123,7 @@ export function PlaylistStage({ } /> </div> + {browserLookup && <BrowserLookupSection slug={slug} />} <div className="flex flex-col gap-2"> <Heading title="Import single video" diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -484,6 +484,7 @@ export default async function ChannelDetailPage({ <PlaylistStage slug={slug} hasUrl={!!config!.url} + browserLookup={(config!.platform ?? detectUrlPlatform(config!.url ?? null)) === "odysee"} defaultQueueKey={platformDefaultQueueKey} existingQueues={existingQueues} metadataScan={{ diff --git a/editor/app/channels/[slug]/videos/[id]/components/BrowserLookupControl.tsx b/editor/app/channels/[slug]/videos/[id]/components/BrowserLookupControl.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import { cancelJobAction } from "../../../../../jobs/actions"; +import { browserLookupAction } from "../../../browserLookupActions"; + +// "Read from the page" (release 32 R9): an Odysee video's record read from its +// page in a headless browser, for when yt-dlp's lookup is refused (a 429). The +// record gains what it lacks — and the media file the page's player asked for, +// which the stored-URL download then reads. Offered on an Odysee record only; +// the job's log names what it wrote. +export function BrowserLookupControl({ slug, videoId }: { slug: string; videoId: string }) { + return ( + <StreamActionLog + trigger={() => browserLookupAction(slug, { ids: [videoId] })} + cancelAction={cancelJobAction} + buttonLabel="Read from the page" + runningLabel="Reading the page…" + label={`Read ${videoId} from its Odysee page`} + /> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -58,6 +58,9 @@ import { type AudioIntegrityRecord, } from "yt-dlp-transcript-common/lib/audioIntegrity"; import { RefreshMetadataControl } from "./components/RefreshMetadataControl"; +import { BrowserLookupControl } from "./components/BrowserLookupControl"; +import { BROWSER_LOOKUP_PLATFORMS } from "yt-dlp-transcript-common/ytdlp/odyseeBrowserLookup"; +import { detectPlatform as detectPagePlatform } from "yt-dlp-transcript-common/lib/platform"; import { loadVideoTags } from "./lib/videoTags"; import { loadVideoOperationPanels } from "./lib/videoOperationPanels"; import { channelTextStall } from "yt-dlp-transcript-common/lib/channelMedia"; @@ -372,6 +375,11 @@ export default async function VideoDetailPage({ existingQueues={existingQueues} /> )} + {/* Release 32 R9: an Odysee channel's record read from its page in a + headless browser, for when yt-dlp's lookup is refused. */} + {BROWSER_LOOKUP_PLATFORMS.includes(config.platform ?? detectPagePlatform(config.url ?? null) ?? "") && ( + <BrowserLookupControl slug={slug} videoId={id} /> + )} </header> <RunningJobsList jobs={activeJobs} hideChannelSlug hideVideoId /> diff --git a/editor/app/channels/components/ChannelForm.tsx b/editor/app/channels/components/ChannelForm.tsx @@ -743,6 +743,28 @@ export function ChannelForm({ new file per 20 minutes on the platform. </span> </label> + <label className="flex items-start gap-2 text-sm"> + <input + type="checkbox" + name="browserLookup" + aria-label="browser lookup" + defaultChecked={seedChecked(state, "browserLookup", c?.browserLookup === true)} + className="mt-1" + /> + <span className="flex flex-col gap-0.5"> + <span className="font-medium"> + Browser lookup{" "} + <span className="text-muted-foreground font-normal"> + (with stored media URL downloads, Odysee) + </span> + </span> + <span className="text-xs text-muted-foreground"> + When a video's record names no media file, read it from the + video's page in a headless browser first, then download from + the file the page names. One page a minute. + </span> + </span> + </label> </Section> <Section title="Retention & persistence"> <label className="flex flex-col gap-1 text-sm"> diff --git a/editor/app/channels/components/channelConfigToForm.ts b/editor/app/channels/components/channelConfigToForm.ts @@ -23,6 +23,7 @@ import { AUDIO_CHECK_PLATFORMS } from "yt-dlp-transcript-common/lib/audioCheckPo // The checkbox-shaped fields (presence, not value). export const CHANNEL_FORM_FLAGS = [ "keepSourceVideo", + "browserLookup", "downloadFilterIncludeLivestreams", "audioCheckEnabled", "audioCheckResumeDuringProbe", @@ -107,6 +108,7 @@ export function channelConfigToFormData(config: ChannelConfig): FormData { put(fd, "cookiesFromBrowser", config.cookiesFromBrowser); put(fd, "cookieMode", config.cookieMode); put(fd, "storedUrlDownloads", config.storedUrlDownloads); + if (config.browserLookup) fd.set("browserLookup", "on"); put(fd, "downloadFilterInclude", config.downloadFilter?.include); put(fd, "downloadFilterExclude", config.downloadFilter?.exclude); if (config.downloadFilter?.includeLivestreams) { diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts @@ -136,3 +136,19 @@ test("the form writes storedUrlDownloads; Never clears it; the ops patch round-t applyChannelFormPatch(back, { storedUrlDownloads: "" }); assert.equal("storedUrlDownloads" in parseChannelForm(back).config, false); }); + +// The browser lookup (release 32 R9): a checkbox — checked writes `true`, +// unchecked writes nothing; the ops patch round-trips it. +test("the form writes browserLookup from its checkbox; unchecked clears it; the ops patch round-trips", () => { + assert.equal(parseChannelForm(form({ browserLookup: "on" })).config.browserLookup, true); + assert.equal("browserLookup" in parseChannelForm(form({})).config, false); + assert.ok((CHANNEL_FORM_FIELDS as readonly string[]).includes("browserLookup")); + const fd = channelConfigToFormData({ handling: "transcribe", name: "Synth", url: ODYSEE }); + applyChannelFormPatch(fd, { browserLookup: true }); + const set = parseChannelForm(fd).config; + assert.equal(set.browserLookup, true); + const back = channelConfigToFormData(set); + assert.equal(back.get("browserLookup"), "on"); + applyChannelFormPatch(back, { browserLookup: false }); + assert.equal("browserLookup" in parseChannelForm(back).config, false); +}); diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts @@ -62,6 +62,7 @@ export const CHANNEL_FORM_FIELDS = [ "cookieMode", "audioCheck", "storedUrlDownloads", + "browserLookup", "downloadFilter", "recordedDate", "mirror", @@ -228,6 +229,8 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { const storedUrlRaw = String(formData.get("storedUrlDownloads") ?? "").trim(); const storedUrlDownloads = isStoredUrlMode(storedUrlRaw) && storedUrlRaw !== "never" ? storedUrlRaw : undefined; + // The browser lookup (release 32 R9): a checkbox; unchecked = omitted. + const browserLookup = formData.get("browserLookup") != null; // Download filter. Both patterns are regex SOURCES compiled with "i" at // download time, so the form is the place that refuses an unparseable one: @@ -409,6 +412,7 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm { if (cookieMode) config.cookieMode = cookieMode; if (audioCheck) config.audioCheck = audioCheck; if (storedUrlDownloads) config.storedUrlDownloads = storedUrlDownloads; + if (browserLookup) config.browserLookup = true; if (downloadFilter) config.downloadFilter = downloadFilter; if (recordedDateTitlePattern) { config.recordedDate = { titlePattern: recordedDateTitlePattern }; diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -60,6 +60,7 @@ import { replayFetchWindowAction, } from "../channels/[slug]/videos/[id]/videoActions"; import { fetchWindowsJobAction } from "../channels/[slug]/videos/fetchWindowsAction"; +import { browserLookupAction } from "../channels/[slug]/browserLookupActions"; import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows"; import { reportsPrepareAction } from "../sites/lib/reportsPrepareAction"; import { reportsExportAction } from "../sites/lib/reportsExportAction"; @@ -366,6 +367,18 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { } return refreshVideoMetadataAction(spec.slug, videoId, queueKey); }, + // An Odysee record (or the listing) read from its page in a browser: the + // ids and the listing flag as asked; the action re-checks the door. + "browser-lookup": (spec) => { + const { p, queueKey } = params(spec); + const ids = Array.isArray(p.videoIds) ? p.videoIds.filter((x): x is string => typeof x === "string") : []; + return browserLookupAction(spec.slug, { + ...(ids.length ? { ids } : {}), + ...(p.listing === true ? { listing: true } : {}), + ...(num(p.scrolls) !== undefined ? { scrolls: num(p.scrolls) } : {}), + ...(queueKey ? { queueKey } : {}), + }); + }, "check-post-availability": (spec) => { const { p, queueKey } = params(spec); return checkPostAvailabilityAction( diff --git a/editor/e2e/browser-lookup.spec.ts b/editor/e2e/browser-lookup.spec.ts @@ -0,0 +1,86 @@ +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { test, expect } from "@playwright/test"; +import { baseUrl } from "./baseUrl"; +import { channelStage, generateReport, readJson, resetData, resolvePath, testPaths } from "./helpers"; +import { odyseePageFixtureFile } from "./servers"; +import { + cdnUrlOf, + pageUrlOf, + syntheticChannel, + syntheticClaim, + videoPageRead, +} from "yt-dlp-transcript-common/testing/web/fakeOdyseePage.mjs"; + +// Release 32 R9: the browser lookup, by hand (the UI-without-AI rule). An +// Odysee record that stores no media URL is read from its page — here from the +// slot's recorded page reads (E2E_ODYSEE_PAGE_FIXTURE, e2e/servers.ts; no +// browser opens on the e2e server) — and the record gains the file the page +// named. The per-channel setting is on the Configure form; the listing's +// button is in the Playlist stage of an Odysee channel. + +const CHANNEL = "test-transcribe"; +const FIXTURE = "one-transcribe-channel"; +const ROOT = `${testPaths().transcriptsDir}/channels/${CHANNEL}`; +const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" }); +const claim = syntheticClaim({ name: "a-synthetic-stream", title: "A Synthetic Stream", channel: ch }); +const CLAIM = claim.claim_id; + +async function invalidate() { + await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {}); +} + +test("configure: the browser lookup setting saves and clears", async ({ page }) => { + await resetData(FIXTURE); + await generateReport(page, CHANNEL); + await page.goto(channelStage(CHANNEL, "configure")); + const box = page.getByLabel("browser lookup", { exact: true }); + await expect(box).not.toBeChecked(); + await box.check(); + await page.getByRole("button", { name: /save changes/i }).click(); + await expect + .poll(async () => (await readJson<{ browserLookup?: boolean }>(`${ROOT}/config.json`)).browserLookup) + .toBe(true); + await page.reload(); + await expect(page.getByLabel("browser lookup", { exact: true })).toBeChecked(); + await page.getByLabel("browser lookup", { exact: true }).uncheck(); + await page.getByRole("button", { name: /save changes/i }).click(); + await expect + .poll(async () => "browserLookup" in (await readJson<Record<string, unknown>>(`${ROOT}/config.json`))) + .toBe(false); +}); + +test("video page: Read from the page completes the record with the file the page named", async ({ page }) => { + test.setTimeout(120_000); + await resetData(FIXTURE); + const dir = resolvePath(`${ROOT}/data/${CLAIM}`); + await mkdir(dir, { recursive: true }); + await writeFile( + `${dir}/metadata.info.json`, + JSON.stringify({ id: CLAIM, extractor: "lbry", title: "A synthetic stream", webpage_url: pageUrlOf(claim) }), + ); + const fixture = odyseePageFixtureFile(resolvePath(testPaths().transcriptsDir)); + await writeFile(fixture, JSON.stringify({ [pageUrlOf(claim)]: videoPageRead({ claim }) })); + try { + await invalidate(); + await page.goto(`/channels/${CHANNEL}/videos/${CLAIM}`); + await page.getByRole("button", { name: "Read from the page" }).click(); + await expect + .poll( + async () => { + const info = JSON.parse(await readFile(`${dir}/metadata.info.json`, "utf8")) as { formats?: { url: string }[] }; + return info.formats?.[0]?.url ?? null; + }, + { timeout: 90_000 }, + ) + .toBe(cdnUrlOf(claim)); + const info = JSON.parse(await readFile(`${dir}/metadata.info.json`, "utf8")) as Record<string, unknown>; + expect(info.title).toBe("A synthetic stream"); + expect(typeof info._browserLookupAt).toBe("string"); + // The page now offers the stored URL the lookup found (R7's control). + await invalidate(); + await page.reload(); + await expect(page.getByLabel("stored media URL", { exact: true })).toBeVisible(); + } finally { + await rm(fixture, { force: true }); + } +}); diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -41,6 +41,8 @@ // pnpm ops sync --json '{"slug":"the-quartering"}' --wait // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait +// pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait +// pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait // pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait // pnpm ops import-video --json '{"slug":"demo-archive","url":"https://archive.org/details/example-item"}' // pnpm ops import-archive-org --json '{"slug":"demo-archive","item":"example-item","match":"\\.mp4$"}' --wait @@ -313,6 +315,10 @@ const ACTIONS = [ // ONE video's metadata.info.json re-read from its source ({slug, id}): no // subtitles, no media; the rewrite lands in metadata.history.json. "refresh-metadata", + // An Odysee record ({slug, ids: [...]}) or the channel's listing ({slug, + // listing: true, scrolls?}) read from its page in a headless browser, for + // when yt-dlp's lookup is refused; one page a minute, on the platform queue. + "browser-lookup", "import-video", // archive.org media into a channel: one item ({slug, item, files: [...] | // match: "<regex>"}), many ({items: [...]}) or a search ({query, limit?}); @@ -1126,6 +1132,15 @@ export function usage() { ' the keys that changed. An id with no data/<id>/ is refused (a refresh', ' re-reads a video already archived), as are archive.org and Wayback records.', "", + 'browser-lookup reads Odysee records from their pages in a headless browser,', + ' for when yt-dlp\'s lookup answers 429: {"slug", "ids": [...]} (at most 50)', + ' writes each record (none yet: whole, `_source: "browser"`) or completes it', + ' (the keys it lacks, and the one media file the page\'s player asked for);', + ' "listing": true (with "scrolls", default 5, at most 40) adds the uploads', + ' the channel page shows to the playlist, newest first, through the title', + ' match filter. One page a minute; not refused for a held platform. The log', + ' ends with a `summary: {...}` line.', + "", 'retry-bucket runs one bucket of a channel\'s report as one job, past any', ' lane hold: {"slug", "bucket"}. "ids": [...] runs only those videos, and', " every one must be in the bucket (a stray id is refused, named); a job run",