Archilyzer · Source

archilyzer

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

commit 41339c006609cab14a8f5a536450433ac99341e8
parent 26c697752efb6d779faff5483339fc99f33b7c6b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 17 Oct 2026 01:38:58 -0400

common: a browser-backed Odysee lookup — when yt-dlp's lbry lookup is refused, a video's record (or a channel's listing) is read from its page in headless Chromium (ytdlp/odyseePageReader.ts, injected; refuses under a test runner, answers from E2E_ODYSEE_PAGE_FIXTURE on the e2e server) out of the page's own resolve / claim_search / get answers (lib/odyseePageApi.ts, yt-dlp's lbry shapes) into the metadata.info.json yt-dlp writes, `_source: "browser"`, one `original` format: whole when there is none, else only what it lacks (history writer browser-lookup); a listing adds the page's uploads at the top of the playlist and to the roster, add-only; the channel's title match filter and download filters decide; one page a minute; the browser-lookup job (controller/browserLookupJob.ts); the managed download looks up first with storedUrlDownloads and the channel's new `browserLookup`; CHANNEL.md, ENVIRONMENT.md; synthetic page answers in the test kit

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

Diffstat:
MCHANNEL.md | 1+
MENVIRONMENT.md | 1+
Acommon/controller/browserLookupJob.ts | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/odyseeBrowserListing.test.ts | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/odyseeBrowserListing.ts | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 3+++
Mcommon/jobs/jobKinds.ts | 16++++++++++++++++
Mcommon/lib/channelConfig.ts | 6++++++
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Mcommon/lib/envVars.ts | 1+
Mcommon/lib/metadataHistory.ts | 4++++
Acommon/lib/odyseePageApi.test.ts | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/odyseePageApi.ts | 356+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/web/fakeOdyseePage.d.mts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/web/fakeOdyseePage.mjs | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/browserLookupDownload.test.ts | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 111++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Acommon/ytdlp/odyseeBrowserLookup.test.ts | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/odyseeBrowserLookup.ts | 263+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/odyseePageReader.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/storedUrlPageOpen.ts | 5+++++
Meditor/e2e/servers.ts | 9+++++++++
Meditor/playwright.config.ts | 6++++++
24 files changed, 1979 insertions(+), 4 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -47,6 +47,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. | | `audioCheck` | config | Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {"enabled": false}` turns it off); the channel's opt-in for any other platform. See [`audioCheck`](#audiocheck). | | `storedUrlDownloads` | config | Whether a full download (transcribe handling) reads the media URL the record's `metadata.info.json` already stores, the way the platform's own player reads it — ranged requests with the page's Referer and Origin, no yt-dlp — through the same audio check. `"never"` (the default: the page, as always), `"fallback"` (the page first; on a rate limit, or a held platform, the stored URL) or `"only"` (the stored URL and no page request; a video without one fails, asking nothing). Odysee only (its CDN hosts). Two such downloads on one platform are at least 20 minutes apart: the CDN allows one new file per rest. A request's own `storedUrl` overrides it. | +| `browserLookup` | config | `true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: "browser"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says. | | `recordedDate` | config | For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped. See [`recordedDate`](#recordeddate). | | `mirror` | config | For a channel that MIRRORS another creator's streams: the creator's channels it copies (`of`, their slugs). The mirror scan (`pnpm ops mirror-scan`) pairs each of this channel's videos with the creator's by date and title and writes `transcripts/mirrors/<slug>.json`: which videos the creator still has public, removed or never uploaded, and which of the creator's removed videos this channel holds. Private: never published. An object without a usable `of` is dropped. See [`mirror`](#mirror). | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -221,6 +221,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts | | `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts | | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | +| `E2E_ODYSEE_PAGE_FIXTURE` | unset (a headless browser) | A JSON file of recorded Odysee page reads keyed by page URL (`"*"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`). | common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts | | `E2E_BLUESKY_ORIGIN_FILE` | unset (the real Bluesky) | A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored. | common/social/blueskyEndpoints.ts | | `E2E_AUDIO_CHECK_DEBUG_PAUSE_MS` | off | A debugging pause inside the audio check. | common/ytdlp/audioCheckedDownload.ts | | `E2E_FAKE_YTDLP_AUDIO_CHECK_MODE` | — | Fake yt-dlp: which audio-check scenario to act out. | editor/e2e/fixtures/bin/fake-ytdlp.mjs | diff --git a/common/controller/browserLookupJob.ts b/common/controller/browserLookupJob.ts @@ -0,0 +1,175 @@ +// THE BROWSER LOOKUP AS A JOB (release 32 R9) — what the video page's "Read +// from the page", the channel page's "List from the page" and +// `/api/ops/browser-lookup` enqueue. The work is ytdlp/odyseeBrowserLookup.ts +// (one video) and controller/odyseeBrowserListing.ts (the channel's page). +// +// THE PER-REQUEST OPT-IN: a person (or an ops body) asks for exactly this. A +// channel's `browserLookup: true` makes the managed download do the video half +// by itself when the lookup is refused (ytdlp/downloadOneManaged.ts). +// +// THE REFUSALS COME BEFORE ANY JOB: a channel whose text cannot be read; a +// request naming nothing; an id the channel cannot resolve to a page URL, or a +// page that is not Odysee's; a listing of a channel whose URL is not an Odysee +// channel page or whose yt-dlp match filter cannot be applied here. +// +// NOT REFUSED FOR A HELD OR COOLING PLATFORM: the hold is yt-dlp's lookup's, +// and asking the page as a browser is the way round it the operator measured. +// Paced (one page per BROWSER_LOOKUP gap, ytdlp/odyseeBrowserLookup.ts) and on +// the platform's download queue, so it never runs beside a download, a sync or +// another lookup of that platform. `needsText`: it writes text files only. +// +// The job's log ends with `summary: {json}` — the per-video statuses and the +// listing's counts — for the UI to read back into sentences. + +import path from "node:path"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { detectPlatform } from "../lib/platform"; +import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys"; +import type { Paths } from "../lib/paths"; +import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; +import { + BROWSER_LOOKUP_PLATFORMS, + browserLookupVideo, + type BrowserLookupDeps, +} from "../ytdlp/odyseeBrowserLookup"; +import { browserListChannel, browserListingRefusal } from "./odyseeBrowserListing"; +import { isVideoIdSegment } from "./refreshVideoMetadata"; +import { findVideoSourceUrl } from "./undownloadedVideos"; + +export const BROWSER_LOOKUP_JOB_KIND = "browser-lookup"; +// A bound on one request: each video is a page view, a minute apart. +export const BROWSER_LOOKUP_MAX_VIDEOS = 50; + +export type BrowserLookupSummary = { + videos: { id: string; status: string; stored: boolean; error?: string }[]; + listing?: { status: string; seen?: number; filtered?: number; added?: number; error?: string }; +}; + +export type BrowserLookupJobOpts = { + paths: Paths; + slug: string; + channelConfig: ChannelConfig; + videoIds?: string[]; + listing?: boolean; + scrolls?: number; + skipLiveDownloads: boolean; + queueKey?: string; + requestedBy?: string; + afterRun?: () => void | Promise<void>; + // Test seam: the page reader and the gap. + deps?: BrowserLookupDeps; +}; + +export async function runBrowserLookupJob(opts: BrowserLookupJobOpts): Promise<StreamActionResult> { + const { paths, slug, channelConfig } = opts; + try { + await assertChannelTextReadable(paths, slug, channelConfig); + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + const ids = [...new Set(opts.videoIds ?? [])]; + if (ids.length === 0 && !opts.listing) { + return { ok: false, error: "Name the videos to look up, or ask for the channel's listing." }; + } + if (ids.length > BROWSER_LOOKUP_MAX_VIDEOS) { + return { ok: false, error: `At most ${BROWSER_LOOKUP_MAX_VIDEOS} videos per browser lookup (${ids.length} asked).` }; + } + const bad = ids.filter((id) => !isVideoIdSegment(id)); + if (bad.length) return { ok: false, error: `Not a video id: ${bad.join(", ")}.` }; + if (opts.listing) { + const refusal = browserListingRefusal(channelConfig); + if (refusal) return { ok: false, error: refusal }; + } + const targets: { id: string; url: string }[] = []; + const unresolved: string[] = []; + for (const id of ids) { + const url = await findVideoSourceUrl(paths, slug, id, channelConfig); + const platform = url ? detectPlatform(url) : null; + if (!url || !platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform)) unresolved.push(id); + else targets.push({ id, url }); + } + if (unresolved.length) { + return { + ok: false, + error: + `No Odysee page URL for ${unresolved.join(", ")} (no metadata.info.json, and the playlist has no ` + + `matching entry, or the page is not Odysee's).`, + }; + } + + return runManagedFunction({ + kind: BROWSER_LOOKUP_JOB_KIND, + queueKey: resolveQueueKey(downloadQueueKey(channelConfig), opts.queueKey), + paths, + channelSlug: slug, + ...(targets.length === 1 && !opts.listing ? { videoId: targets[0].id } : {}), + spec: { + kind: BROWSER_LOOKUP_JOB_KIND, + slug, + params: { + ...(ids.length ? { videoIds: ids } : {}), + ...(opts.listing ? { listing: true } : {}), + ...(opts.scrolls !== undefined ? { scrolls: opts.scrolls } : {}), + queueKey: opts.queueKey, + }, + }, + fn: async (onLog, signal) => { + const summary: BrowserLookupSummary = { videos: [] }; + if (opts.listing) { + const r = await browserListChannel({ + paths, + slug, + config: channelConfig, + ...(opts.scrolls !== undefined ? { scrolls: opts.scrolls } : {}), + skipLiveDownloads: opts.skipLiveDownloads, + onLog, + signal, + ...(opts.deps ? { deps: opts.deps } : {}), + }); + summary.listing = + r.status === "listed" + ? { status: r.status, seen: r.seen, filtered: r.filtered, added: r.added.length } + : { status: r.status, error: r.error }; + if (r.status !== "listed") onLog(`Browser listing: ${r.status} — ${r.error}\n`); + } + for (const t of targets) { + if (signal.aborted) break; + const r = await browserLookupVideo({ + videoDir: path.join(paths.channelsDir, slug, "data", t.id), + pageUrl: t.url, + onLog, + signal, + ...(opts.requestedBy ? { requestedBy: opts.requestedBy } : {}), + ...(opts.deps ? { deps: opts.deps } : {}), + }); + if ("error" in r) { + onLog(`${t.id}: ${r.status} — ${r.error}\n`); + summary.videos.push({ id: t.id, status: r.status, stored: false, error: r.error }); + } else { + summary.videos.push({ id: t.id, status: r.status, stored: r.stored !== null }); + } + } + onLog(`summary: ${JSON.stringify(summary)}\n`); + await opts.afterRun?.(); + const good = + summary.videos.filter((v) => v.status === "written" || v.status === "patched" || v.status === "unchanged").length + + (summary.listing?.status === "listed" ? 1 : 0); + if (good === 0 && !signal.aborted) { + throw new Error("The browser lookup found nothing it could write."); + } + }, + }); +} + +// The job log's last `summary:` line, parsed (the UI reads it back). +export function browserLookupSummaryOf(log: string): BrowserLookupSummary | null { + const lines = log.split("\n").filter((l) => l.startsWith("summary: ")); + const last = lines.at(-1); + if (!last) return null; + try { + return JSON.parse(last.slice("summary: ".length)) as BrowserLookupSummary; + } catch { + return null; + } +} diff --git a/common/controller/odyseeBrowserListing.test.ts b/common/controller/odyseeBrowserListing.test.ts @@ -0,0 +1,103 @@ +// A channel's listing from its page in a (fake) browser, and the browser +// lookup job's door (release 32 R9). No browser: testing/web/fakeOdyseePage.mjs. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/odyseeBrowserListing.test.ts + +import { test, beforeEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { browserListChannel, browserListingRefusal } from "./odyseeBrowserListing"; +import { browserLookupSummaryOf, runBrowserLookupJob } from "./browserLookupJob"; +import { clearPlatformGaps } from "../jobs/platformGap"; +import { + channelPageRead, + channelUrlOf, + fakePageReader, + pageUrlOf, + syntheticChannel, + syntheticClaim, +} from "../testing/web/fakeOdyseePage.mjs"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "browserlisting-")); +const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" }); +const show1 = syntheticClaim({ name: "show-1", title: "SynthShow - 1", channel: ch, releaseTime: 1700000000 }); +const show2 = syntheticClaim({ name: "show-2", title: "SynthShow - 2", channel: ch, releaseTime: 1700200000 }); +const vlog = syntheticClaim({ name: "vlog", title: "A vlog", channel: ch, releaseTime: 1700100000 }); +const stranger = syntheticClaim({ name: "theirs", title: "SynthShow - not ours", channel: syntheticChannel({ name: "@other" }) }); +const signal = new AbortController().signal; +const noLog = () => {}; + +let n = 0; +async function channel(config: Partial<ChannelConfig>, playlist?: string[]) { + const channelsDir = path.join(ROOT, `case-${++n}`, "channels"); + const slug = "synth"; + await mkdir(path.join(channelsDir, slug), { recursive: true }); + const cfg = { handling: "transcribe", platform: "odysee", url: channelUrlOf(ch), ...config } as ChannelConfig; + await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify(cfg)); + if (playlist) await writeFile(path.join(channelsDir, slug, "playlist"), playlist.join("\n") + "\n"); + return { paths: { channelsDir } as Paths, slug, cfg, root: path.join(channelsDir, slug) }; +} + +beforeEach(() => clearPlatformGaps()); + +test("the listing adds the page's own new uploads at the top of the playlist, newest first, and to the roster", async () => { + const c = await channel({}, [pageUrlOf(show1)]); + const reader = fakePageReader({ [channelUrlOf(ch)]: channelPageRead({ channel: ch, pages: [[show2, stranger], [vlog, show1]] }) }); + const r = await browserListChannel({ + paths: c.paths, + slug: c.slug, + config: c.cfg, + scrolls: 2, + skipLiveDownloads: true, + onLog: noLog, + signal, + deps: { reader, gapMs: 0 }, + }); + assert.equal(r.status, "listed"); + assert.ok(r.status === "listed" && r.seen === 3 && r.added.length === 2); + const playlist = (await readFile(path.join(c.root, "playlist"), "utf8")).trim().split("\n"); + assert.deepEqual(playlist, [pageUrlOf(show2), pageUrlOf(vlog), pageUrlOf(show1)], "new first, nothing removed"); + const roster = JSON.parse(await readFile(path.join(c.root, "roster.json"), "utf8")); + assert.ok(JSON.stringify(roster).includes(show2.claim_id)); + assert.equal(reader.calls[0].scrolls, 2); +}); + +test("the channel's title match filter decides what is listed", async () => { + const c = await channel({ ytdlpExtraArgs: ["--match-filters=title~='SynthShow'"] }); + const reader = fakePageReader({ "*": channelPageRead({ channel: ch, pages: [[show2, vlog, show1]] }) }); + const r = await browserListChannel({ paths: c.paths, slug: c.slug, config: c.cfg, skipLiveDownloads: true, onLog: noLog, signal, deps: { reader, gapMs: 0 } }); + assert.ok(r.status === "listed" && r.filtered === 1); + const playlist = (await readFile(path.join(c.root, "playlist"), "utf8")).trim().split("\n"); + assert.deepEqual(playlist, [pageUrlOf(show2), pageUrlOf(show1)]); +}); + +test("refused before anything opens: not Odysee, no @channel, an unreadable match filter", async () => { + assert.match(browserListingRefusal({ url: "https://www.youtube.com/@x" } as ChannelConfig) ?? "", /Odysee|odysee/); + assert.match(browserListingRefusal({ url: "https://odysee.com/some-stream:abc" } as ChannelConfig) ?? "", /@channel/); + assert.match( + browserListingRefusal({ url: channelUrlOf(ch), ytdlpExtraArgs: ["--match-filter", "duration>600"] } as ChannelConfig) ?? "", + /cannot be applied/, + ); + assert.equal(browserListingRefusal({ url: channelUrlOf(ch) } as ChannelConfig), null); +}); + +test("the job's door: nothing named, too many, an id with no Odysee page", async () => { + const c = await channel({}, [pageUrlOf(show1)]); + const base = { paths: c.paths, slug: c.slug, channelConfig: c.cfg, skipLiveDownloads: true }; + assert.equal((await runBrowserLookupJob({ ...base })).ok, false); + const many = await runBrowserLookupJob({ ...base, videoIds: Array.from({ length: 51 }, (_, i) => `v${i}`) }); + assert.match((many as { error: string }).error, /At most 50/); + const yt = await channel({ platform: "youtube", url: "https://www.youtube.com/@synth" } as Partial<ChannelConfig>); + const notOdysee = await runBrowserLookupJob({ paths: yt.paths, slug: yt.slug, channelConfig: yt.cfg, skipLiveDownloads: true, videoIds: ["abcdefghijk"] }); + assert.match((notOdysee as { error: string }).error, /No Odysee page URL for abcdefghijk/); +}); + +test("the summary line reads back", () => { + const log = `x\nsummary: {"videos":[{"id":"a","status":"written","stored":true}]}\n`; + assert.deepEqual(browserLookupSummaryOf(log), { videos: [{ id: "a", status: "written", stored: true }] }); + assert.equal(browserLookupSummaryOf("nothing"), null); +}); diff --git a/common/controller/odyseeBrowserListing.ts b/common/controller/odyseeBrowserListing.ts @@ -0,0 +1,161 @@ +// A CHANNEL'S LISTING FROM ITS PAGE, IN A BROWSER (release 32 R9). +// +// yt-dlp's lbry listing (`--flat-playlist` of the channel URL) is a +// `claim_search` through Odysee's API, and on 2026-10-16/17 it answered 429 +// where the channel page, loaded by a browser, answered 200. This opens the +// channel page (ytdlp/odyseePageReader.ts), scrolls it a bounded number of +// times so it lists more uploads, and reads the uploads out of the page's own +// `claim_search` answers (lib/odyseePageApi.ts listingFromResponses) as the +// page URLs yt-dlp's listing prints. +// +// ADD-ONLY. A page shows the newest uploads, not the whole channel, so this +// never decides that something LEFT the listing: the ids join the roster as a +// sighting (mergeRosterFile, source "listing" — the paged sync's call), and +// the ones `playlist` does not hold yet are put at its top, newest first, +// ahead of everything already there. Nothing is removed and nothing is +// downloaded: the download lane and download-missing see them as undownloaded +// as they see any listed video. Serialised with the channel's sync and +// downloads by the job's queue (the platform's download queue). +// +// FILTERED AS yt-dlp's LISTING WOULD BE: a channel whose `ytdlpExtraArgs` carry +// a `--match-filter` lists only the matching titles through yt-dlp; here the +// readable form (`title~='<regex>'`) is applied, and an unreadable one refuses +// the listing (ytdlp/odyseeBrowserLookup.ts browserLookupDecision). The app's +// download filters apply too. + +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { detectPlatform } from "../lib/platform"; +import { extractVideoId } from "../lib/videoId"; +import { writeFileAtomic } from "../lib/jsonFile-server"; +import { + channelClaimFor, + listingFromResponses, + odyseeInfoFromClaim, + odyseePageRef, +} from "../lib/odyseePageApi"; +import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; +import { + BROWSER_LOOKUP_PLATFORMS, + browserLookupDecision, + browserLookupGapKey, + browserLookupGapMs, + type BrowserLookupDeps, +} from "../ytdlp/odyseeBrowserLookup"; +import { readOdyseePage } from "../ytdlp/odyseePageReader"; +import { mergeRosterFile, observationsFromUrls } from "./rosterStore"; + +export const BROWSER_LISTING_DEFAULT_SCROLLS = 5; + +export type BrowserListingResult = + | { status: "listed"; seen: number; filtered: number; added: string[] } + | { status: "refused" | "unreadable" | "not-found"; error: string }; + +// Before anything is opened: the channel's URL is an Odysee channel page, and +// its match filter (if any) is one a browser listing can apply. +export function browserListingRefusal(config: ChannelConfig): string | null { + const url = config.url ?? ""; + const platform = detectPlatform(url); + if (!platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform)) { + return `A browser listing is for ${BROWSER_LOOKUP_PLATFORMS.join(", ")} channels; this channel's URL is ${url || "unset"}.`; + } + if (!odyseePageRef(url).channel) return `The channel URL (${url}) names no @channel page.`; + const probe = browserLookupDecision(config, { title: "" }, { skipLiveDownloads: false }); + if (!probe.ok && !probe.skip) return `Not listed: ${probe.reason}.`; + return null; +} + +export async function browserListChannel(opts: { + paths: Paths; + slug: string; + config: ChannelConfig; + scrolls?: number; + skipLiveDownloads: boolean; + onLog: (s: string) => void; + signal: AbortSignal; + deps?: BrowserLookupDeps; +}): Promise<BrowserListingResult> { + const { paths, slug, config, onLog, signal } = opts; + const refusal = browserListingRefusal(config); + if (refusal) return { status: "refused", error: refusal }; + const pageUrl = config.url!; + const platform = detectPlatform(pageUrl)!; + const ref = odyseePageRef(pageUrl); + const key = browserLookupGapKey(platform); + const gapMs = opts.deps?.gapMs ?? browserLookupGapMs(platform); + try { + await waitForPlatformGap({ + label: `A browser listing (${platform})`, + remainingMs: () => platformGapRemainingMs(key), + signal, + onLog: (line) => onLog(`${line}\n`), + ...(opts.deps?.sleep ? { sleep: opts.deps.sleep } : {}), + }); + } catch { + return { status: "unreadable", error: "cancelled while waiting for the gap between browser lookups" }; + } + notePlatformGap(key, gapMs); + const reader = opts.deps?.reader ?? readOdyseePage; + let read; + try { + read = await reader({ pageUrl, signal, onLog, scrolls: opts.scrolls ?? BROWSER_LISTING_DEFAULT_SCROLLS }); + } finally { + notePlatformGap(key, gapMs); + } + if (!read.ok && read.responses.length === 0) { + return { status: "unreadable", error: `the channel page could not be read (${read.error ?? "no API answer"})` }; + } + // The channel's claim id: the page's resolve of `@name`, else the URL's own. + const fromUrl = (() => { + try { + const seg = decodeURIComponent(new URL(pageUrl).pathname).split("/").find((s) => s.startsWith("@")) ?? ""; + const m = /[:#]([0-9a-f]{40})$/.exec(seg); + return m ? m[1] : null; + } catch { + return null; + } + })(); + const channelClaim = ref.channel ? channelClaimFor(read.responses, ref.channel) : null; + const listing = listingFromResponses(read.responses, { + claimId: channelClaim?.claimId ?? fromUrl, + name: ref.channel, + }); + if (listing.length === 0) { + return { status: "not-found", error: `the channel page's API answers (${read.responses.length}) list no uploads of ${ref.channel}` }; + } + let filtered = 0; + const kept: string[] = []; + for (const { url, claim } of listing) { + const info = odyseeInfoFromClaim(claim, { pageUrl: url, streamingUrl: null }); + const d = browserLookupDecision(config, info, { skipLiveDownloads: opts.skipLiveDownloads }); + if (d.ok) kept.push(url); + else filtered++; + } + + const root = path.join(paths.channelsDir, slug); + const playlistPath = path.join(root, "playlist"); + const existing = (await readFile(playlistPath, "utf8").catch(() => "")) + .split("\n") + .map((s) => s.trim()) + .filter(Boolean); + const have = new Set(existing.map((u) => extractVideoId(u)).filter((id): id is string => Boolean(id))); + const added = kept.filter((u) => { + const id = extractVideoId(u); + return id !== null && !have.has(id); + }); + if (added.length > 0) { + const next = [...added, ...existing]; + await writeFileAtomic(playlistPath, next.join("\n") + "\n", { mkdir: true }); + } + if (kept.length > 0) { + await mergeRosterFile(paths, slug, observationsFromUrls(kept), new Date().toISOString(), "listing"); + } + onLog( + `Browser listing of ${ref.channel}: ${listing.length} upload(s) on the page` + + (filtered ? `, ${filtered} declined by the channel's filters` : "") + + `, ${added.length} new to the playlist.\n`, + ); + return { status: "listed", seen: listing.length, filtered, added }; +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -95,6 +95,8 @@ const ADDED_KINDS: Record<string, { label: string; drainable: boolean }> = { "fetch-windows": { label: "Fetch windows", drainable: true }, // One video's metadata re-read: one spawn, cancelled rather than drained. "refresh-metadata": { label: "Refresh metadata", drainable: false }, + // An Odysee record or listing read from its page in a browser: page by page. + "browser-lookup": { label: "Browser lookup", drainable: false }, // One file through a local worker (pnpm ops transcribe): one engine run. "transcribe-file": { label: "Transcribe file", drainable: false }, // One synthesis (pnpm ops tts): one engine run, or a cache hit. @@ -167,6 +169,7 @@ const TEXT_KINDS = [ "evict-clips", "metadata-scan", "refresh-metadata", + "browser-lookup", "download-missing-subs", "check-availability", "quick-availability-check", diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -681,6 +681,22 @@ const JOB_KINDS: Record<string, JobKindMeta> = { needsMedia: false, needsText: true, }, + // An Odysee video's record (or the channel's listing) read from its page in + // a headless browser (release 32 R9, controller/browserLookupJob.ts), when + // yt-dlp's lookup is refused. On the platform download queue, so it never + // runs beside a download or a sync of that platform; `needsText`: it writes + // metadata.info.json, the playlist and the roster, no media. Not drainable + // (each page is ~20 s); replayable (the spec carries the ids and the listing + // flag). + "browser-lookup": { + kind: "browser-lookup", + label: "Browser lookup", + drainable: false, + replayable: true, + queueKeyStrategy: "platform", + needsMedia: false, + needsText: true, + }, // THE HUB'S AND THE HOMEPAGE'S BUILD AND DEPLOY (release 13 slice W1). They // ran from /sites — the hub since release 7, the homepage since release 11 — // with no entry here, so /jobs showed their raw machine kinds. The labels diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -152,6 +152,9 @@ export type ChannelConfig = { // Release 32 R7: whether a full download may read the record's stored media // URL (lib/storedMediaUrl.ts) the way the platform's player does. storedUrlDownloads?: StoredUrlMode; + // Release 32 R9: when yt-dlp's lookup is refused, read a video's metadata + // from its page in a headless browser (ytdlp/odyseeBrowserLookup.ts). + browserLookup?: boolean; recordedDate?: RecordedDateRule; mirror?: MirrorConfig; }; @@ -214,6 +217,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { "Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {\"enabled\": false}` turns it off); the channel's opt-in for any other platform.", storedUrlDownloads: 'Whether a full download (transcribe handling) reads the media URL the record\'s `metadata.info.json` already stores, the way the platform\'s own player reads it — ranged requests with the page\'s Referer and Origin, no yt-dlp — through the same audio check. `"never"` (the default: the page, as always), `"fallback"` (the page first; on a rate limit, or a held platform, the stored URL) or `"only"` (the stored URL and no page request; a video without one fails, asking nothing). Odysee only (its CDN hosts). Two such downloads on one platform are at least 20 minutes apart: the CDN allows one new file per rest. A request\'s own `storedUrl` overrides it.', + browserLookup: + "`true`, with `storedUrlDownloads` `fallback` or `only`: when a video's record stores no media URL — `only`, or a `fallback` whose yt-dlp lookup was refused (a 429) — the managed download opens the video's page in a headless browser, reads the record from the page's own API answers and writes `metadata.info.json` (marked `_source: \"browser\"`), then downloads from the media URL the page named. Odysee only; one page a minute; the channel's `--match-filter title~='…'` and download filters still decide. Absent = off. The video page's **Read from the page** and the channel's **List from the page** ask for it once, whatever this says.", recordedDate: "For a channel that MIRRORS another's streams (a VOD archive): how to read the date a video was RECORDED from its title, since its `upload_date` is the date of the copy. The index stores the result as the record's `recordedDate` (`YYYYMMDD`), which coverage reads before the upload date. A title it does not match, a date that is not a real day, or one after the upload date gives none. Changing the rule re-derives the channel's records on the next index build. An object without a usable `titlePattern` is dropped.", mirror: @@ -422,6 +427,7 @@ export const CHANNEL_CONFIG_COERCIONS: { : undefined, audioCheck: coerceAudioCheck, storedUrlDownloads: (v) => (isStoredUrlMode(v) ? v : undefined), + browserLookup: (v) => (v === true ? true : undefined), recordedDate: coerceRecordedDateRule, mirror: coerceMirrorConfig, }; diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 35); + assert.equal(CHANNEL_CONFIG_KEYS.length, 36); assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -76,6 +76,7 @@ export const channelConfigObjectSchema = z.object({ sleepBetweenDownloadsSeconds: field("sleepBetweenDownloadsSeconds"), audioCheck: field("audioCheck"), storedUrlDownloads: field("storedUrlDownloads"), + browserLookup: field("browserLookup"), recordedDate: field("recordedDate"), mirror: field("mirror"), }); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -218,6 +218,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." }, { name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, + { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." }, { name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." }, diff --git a/common/lib/metadataHistory.ts b/common/lib/metadataHistory.ts @@ -82,6 +82,10 @@ export const METADATA_HISTORY_WRITERS = [ // controller/attachMedia.ts `createRecords`): the folder's own yt-dlp // .info.json, or one built from its description.txt / source.txt and name. "local-archive", + // An Odysee record completed from its page's own API answers in a headless + // browser (release 32 R9, ytdlp/odyseeBrowserLookup.ts), when yt-dlp's lookup + // is refused: only the keys the file lacks, and the one stored format. + "browser-lookup", ] as const; export type MetadataHistoryWriter = (typeof METADATA_HISTORY_WRITERS)[number]; diff --git a/common/lib/odyseePageApi.test.ts b/common/lib/odyseePageApi.test.ts @@ -0,0 +1,105 @@ +// Reading an Odysee record out of a page's own API answers (release 32 R9), +// over synthetic answers in the LBRY SDK's shape (testing/web/fakeOdyseePage.mjs). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/odyseePageApi.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + claimForPage, + claimsFromResponses, + isOdyseeApiUrl, + listingFromResponses, + odyseeInfoFromClaim, + odyseePageRef, + originalFileUrl, + streamingUrlFor, + channelClaimFor, +} from "./odyseePageApi"; +import { storedMediaUrlFromInfo } from "./storedMediaUrl"; +import { + cdnUrlOf, + channelPageRead, + pageUrlOf, + refusedAnswer, + syntheticChannel, + syntheticClaim, + videoPageRead, +} from "../testing/web/fakeOdyseePage.mjs"; + +const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" }); +const v1 = syntheticClaim({ name: "first-stream", title: "First Stream", channel: ch, releaseTime: 1700000000, duration: 4321 }); +const v2 = syntheticClaim({ name: "second-stream", title: "Second Stream", channel: ch, releaseTime: 1700100000 }); +const other = syntheticClaim({ name: "recommended", title: "Someone Else", channel: syntheticChannel({ name: "@other" }) }); + +test("the API hosts, and nothing else", () => { + assert.ok(isOdyseeApiUrl("https://api.na-backend.odysee.com/api/v1/proxy?m=resolve")); + assert.ok(isOdyseeApiUrl("https://api.odysee.com/file/view_count")); + assert.ok(isOdyseeApiUrl("https://api.lbry.tv/api/v1/proxy")); + assert.ok(!isOdyseeApiUrl("https://player.odycdn.com/v6/streams/x/y.mp4")); + assert.ok(!isOdyseeApiUrl("https://odysee.com/@x")); + assert.ok(!isOdyseeApiUrl("not a url")); +}); + +test("claims come out of resolve, claim_search and bare answers; a refusal adds nothing", () => { + const read = videoPageRead({ claim: v1, related: [other, v2] }); + const claims = claimsFromResponses([...read.responses, refusedAnswer("resolve")]); + assert.deepEqual([...claims.keys()].sort(), [v1.claim_id, v2.claim_id, other.claim_id].sort()); +}); + +test("the page's claim: by the URL's claim id (full or a prefix), never 'the only one'", () => { + const claims = claimsFromResponses(videoPageRead({ claim: v1, related: [other] }).responses); + assert.equal(claimForPage(claims, pageUrlOf(v1))?.claim_id, v1.claim_id); + assert.equal(claimForPage(claims, `https://odysee.com/first-stream:${v1.claim_id.slice(0, 3)}`)?.claim_id, v1.claim_id); + assert.equal(claimForPage(claims, "https://odysee.com/first-stream")?.claim_id, v1.claim_id, "by name, one match"); + assert.equal(claimForPage(claims, "https://odysee.com/not-here:abc")?.claim_id, undefined); + assert.deepEqual(odyseePageRef(`https://odysee.com/@synthchan:5/first-stream:${v1.claim_id}`), { + name: "first-stream", + claimRef: v1.claim_id, + channel: "@synthchan", + }); +}); + +test("the file: the get answer's streaming_url, else the player's CDN request; v3 for an /api/ path", () => { + const read = videoPageRead({ claim: v1 }); + assert.equal(streamingUrlFor(v1.claim_id, read.responses, read.mediaUrls), cdnUrlOf(v1)); + const noGet = videoPageRead({ claim: v1, get: false }); + assert.equal(streamingUrlFor(v1.claim_id, noGet.responses, noGet.mediaUrls), cdnUrlOf(v1), "the CDN request, query dropped"); + assert.equal(streamingUrlFor(v1.claim_id, noGet.responses, []), null); + assert.equal(originalFileUrl("https://cdn.example/api/v4/streams/free/x/y"), "https://cdn.example/api/v3/streams/free/x/y"); +}); + +test("the record yt-dlp would write, marked _source: browser, and the stored-URL reader trusts it", () => { + const info = odyseeInfoFromClaim(v1, { pageUrl: pageUrlOf(v1), streamingUrl: cdnUrlOf(v1), at: "2026-10-17T00:00:00.000Z" }); + assert.equal(info.id, v1.claim_id); + assert.equal(info.title, "First Stream"); + assert.equal(info.duration, 4321); + assert.equal(info.release_timestamp, 1700000000); + assert.equal(info.upload_date, "20231114", "from the timestamp, UTC, as yt-dlp derives it"); + assert.equal(info.channel, "Synth Channel"); + assert.equal(info.uploader_id, "@synthchan"); + assert.equal(info.extractor, "lbry"); + assert.equal(info.webpage_url, pageUrlOf(v1)); + assert.equal(info._source, "browser"); + assert.equal((info.formats as unknown[]).length, 1); + assert.equal(info.filesize, 123456789, "the SDK's string size, as a number"); + const stored = storedMediaUrlFromInfo(info); + assert.equal(stored?.url, cdnUrlOf(v1)); + assert.equal(stored?.host, "player.odycdn.com"); + const bare = odyseeInfoFromClaim(v1, { pageUrl: pageUrlOf(v1), streamingUrl: null }); + assert.equal(bare.formats, undefined); + assert.equal(storedMediaUrlFromInfo(bare), null); +}); + +test("a channel page's listing: its own uploads, newest first, as listing URLs", () => { + const read = channelPageRead({ channel: ch, pages: [[v1, other], [v2]] }); + const claim = channelClaimFor(read.responses, "@synthchan"); + assert.equal(claim?.claimId, ch.claim_id); + const listing = listingFromResponses(read.responses, { claimId: claim?.claimId, name: "@synthchan" }); + assert.deepEqual( + listing.map((l) => l.url), + [pageUrlOf(v2), pageUrlOf(v1)], + ); + assert.deepEqual(listingFromResponses(read.responses, { name: "@synthchan" }).length, 2, "by name when no id"); + assert.deepEqual(listingFromResponses(read.responses, {}), [], "no channel, no listing"); +}); diff --git a/common/lib/odyseePageApi.ts b/common/lib/odyseePageApi.ts @@ -0,0 +1,356 @@ +// AN ODYSEE RECORD FROM THE PAGE'S OWN API ANSWERS (release 32 R9). +// +// Measured live 2026-10-17: a headless browser's load of an odysee.com page +// gets 200 from Odysee's API (`api.na-backend.odysee.com/api/v1/proxy`, +// `api.odysee.com/*`) where yt-dlp's lbry extractor gets 429 — the page asks +// the same LBRY SDK methods yt-dlp does (`resolve`, `claim_search`, `get`), as +// a browser. ytdlp/odyseePageReader.ts opens the page and keeps every JSON +// answer of those hosts (and the URLs the player asks the CDN for); this module +// reads them into the metadata.info.json shape yt-dlp writes, so the index, the +// stored-URL download (lib/storedMediaUrl.ts) and every reader see an ordinary +// record — marked `_source: "browser"`. +// +// THE SHAPES are the LBRY SDK's JSON-RPC answers as yt-dlp's own extractor +// reads them (yt_dlp/extractor/lbry.py: `_parse_stream`, `_fetch_page`, the +// `get` call's `streaming_url`): a claim is `{claim_id, name, timestamp, +// value_type, value: {title, description, thumbnail.url, release_time, tags, +// license, stream_type, source: {name, media_type, size}, video|audio: +// {duration, width, height}}, signing_channel: {claim_id, name, value.title}}`; +// `resolve` answers `{result: {<lbry url>: claim}}`, `claim_search` `{result: +// {items: [claim…]}}`, `get` `{result: {streaming_url}}`. The reader is +// TOLERANT of where in an answer a claim sits (a result keyed by URL, a list of +// items, a bare claim, a JSON-RPC batch) because the page's exact request mix +// was not recorded offline: the unit tests run on synthetic answers of that +// shape, and the live check (plans/release-32/odysee-loop.md) is what confirms +// the page asks these and nothing else is needed. +// +// Pure: no I/O. + +export type PageApiResponse = { + // The request URL (the proxy's `?m=<method>` included when the page sends it). + url: string; + status: number; + // The request's JSON body, when it had one (a JSON-RPC call). + request?: unknown; + // The response's JSON body. + body: unknown; +}; + +// The hosts whose answers are the page's API (and the ones yt-dlp's extractor +// asks — api.lbry.tv is its proxy). +export const ODYSEE_API_HOSTS: readonly string[] = [ + "api.na-backend.odysee.com", + "api.odysee.com", + "api.lbry.tv", + "api.lbry.com", +]; + +export function isOdyseeApiUrl(raw: string): boolean { + try { + const host = new URL(raw).hostname.toLowerCase(); + return ODYSEE_API_HOSTS.includes(host) || (host.endsWith(".odysee.com") && host.startsWith("api.")); + } catch { + return false; + } +} + +export type OdyseeClaim = { + claim_id: string; + name: string; + value_type?: string; + timestamp?: number; + permanent_url?: string; + canonical_url?: string; + value: Record<string, unknown>; + signing_channel?: { claim_id?: string; name?: string; value?: Record<string, unknown> }; +}; + +const obj = (v: unknown): Record<string, unknown> | null => + v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null; +const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined); +// The SDK answers many numbers as strings ("release_time": "1702586407"). +const int = (v: unknown): number | undefined => { + const n = typeof v === "number" ? v : typeof v === "string" && /^\d+$/.test(v) ? Number(v) : NaN; + return Number.isFinite(n) ? Math.trunc(n) : undefined; +}; + +function asClaim(v: unknown): OdyseeClaim | null { + const o = obj(v); + if (!o) return null; + const claimId = str(o.claim_id); + const name = str(o.name); + const value = obj(o.value); + if (!claimId || !/^[0-9a-f]{40}$/.test(claimId) || !name || !value) return null; + return o as unknown as OdyseeClaim; +} + +// The JSON-RPC results in one answer (a batch is an array of envelopes). +function resultsOf(body: unknown): unknown[] { + if (Array.isArray(body)) return body.flatMap(resultsOf); + const o = obj(body); + if (!o) return []; + if ("result" in o) return [o.result]; + if ("data" in o) return [o.data]; + return [o]; +} + +// Every claim in the answers, by claim id (the first seen wins). +export function claimsFromResponses(responses: readonly PageApiResponse[]): Map<string, OdyseeClaim> { + const out = new Map<string, OdyseeClaim>(); + const add = (c: OdyseeClaim | null) => { + if (c && !out.has(c.claim_id)) out.set(c.claim_id, c); + }; + for (const r of responses) { + if (r.status < 200 || r.status >= 300) continue; + for (const result of resultsOf(r.body)) { + const direct = asClaim(result); + if (direct) { + add(direct); + continue; + } + const o = obj(result); + if (!o) continue; + if (Array.isArray(o.items)) for (const item of o.items) add(asClaim(item)); + for (const v of Object.values(o)) add(asClaim(v)); + } + } + return out; +} + +const STREAM_TYPES = new Set(["video", "audio"]); + +export function isStreamClaim(c: OdyseeClaim): boolean { + return (c.value_type === undefined || c.value_type === "stream") && STREAM_TYPES.has(String(c.value.stream_type)); +} + +// The video's page URL → its claim id (`…/<name>:<claim id or a prefix>`) and name. +export function odyseePageRef(pageUrl: string): { name: string | null; claimRef: string | null; channel: string | null } { + let u: URL; + try { + u = new URL(pageUrl); + } catch { + return { name: null, claimRef: null, channel: null }; + } + const segs = decodeURIComponent(u.pathname).split("/").filter(Boolean); + const last = segs.at(-1) ?? ""; + const channelSeg = segs.find((s) => s.startsWith("@")) ?? null; + const [name, ref] = last.startsWith("@") ? [null, null] : splitRef(last); + return { name, claimRef: ref, channel: channelSeg ? splitRef(channelSeg)[0] : null }; +} + +function splitRef(seg: string): [string | null, string | null] { + const i = seg.search(/[:#]/); + if (i < 0) return [seg || null, null]; + const ref = seg.slice(i + 1).toLowerCase(); + return [seg.slice(0, i) || null, /^[0-9a-f]{1,40}$/.test(ref) ? ref : null]; +} + +// The claim a VIDEO page is about: by claim id (a full id, or the prefix the +// URL carries), else by name when exactly one stream claim has it. A video +// page also resolves its recommendations, so "the one stream claim" is never +// assumed. +export function claimForPage(claims: ReadonlyMap<string, OdyseeClaim>, pageUrl: string): OdyseeClaim | null { + const { name, claimRef } = odyseePageRef(pageUrl); + const streams = [...claims.values()].filter(isStreamClaim); + if (claimRef) { + const hits = streams.filter((c) => c.claim_id.startsWith(claimRef) && (!name || c.name === name || claimRef.length === 40)); + return hits.length === 1 ? hits[0] : null; + } + if (name) { + const hits = streams.filter((c) => c.name === name); + return hits.length === 1 ? hits[0] : null; + } + return null; +} + +// yt-dlp's own rule: the v3 API path is the ORIGINAL file (lbry.py: "GET +// request to v3 API returns original video/audio file if available"). A v6 +// `/streams/` URL has no /api/ segment and is kept as it is. +export function originalFileUrl(streamingUrl: string): string { + return streamingUrl.replace(/\/api\/v\d+\//, "/api/v3/"); +} + +// The claim's file on the CDN: a `get` answer's `streaming_url` naming the +// claim, else the first URL the player asked the CDN for under the claim's +// `/streams/<claim id>/` (query and fragment dropped). +export function streamingUrlFor( + claimId: string, + responses: readonly PageApiResponse[], + mediaUrls: readonly string[] = [], +): string | null { + for (const r of responses) { + if (r.status < 200 || r.status >= 300) continue; + for (const result of resultsOf(r.body)) { + const s = str(obj(result)?.streaming_url); + if (s && s.includes(claimId)) return originalFileUrl(s); + } + } + for (const m of mediaUrls) { + try { + const u = new URL(m); + if (u.pathname.includes(`/streams/${claimId}/`)) return `${u.origin}${u.pathname}`; + } catch { + /* not a URL */ + } + } + return null; +} + +const MIME_EXT: Readonly<Record<string, string>> = { + "video/mp4": "mp4", + "video/webm": "webm", + "video/quicktime": "mov", + "video/x-matroska": "mkv", + "audio/mpeg": "mp3", + "audio/mp4": "m4a", + "audio/ogg": "ogg", +}; + +function extOf(source: Record<string, unknown> | null, url: string | null): string { + const fromName = str(source?.name)?.match(/\.([A-Za-z0-9]{2,5})$/)?.[1]; + if (fromName) return fromName.toLowerCase(); + const mime = str(source?.media_type); + if (mime && MIME_EXT[mime]) return MIME_EXT[mime]; + const fromUrl = url?.match(/\.([A-Za-z0-9]{2,5})(?:$|[?#])/)?.[1]; + return fromUrl ? fromUrl.toLowerCase() : "mp4"; +} + +const ymd = (epochSec: number | undefined): string | undefined => { + if (epochSec === undefined) return undefined; + const d = new Date(epochSec * 1000); + if (Number.isNaN(d.getTime())) return undefined; + return d.toISOString().slice(0, 10).replace(/-/g, ""); +}; + +export const BROWSER_SOURCE = "browser"; + +// The metadata.info.json a browser lookup writes: the fields yt-dlp's lbry +// extractor sets (and the derived dates its core adds), plus ONE format — +// `original`, the claim's file — when the page named it. `_source: "browser"` +// says who wrote it; a later yt-dlp prefetch rewrites the file whole. +export function odyseeInfoFromClaim( + claim: OdyseeClaim, + opts: { pageUrl: string; streamingUrl: string | null; at?: string }, +): Record<string, unknown> { + const v = claim.value; + const streamType = String(v.stream_type); + const media = obj(v[streamType]); + const source = obj(v.source); + const thumb = str(obj(v.thumbnail)?.url); + const timestamp = int(claim.timestamp); + const releaseTimestamp = int(v.release_time); + const duration = int(media?.duration); + const width = int(media?.width); + const height = int(media?.height); + const filesize = int(source?.size); + const channel = obj(claim.signing_channel); + const channelId = str(channel?.claim_id); + const uploaderId = str(channel?.name); + const tags = Array.isArray(v.tags) ? v.tags.filter((t): t is string => typeof t === "string" && t !== "") : undefined; + const url = opts.streamingUrl; + const ext = extOf(source, url); + const format = url + ? { + url, + format_id: "original", + quality: 1, + ext, + protocol: url.startsWith("http:") ? "http" : "https", + ...(filesize !== undefined ? { filesize } : {}), + ...(width !== undefined ? { width } : {}), + ...(height !== undefined ? { height } : {}), + ...(streamType === "audio" ? { vcodec: "none" } : {}), + http_headers: { Referer: "https://odysee.com/" }, + } + : null; + let basename: string | undefined; + try { + basename = decodeURIComponent(new URL(opts.pageUrl).pathname).split("/").filter(Boolean).at(-1); + } catch { + basename = undefined; + } + const info: Record<string, unknown> = { + id: claim.claim_id, + title: str(v.title) ?? claim.name, + ...(thumb ? { thumbnail: thumb, thumbnails: [{ url: thumb, id: "0" }] } : {}), + ...(str(v.description) !== undefined ? { description: v.description } : {}), + ...(str(v.license) ? { license: v.license } : {}), + ...(timestamp !== undefined ? { timestamp } : {}), + ...(releaseTimestamp !== undefined ? { release_timestamp: releaseTimestamp } : {}), + ...(tags && tags.length ? { tags } : {}), + ...(duration !== undefined ? { duration } : {}), + ...(str(obj(channel?.value)?.title) ? { channel: obj(channel?.value)?.title } : {}), + ...(channelId ? { channel_id: channelId } : {}), + ...(uploaderId ? { uploader_id: uploaderId } : {}), + ...(uploaderId && channelId ? { channel_url: `https://odysee.com/${uploaderId}:${channelId}` } : {}), + ...(format ? { formats: [format] } : {}), + is_live: false, + http_headers: { Referer: "https://odysee.com/" }, + webpage_url: opts.pageUrl, + ...(basename ? { webpage_url_basename: basename } : {}), + webpage_url_domain: "odysee.com", + extractor: "lbry", + extractor_key: "LBRY", + display_id: claim.claim_id, + fulltitle: str(v.title) ?? claim.name, + ...(ymd(timestamp ?? releaseTimestamp) ? { upload_date: ymd(timestamp ?? releaseTimestamp) } : {}), + ...(ymd(releaseTimestamp) ? { release_date: ymd(releaseTimestamp) } : {}), + // The selected format at the top level, as yt-dlp writes it. + ...(format + ? { + url: format.url, + format_id: format.format_id, + ext: format.ext, + protocol: format.protocol, + ...(filesize !== undefined ? { filesize } : {}), + ...(width !== undefined ? { width } : {}), + ...(height !== undefined ? { height } : {}), + } + : {}), + _type: "video", + _source: BROWSER_SOURCE, + ...(opts.at ? { _browserLookupAt: opts.at } : {}), + }; + return info; +} + +// A channel page's listing: its stream claims (signed by the channel, when the +// channel is known), newest first by release time, as the page URLs yt-dlp's +// listing prints (`https://odysee.com/<name>:<claim id>`). +export function listingFromResponses( + responses: readonly PageApiResponse[], + channel: { claimId?: string | null; name?: string | null }, +): { url: string; claim: OdyseeClaim }[] { + const claims = [...claimsFromResponses(responses).values()].filter(isStreamClaim); + const mine = claims.filter((c) => { + const sc = c.signing_channel; + if (channel.claimId) return sc?.claim_id === channel.claimId; + if (channel.name) return sc?.name === channel.name; + return false; + }); + const when = (c: OdyseeClaim) => int(c.value.release_time) ?? int(c.timestamp) ?? 0; + return mine + .sort((a, b) => when(b) - when(a)) + .map((claim) => ({ url: `https://odysee.com/${claim.name}:${claim.claim_id}`, claim })); +} + +// The channel claim a channel page resolved (`@name`), when it did. +export function channelClaimFor( + responses: readonly PageApiResponse[], + channelName: string, +): { claimId: string; name: string } | null { + for (const r of responses) { + if (r.status < 200 || r.status >= 300) continue; + for (const result of resultsOf(r.body)) { + const o = obj(result); + if (!o) continue; + for (const v of [o, ...Object.values(o)]) { + const c = obj(v); + if (c && c.value_type === "channel" && c.name === channelName && typeof c.claim_id === "string") { + return { claimId: c.claim_id, name: channelName }; + } + } + } + } + return null; +} diff --git a/common/testing/web/fakeOdyseePage.d.mts b/common/testing/web/fakeOdyseePage.d.mts @@ -0,0 +1,58 @@ +import type { PageApiResponse } from "../../lib/odyseePageApi"; +import type { PageApiRead, PageApiReader } from "../../ytdlp/odyseePageReader"; + +export type SyntheticChannel = { + claim_id: string; + name: string; + value_type: "channel"; + timestamp: number; + value: { title: string }; +}; + +export type SyntheticClaim = { + claim_id: string; + name: string; + value_type: "stream"; + timestamp: number; + canonical_url: string; + permanent_url: string; + signing_channel: { claim_id: string; name: string; value: { title: string } }; + value: Record<string, unknown> & { title: string; source: { sd_hash: string; media_type: string; name: string; size: string } }; +}; + +export function syntheticChannel(opts: { name: string; title?: string; claimId?: string }): SyntheticChannel; +export function syntheticClaim(opts: { + name: string; + title: string; + channel: SyntheticChannel; + claimId?: string; + releaseTime?: number; + timestamp?: number; + duration?: number; + size?: number; + sdHash?: string; + streamType?: "video" | "audio" | "binary"; + mediaType?: string; + height?: number; + width?: number; + description?: string; + tags?: string[]; +}): SyntheticClaim; +export function pageUrlOf(claim: SyntheticClaim): string; +export function channelUrlOf(channel: SyntheticChannel): string; +export function cdnUrlOf(claim: SyntheticClaim): string; +export function resolveAnswer(claims: ReadonlyArray<SyntheticClaim | SyntheticChannel>): PageApiResponse; +export function claimSearchAnswer(claims: ReadonlyArray<SyntheticClaim>, page?: number): PageApiResponse; +export function getAnswer(claim: SyntheticClaim, streamingUrl: string): PageApiResponse; +export function refusedAnswer(method: string): PageApiResponse; +export function videoPageRead(opts: { + claim: SyntheticClaim; + related?: SyntheticClaim[]; + streamingUrl?: string | null; + mediaUrls?: string[]; + get?: boolean; +}): PageApiRead; +export function channelPageRead(opts: { channel: SyntheticChannel; pages: SyntheticClaim[][] }): PageApiRead; +export function fakePageReader( + reads: Record<string, PageApiRead | ((opts: { pageUrl: string; play?: boolean; scrolls?: number }) => PageApiRead)>, +): PageApiReader & { calls: { pageUrl: string; play: boolean; scrolls: number }[] }; diff --git a/common/testing/web/fakeOdyseePage.mjs b/common/testing/web/fakeOdyseePage.mjs @@ -0,0 +1,143 @@ +// Synthetic odysee.com page reads (release 32 R9): what a headless browser's +// load of a video page or a channel page would keep of the page's own API +// answers — the LBRY SDK's JSON-RPC through Odysee's proxy (`resolve`, +// `claim_search`, `get`), in the shape yt-dlp's lbry extractor reads +// (yt_dlp/extractor/lbry.py). Invented claims, channels and hashes: nothing +// recorded from the real site. No browser and no network: `fakePageReader` +// answers a PageApiReader call from these. +// +// const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" }); +// const v = syntheticClaim({ name: "a-synthetic-stream", title: "…", channel: ch, releaseTime: 1700000000 }); +// const read = videoPageRead({ claim: v, related: [other], streamingUrl: cdnUrlOf(v) }); +// const reader = fakePageReader({ [pageUrlOf(v)]: read }); // reader.calls lists every call + +const PROXY = "https://api.na-backend.odysee.com/api/v1/proxy"; + +function hex40(seed) { + let h = ""; + let x = 0x9e3779b9 ^ [...String(seed)].reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 7); + while (h.length < 40) { + x = (x * 1103515245 + 12345) >>> 0; + h += (x >>> 8).toString(16).padStart(6, "0"); + } + return h.slice(0, 40); +} + +export function syntheticChannel({ name, title, claimId }) { + return { + claim_id: claimId ?? hex40(`channel:${name}`), + name, + value_type: "channel", + timestamp: 1690000000, + value: { title: title ?? name.slice(1) }, + }; +} + +export function syntheticClaim({ + name, + title, + channel, + claimId, + releaseTime = 1700000000, + timestamp, + duration = 3600, + size = 123456789, + sdHash, + streamType = "video", + mediaType = "video/mp4", + height = 720, + width = 1280, + description = "A synthetic stream.", + tags = ["synthetic"], +}) { + const id = claimId ?? hex40(`stream:${name}`); + return { + claim_id: id, + name, + value_type: "stream", + timestamp: timestamp ?? releaseTime + 60, + canonical_url: `lbry://${channel.name}#${channel.claim_id.slice(0, 1)}/${name}#${id.slice(0, 1)}`, + permanent_url: `lbry://${name}#${id}`, + signing_channel: { claim_id: channel.claim_id, name: channel.name, value: { title: channel.value.title } }, + value: { + title, + description, + license: "None", + // The SDK answers these as strings. + release_time: String(releaseTime), + tags, + stream_type: streamType, + source: { + media_type: mediaType, + name: `${name}.mp4`, + sd_hash: sdHash ?? hex40(`sd:${name}`) + hex40(`sd2:${name}`).slice(0, 56), + size: String(size), + }, + thumbnail: { url: `https://thumbs.odycdn.com/${hex40(`th:${name}`).slice(0, 32)}.webp` }, + [streamType]: streamType === "video" ? { duration, height, width } : { duration }, + }, + }; +} + +export const pageUrlOf = (claim) => `https://odysee.com/${claim.name}:${claim.claim_id}`; +export const channelUrlOf = (channel) => `https://odysee.com/${channel.name}`; +export const cdnUrlOf = (claim) => + `https://player.odycdn.com/v6/streams/${claim.claim_id}/${claim.value.source.sd_hash.slice(0, 6)}.mp4`; + +const rpc = (method, params, result, status = 200) => ({ + url: `${PROXY}?m=${method}`, + status, + request: { jsonrpc: "2.0", method, params, id: 1 }, + body: status === 200 ? { jsonrpc: "2.0", result, id: 1 } : { error: { code: status, message: "Too Many Requests" } }, +}); + +export const resolveAnswer = (claims) => + rpc( + "resolve", + { urls: claims.map((c) => c.permanent_url ?? `lbry://${c.name}#${c.claim_id}`) }, + Object.fromEntries(claims.map((c) => [c.permanent_url ?? `lbry://${c.name}#${c.claim_id}`, c])), + ); + +export const claimSearchAnswer = (claims, page = 1) => + rpc("claim_search", { page, page_size: claims.length, no_totals: true }, { items: claims, page, page_size: claims.length }); + +export const getAnswer = (claim, streamingUrl) => + rpc("get", { uri: claim.permanent_url, save_file: false }, { streaming_url: streamingUrl, claim_id: claim.claim_id }); + +export const refusedAnswer = (method) => rpc(method, {}, null, 429); + +// A video page: its resolve (the claim plus recommendations), the related +// claim_search, the player's get and its CDN request. +export function videoPageRead({ claim, related = [], streamingUrl, mediaUrls, get = true }) { + const url = streamingUrl === undefined ? cdnUrlOf(claim) : streamingUrl; + return { + ok: true, + responses: [ + resolveAnswer([claim]), + ...(related.length ? [claimSearchAnswer(related)] : []), + ...(get && url ? [getAnswer(claim, url)] : []), + ], + mediaUrls: mediaUrls ?? (url ? [`${url}?range=0`] : []), + }; +} + +// A channel page: its resolve, and one claim_search per page of uploads. +export function channelPageRead({ channel, pages }) { + return { + ok: true, + responses: [resolveAnswer([channel]), ...pages.map((p, i) => claimSearchAnswer(p, i + 1))], + mediaUrls: [], + }; +} + +export function fakePageReader(reads) { + const calls = []; + const reader = async ({ pageUrl, play, scrolls }) => { + calls.push({ pageUrl, play: Boolean(play), scrolls: scrolls ?? 0 }); + const hit = reads[pageUrl] ?? reads["*"]; + if (!hit) return { ok: false, responses: [], mediaUrls: [], error: `no recorded read for ${pageUrl}` }; + return typeof hit === "function" ? hit({ pageUrl, play, scrolls }) : hit; + }; + reader.calls = calls; + return reader; +} diff --git a/common/ytdlp/browserLookupDownload.test.ts b/common/ytdlp/browserLookupDownload.test.ts @@ -0,0 +1,143 @@ +// downloadOneManaged with the browser lookup (release 32 R9): a record that +// stores no media URL is read from its page (a fake page reader — no browser) +// and downloaded from the file the page named, from a fake CDN on loopback; +// the channel's title match filter still decides; off, nothing changes. Real +// ffmpeg for the audio check (skipped without it). No real network. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/browserLookupDownload.test.ts + +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"; +import { hasFfmpeg, makeToneFile } from "../testing/audio/corruptAudio.mjs"; +import { startFakeRangedCdn, type FakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; +import { fakePageReader, syntheticChannel, syntheticClaim, videoPageRead } from "../testing/web/fakeOdyseePage.mjs"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { Paths } from "../lib/paths"; +import { storedUrlAttemptOf } from "../lib/downloadOutcome"; +import { clearPlatformGaps } from "../jobs/platformGap"; +import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged"; + +const FF = hasFfmpeg(); +const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUEfedcba98"; +const FILE_PATH = `/v6/streams/${CLAIM}/d4e5f6.mp4`; +const PAGE = `https://odysee.com/synthetic-stream:${CLAIM}`; +const FAST = { intervalMs: 0, sizeGateBytes: 0, maxRollbacks: 3 }; +const ch = syntheticChannel({ name: "@synth", title: "Synth" }); + +type Fixture = { root: string; videoDir: string; ytdlpLog: string; paths: Paths; cdn: FakeRangedCdn }; + +async function fixture(opts: { prefetch?: "ok" | "429" } = {}): Promise<Fixture> { + const root = await mkdtemp(path.join(os.tmpdir(), "browser-download-")); + const channelsDir = path.join(root, "channels"); + const videoDir = path.join(channelsDir, "c", "data", CLAIM); + await mkdir(videoDir, { recursive: true }); + const clean = FF ? await readFile(makeToneFile(path.join(root, "src.mp4"), { duration: 30, faststart: true })) : Buffer.alloc(1); + const cdn = await startFakeRangedCdn({ files: { [FILE_PATH]: clean } }); + const ytdlpLog = path.join(root, "ytdlp.log"); + const bin = path.join(root, "fake-ytdlp.sh"); + const line429 = `echo "ERROR: [lbry] ${CLAIM}: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; exit 1`; + await writeFile( + bin, + `#!/bin/sh\necho "$@" >> ${JSON.stringify(ytdlpLog)}\n` + + `case "$*" in *--skip-download*) ${opts.prefetch === "429" ? line429 : "exit 0"} ;; esac\nexit 0\n`, + ); + await chmod(bin, 0o755); + const paths = { channelsDir, ytdlpBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; + return { root, videoDir, ytdlpLog, paths, cdn }; +} + +function claim(title = "SynthShow - 01/02/2024") { + return syntheticClaim({ name: "synthetic-stream", title, channel: ch, claimId: CLAIM, duration: 30 }); +} + +function run(f: Fixture, reader: ReturnType<typeof fakePageReader>, over: Partial<ManagedDownloadOpts> = {}, log = { s: "" }) { + return downloadOneManaged({ + channelSlug: "c", + channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth", audioFormat: "mp3", browserLookup: true } as ChannelConfig, + paths: f.paths, + videoUrl: PAGE, + onLog: (s) => (log.s += s), + signal: new AbortController().signal, + storedUrlDeps: { fetch: f.cdn.fetch, chunkBytes: 16 * 1024, knobs: FAST, gapMs: 0, openPage: null }, + browserLookupDeps: { reader, gapMs: 0 }, + ...over, + }); +} + +async function done(f: Fixture) { + clearPlatformGaps(); + await f.cdn.close(); + await rm(f.root, { recursive: true, force: true }); +} + +test("only, no record: the page is read, the record written, the file downloaded from the URL it named", { skip: !FF }, async () => { + const f = await fixture(); + try { + const reader = fakePageReader({ [PAGE]: videoPageRead({ claim: claim(), streamingUrl: f.cdn.url(FILE_PATH) }) }); + const log = { s: "" }; + const record = await run(f, reader, { storedUrl: "only" }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.equal(reader.calls.length, 1); + assert.equal(storedUrlAttemptOf(record)?.why, "only"); + const info = JSON.parse(await readFile(path.join(f.videoDir, "metadata.info.json"), "utf8")); + assert.equal(info._source, "browser"); + assert.equal(info.formats[0].url, f.cdn.url(FILE_PATH)); + assert.match(log.s, /stores no media URL; reading its record from the page in a browser/); + } finally { + await done(f); + } +}); + +test("fallback, the prefetch rate-limited and no record: the browser lookup, then the stored-URL download", { skip: !FF }, async () => { + const f = await fixture({ prefetch: "429" }); + try { + const reader = fakePageReader({ "*": videoPageRead({ claim: claim(), streamingUrl: f.cdn.url(FILE_PATH) }) }); + const log = { s: "" }; + const record = await run(f, reader, { storedUrl: "fallback" }, log); + assert.equal(record.status, "ok-audio-checked", log.s); + assert.equal(storedUrlAttemptOf(record)?.why, "rate-limited", "the platform still backs off"); + assert.equal(reader.calls.length, 1); + } finally { + await done(f); + } +}); + +test("the channel's title match filter declines what the page found: skipped, no CDN read", async () => { + const f = await fixture(); + try { + const reader = fakePageReader({ "*": videoPageRead({ claim: claim("A vlog"), streamingUrl: f.cdn.url(FILE_PATH) }) }); + const record = await run(f, reader, { + storedUrl: "only", + channelConfig: { + handling: "transcribe", + url: "https://odysee.com/@synth", + browserLookup: true, + ytdlpExtraArgs: ["--match-filters=title~='SynthShow'"], + } as ChannelConfig, + }); + assert.equal(record.status, "skipped-filtered"); + assert.equal(record.filter?.name, "ytdlpMatchFilter"); + assert.equal(f.cdn.requests.length, 0); + } finally { + await done(f); + } +}); + +test("browserLookup off: no page is read, and `only` with no record fails asking nothing (as before)", async () => { + const f = await fixture(); + try { + const reader = fakePageReader({ "*": videoPageRead({ claim: claim(), streamingUrl: f.cdn.url(FILE_PATH) }) }); + const record = await run(f, reader, { + storedUrl: "only", + channelConfig: { handling: "transcribe", url: "https://odysee.com/@synth" } as ChannelConfig, + }); + assert.equal(record.status, "failed"); + assert.equal(record.failureClass, "per_video"); + assert.equal(reader.calls.length, 0); + } finally { + await done(f); + } +}); diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -118,6 +118,13 @@ import type { DownloadFailureClass } from "../lib/availability"; import { platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; import { noteStoredUrlRead } from "../jobs/storedUrlPace"; import { + BROWSER_LOOKUP_PLATFORMS, + browserLookupDecision, + browserLookupVideo, + browserLookupWanted, + type BrowserLookupDeps, +} from "./odyseeBrowserLookup"; +import { storedUrlDownload, type StoredUrlDownloadDeps, type StoredUrlDownloadResult, @@ -232,6 +239,14 @@ export type ManagedDownloadOpts = { // The platform is HELD and the caller's door let this run through as // `only` (the log and the attempt say "held" rather than "only"). storedUrlHeld?: boolean; + // THE BROWSER LOOKUP (release 32 R9, ytdlp/odyseeBrowserLookup.ts): with a + // stored-URL mode, a record that stores no media URL — `only`, or a + // `fallback` whose prefetch was rate-limited — is read from the video's page + // in a headless browser first, and downloaded from the file the page named. + // Absent = the channel's `browserLookup`. + browserLookup?: boolean; + // Test seam: the page reader and the gap. Production callers pass none. + browserLookupDeps?: BrowserLookupDeps; // Test seam: the CDN fetch, the chunk, the audio check's knobs, and the gap // between two stored-URL files (default STORED_URL_NEW_FILE_GAP_MS) with // its sleep. Every production caller passes none. @@ -823,11 +838,16 @@ async function runManagedDownload( // platform refused writes nothing useful, and the stored URL is the record's. const storedMode = resolveStoredUrlMode(opts.storedUrl, opts.channelConfig.storedUrlDownloads); const storedDir = canonicalId ? path.join(channelDir, "data", canonicalId) : null; - const stored = + let stored = storedMode !== "never" && opts.channelConfig.handling === "transcribe" && storedDir ? await storedMediaUrl(storedDir) : null; if (storedMode === "only" && canonicalId && storedDir) { + if (!stored) { + const looked = await storedViaBrowserLookup(opts, storedDir, canonicalId, startedAt, attempts); + if (looked && "record" in looked) return looked.record; + if (looked) stored = looked.stored; + } if (stored) { return runStoredUrlDownload(opts, { videoDir: storedDir, @@ -953,7 +973,13 @@ async function runManagedDownload( classifyDownloadFailure(lastFullTail, lastPrefetch.availabilityClass) === "rate_limit" ) { - if (stored && storedMode === "fallback") { + let fallbackStored = stored; + if (!fallbackStored && storedMode === "fallback" && opts.channelConfig.handling === "transcribe") { + const looked = await storedViaBrowserLookup(opts, videoDir, canonicalId, startedAt, attempts); + if (looked && "record" in looked) return looked.record; + if (looked) fallbackStored = looked.stored; + } + if (fallbackStored && storedMode === "fallback") { opts.onLog( `Metadata prefetch for ${canonicalId} was rate-limited by the source; ` + `downloading from the stored media URL instead (the platform still backs off).\n`, @@ -963,7 +989,7 @@ async function runManagedDownload( videoId: canonicalId, channelDir, startedAt, - stored, + stored: fallbackStored, why: "rate-limited", attempts, lastFullTail, @@ -2189,6 +2215,85 @@ async function runStoredUrlDownload( }); } +// THE BROWSER LOOKUP FOR A DOWNLOAD (release 32 R9): the record stores no +// media URL; when the request or the channel asks for it, read the record from +// the video's page in a headless browser. null = not asked (or it found no +// file: the caller goes on as without it); `stored` = download from it; +// `record` = the outcome already written (the channel's filters declined the +// video, or its match filter cannot be applied to a lookup). +async function storedViaBrowserLookup( + opts: ManagedDownloadOpts, + videoDir: string, + videoId: string, + startedAt: string, + attempts: DownloadAttempt[], +): Promise<{ stored: StoredMediaUrl } | { record: DownloadOutcomeRecord } | null> { + if (!browserLookupWanted(opts.browserLookup, opts.channelConfig)) return null; + if (opts.channelConfig.handling !== "transcribe") return null; + const platform = detectPlatform(opts.videoUrl); + if (!platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform) || opts.signal.aborted) return null; + opts.onLog(`${videoId} stores no media URL; reading its record from the page in a browser (browser lookup).\n`); + const r = await browserLookupVideo({ + videoDir, + pageUrl: opts.videoUrl, + onLog: opts.onLog, + signal: opts.signal, + ...(opts.browserLookupDeps ? { deps: opts.browserLookupDeps } : {}), + }); + if ("error" in r) { + opts.onLog(`Browser lookup of ${videoId}: ${r.status} — ${r.error}.\n`); + return null; + } + if (!r.stored) { + opts.onLog(`Browser lookup of ${videoId}: the page named no media file the allowlist trusts.\n`); + return null; + } + const d = browserLookupDecision( + opts.channelConfig, + r.info, + { skipLiveDownloads: opts.globalSkipLiveDownloads ?? true }, + (line) => opts.onLog(line.endsWith("\n") ? line : `${line}\n`), + ); + if (d.ok) return { stored: r.stored }; + if (!d.skip) { + opts.onLog(`Not downloading ${videoId}: ${d.reason}.\n`); + attempts.push({ + n: 1, + kind: "stored-url-ranged", + handling: opts.channelConfig.handling, + usedCookies: false, + ytdlpExitCode: 1, + error: `browser lookup: ${d.reason}`, + }); + return { + record: await writeOutcome(opts, videoDir, { + videoId, + status: "failed", + startedAt, + attempts, + lastFullTail: "", + failureClass: "per_video", + }), + }; + } + opts.onLog(`Skipping ${videoId}: ${d.reason} [filter=${d.filter}]\n`); + const record: DownloadOutcomeRecord = { + videoId, + webpageUrl: opts.videoUrl, + status: "skipped-filtered", + startedAt, + finishedAt: new Date().toISOString(), + attempts, + filter: { name: d.filter, reason: d.reason }, + }; + try { + await writeDownloadOutcome(videoDir, record); + } catch (err) { + opts.onLog(`Failed to write download-outcome.json: ${(err as Error).message}\n`); + } + return { record }; +} + // `only`, and the record stores no media URL the allowlist trusts (or the // channel is not transcribe handling): nothing is asked of anyone. A per-video // failure, so a batch goes on to the next video. diff --git a/common/ytdlp/odyseeBrowserLookup.test.ts b/common/ytdlp/odyseeBrowserLookup.test.ts @@ -0,0 +1,139 @@ +// One video's metadata from its page in a (fake) browser (release 32 R9): the +// record written whole or patched, paced, and the channel's filters applied to +// what it finds. No browser: testing/web/fakeOdyseePage.mjs answers. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/odyseeBrowserLookup.test.ts + +import { test, beforeEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + browserLookupDecision, + browserLookupGapKey, + browserLookupVideo, + browserLookupWanted, + matchFiltersOf, + titleMatchFilter, +} from "./odyseeBrowserLookup"; +import { readOdyseePage } from "./odyseePageReader"; +import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap"; +import { + cdnUrlOf, + fakePageReader, + pageUrlOf, + syntheticChannel, + syntheticClaim, + videoPageRead, +} from "../testing/web/fakeOdyseePage.mjs"; +import type { ChannelConfig } from "../lib/channelConfig"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "browserlookup-")); +const ch = syntheticChannel({ name: "@synthchan", title: "Synth Channel" }); +const v1 = syntheticClaim({ name: "first-stream", title: "SynthShow - 01/02/2024 - Topics", channel: ch }); +const other = syntheticClaim({ name: "recommended", title: "Someone Else", channel: syntheticChannel({ name: "@other" }) }); +let n = 0; +const dirOf = () => path.join(ROOT, `case-${++n}`, "data", v1.claim_id); +const noLog = () => {}; +const signal = new AbortController().signal; + +beforeEach(() => clearPlatformGaps()); + +test("no record yet: the whole record is written from the page, with its stored media URL", async () => { + const reader = fakePageReader({ [pageUrlOf(v1)]: videoPageRead({ claim: v1, related: [other] }) }); + const dir = dirOf(); + const r = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 0 } }); + assert.equal(r.status, "written"); + assert.ok("stored" in r && r.stored?.url === cdnUrlOf(v1)); + const disk = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")); + assert.equal(disk._source, "browser"); + assert.equal(disk.id, v1.claim_id); + assert.deepEqual(reader.calls, [{ pageUrl: pageUrlOf(v1), play: true, scrolls: 0 }], "a video page is played"); +}); + +test("a record with no stored URL is patched (the format and what it lacks), in the history as browser-lookup", async () => { + const dir = dirOf(); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ id: v1.claim_id, title: "Kept Title", webpage_url: pageUrlOf(v1), extractor: "lbry" }), + ); + const reader = fakePageReader({ "*": videoPageRead({ claim: v1 }) }); + const r = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 0 } }); + assert.equal(r.status, "patched"); + const disk = JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")); + assert.equal(disk.title, "Kept Title", "a key it has is never replaced"); + assert.equal(disk.formats[0].url, cdnUrlOf(v1)); + assert.equal(disk._source, undefined, "a patched yt-dlp record is not re-labelled"); + assert.ok(disk._browserLookupAt); + const history = JSON.parse(await readFile(path.join(dir, "metadata.history.json"), "utf8")); + assert.equal(history.entries.at(-1).by, "browser-lookup"); + const again = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 0 } }); + assert.equal(again.status, "unchanged"); +}); + +test("a page that names no such claim is not-found; one that cannot be read is unreadable; nothing written", async () => { + const dir = dirOf(); + const wrong = fakePageReader({ "*": videoPageRead({ claim: other }) }); + const r = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader: wrong, gapMs: 0 } }); + assert.equal(r.status, "not-found"); + const dead = fakePageReader({}); + const r2 = await browserLookupVideo({ videoDir: dir, pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader: dead, gapMs: 0 } }); + assert.equal(r2.status, "unreadable"); + await assert.rejects(readFile(path.join(dir, "metadata.info.json"))); +}); + +test("not an Odysee page: refused before any read", async () => { + const reader = fakePageReader({ "*": videoPageRead({ claim: v1 }) }); + const r = await browserLookupVideo({ videoDir: dirOf(), pageUrl: "https://www.youtube.com/watch?v=abcdefghijk", onLog: noLog, signal, deps: { reader } }); + assert.equal(r.status, "refused"); + assert.equal(reader.calls.length, 0); +}); + +test("paced: the second lookup on the platform waits out the gap the first set", async () => { + const reader = fakePageReader({ "*": videoPageRead({ claim: v1 }) }); + const waits: number[] = []; + const sleep = async (ms: number) => { + waits.push(ms); + clearPlatformGaps(); + }; + await browserLookupVideo({ videoDir: dirOf(), pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 60_000, sleep } }); + assert.deepEqual(waits, []); + assert.ok(platformGapRemainingMs(browserLookupGapKey("odysee")) > 55_000); + await browserLookupVideo({ videoDir: dirOf(), pageUrl: pageUrlOf(v1), onLog: noLog, signal, deps: { reader, gapMs: 60_000, sleep } }); + assert.equal(waits.length, 1); +}); + +test("the real reader never opens a browser under a test runner", async () => { + const log = { s: "" }; + const r = await readOdyseePage({ pageUrl: pageUrlOf(v1), signal, onLog: (s) => (log.s += s) }); + assert.equal(r.ok, false); + assert.match(r.error ?? "", /test runner/); +}); + +test("the opt-in: the request's word, else the channel's", () => { + assert.equal(browserLookupWanted(undefined, {}), false); + assert.equal(browserLookupWanted(undefined, { browserLookup: true }), true); + assert.equal(browserLookupWanted(false, { browserLookup: true }), false); + assert.equal(browserLookupWanted(true, {}), true); +}); + +test("the channel's yt-dlp title match filter is applied; one it cannot read refuses", () => { + assert.deepEqual(matchFiltersOf({ ytdlpExtraArgs: ["--match-filters=title~='SynthShow'", "--match-filter", "title~=\"(?i)other\""] }), [ + "title~='SynthShow'", + 'title~="(?i)other"', + ]); + assert.ok(titleMatchFilter("title~='(?i)synthshow'")?.test("SYNTHSHOW live")); + assert.equal(titleMatchFilter("duration>600"), null); + assert.equal(titleMatchFilter("title~='a' & duration>600"), null); + const cfg = (args: string[]) => ({ handling: "transcribe", ytdlpExtraArgs: args }) as ChannelConfig; + const s = { skipLiveDownloads: true }; + assert.deepEqual(browserLookupDecision(cfg(["--match-filters=title~='SynthShow'"]), { title: "SynthShow - x" }, s), { ok: true }); + const no = browserLookupDecision(cfg(["--match-filters=title~='SynthShow'"]), { title: "A vlog" }, s); + assert.equal(no.ok, false); + assert.ok(!no.ok && no.skip && no.filter === "ytdlpMatchFilter"); + const cannot = browserLookupDecision(cfg(["--match-filters=duration>600"]), { title: "SynthShow" }, s); + assert.ok(!cannot.ok && !cannot.skip); + assert.deepEqual(browserLookupDecision(cfg([]), { title: "anything" }, s), { ok: true }); +}); diff --git a/common/ytdlp/odyseeBrowserLookup.ts b/common/ytdlp/odyseeBrowserLookup.ts @@ -0,0 +1,263 @@ +// ONE VIDEO'S METADATA FROM ITS PAGE, IN A BROWSER (release 32 R9). +// +// When yt-dlp's lbry lookup answers 429 (the prefetch, a refresh), a record +// that was never fetched has no metadata.info.json — and so no stored media +// URL for the stored-URL download (lib/storedMediaUrl.ts) to read. The page +// itself answers a browser (measured 2026-10-17), so this opens the video's +// page (ytdlp/odyseePageReader.ts), reads the claim and the file the player +// asks for out of the page's own API answers (lib/odyseePageApi.ts), and +// writes the record yt-dlp would have written, marked `_source: "browser"`. +// +// WHAT IS WRITTEN. No file yet: the whole record. A file already there: only +// what it lacks — keys it does not have, and the one `original` format (with +// its top-level twins) when it stores no media URL the allowlist trusts — +// through `patchMetadataInfo` as writer `browser-lookup`, so the change is in +// metadata.history.json. A yt-dlp prefetch later rewrites the file whole, as +// it always has. +// +// PACED LIKE THE LOOKUP: one page per platform per BROWSER_LOOKUP gap (the +// platform's import floor, 60 s on Odysee), waited out before and set at the +// start and the end (jobs/platformGap.ts, key `browser-lookup:<platform>`). +// +// THE CHANNEL'S FILTERS STILL DECIDE. A lookup asks no yt-dlp, so the +// channel's `--match-filter(s)` in `ytdlpExtraArgs` would never be applied to +// what it finds: `browserLookupDecision` applies the one form it can read +// (`title~='<regex>'`) and the app's download filters, and a channel whose +// match filter it cannot read is refused rather than fetched unfiltered. +// +// Odysee only (BROWSER_LOOKUP_PLATFORMS); opt-in per channel +// (`browserLookup`) or per request. + +import path from "node:path"; +import { mkdir, readFile } from "node:fs/promises"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { detectPlatform } from "../lib/platform"; +import { writeJsonAtomic } from "../lib/jsonFile-server"; +import { patchMetadataInfo } from "../lib/metadataHistory-server"; +import { storedMediaUrlFromInfo, type StoredMediaUrl } from "../lib/storedMediaUrl"; +import { + claimForPage, + claimsFromResponses, + odyseeInfoFromClaim, + streamingUrlFor, +} from "../lib/odyseePageApi"; +import { evaluateDownloadFilters } from "../lib/downloadFilters"; +import { notePlatformGap, platformGapRemainingMs, waitForPlatformGap } from "../jobs/platformGap"; +import { platformImportMinGapSeconds } from "./platformArgs.mjs"; +import { readOdyseePage, type PageApiReader } from "./odyseePageReader"; + +export const BROWSER_LOOKUP_PLATFORMS: readonly string[] = ["odysee"]; + +export function browserLookupGapKey(platform: string): string { + return `browser-lookup:${platform}`; +} + +export function browserLookupGapMs(platform: string): number { + // A recorded read (the e2e server's E2E_ODYSEE_PAGE_FIXTURE) asks no + // platform anything: no gap. + if (process.env.E2E_ODYSEE_PAGE_FIXTURE) return 0; + return Math.max(60, platformImportMinGapSeconds(platform)) * 1000; +} + +// The request's choice, else the channel's. +export function browserLookupWanted( + request: boolean | undefined, + config: Pick<ChannelConfig, "browserLookup">, +): boolean { + return request ?? config.browserLookup === true; +} + +export type BrowserLookupDeps = { + reader?: PageApiReader; + // The gap between two page reads on a platform (absent = browserLookupGapMs). + gapMs?: number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; +}; + +export type BrowserLookupResult = + | { + status: "written" | "patched" | "unchanged"; + info: Record<string, unknown>; + stored: StoredMediaUrl | null; + claimId: string; + } + | { status: "refused" | "unreadable" | "not-found"; error: string }; + +const INFO_JSON = "metadata.info.json"; + +// Keys of the one format's top-level twins: written together or not at all. +const FORMAT_KEYS = ["formats", "url", "format_id", "ext", "protocol", "filesize", "width", "height"] as const; + +export async function browserLookupVideo(opts: { + videoDir: string; + pageUrl: string; + onLog: (s: string) => void; + signal: AbortSignal; + requestedBy?: string; + deps?: BrowserLookupDeps; +}): Promise<BrowserLookupResult> { + const { videoDir, pageUrl, onLog, signal } = opts; + const platform = detectPlatform(pageUrl); + if (!platform || !BROWSER_LOOKUP_PLATFORMS.includes(platform)) { + return { status: "refused", error: `a browser lookup is for ${BROWSER_LOOKUP_PLATFORMS.join(", ")} pages, not ${pageUrl}` }; + } + const key = browserLookupGapKey(platform); + const gapMs = opts.deps?.gapMs ?? browserLookupGapMs(platform); + try { + await waitForPlatformGap({ + label: `A browser lookup (${platform})`, + remainingMs: () => platformGapRemainingMs(key), + signal, + onLog: (line) => onLog(`${line}\n`), + ...(opts.deps?.sleep ? { sleep: opts.deps.sleep } : {}), + }); + } catch { + return { status: "unreadable", error: "cancelled while waiting for the gap between browser lookups" }; + } + notePlatformGap(key, gapMs); + const reader = opts.deps?.reader ?? readOdyseePage; + let read; + try { + read = await reader({ pageUrl, signal, onLog, play: true }); + } finally { + notePlatformGap(key, gapMs); + } + if (!read.ok && read.responses.length === 0) { + return { status: "unreadable", error: `the page could not be read (${read.error ?? "no API answer"})` }; + } + const claims = claimsFromResponses(read.responses); + const claim = claimForPage(claims, pageUrl); + if (!claim) { + return { + status: "not-found", + error: `the page's API answers (${read.responses.length}) name no stream claim for ${pageUrl}`, + }; + } + const streamingUrl = streamingUrlFor(claim.claim_id, read.responses, read.mediaUrls); + const at = new Date().toISOString(); + const info = odyseeInfoFromClaim(claim, { pageUrl, streamingUrl, at }); + onLog( + `The page names ${claim.claim_id} ("${String(info.title)}")` + + (streamingUrl ? `, its file ${new URL(streamingUrl).host}` : ", but no media file") + + ".\n", + ); + + const file = path.join(videoDir, INFO_JSON); + let current: Record<string, unknown> | null = null; + let exists = false; + try { + const text = await readFile(file, "utf8"); + exists = true; + const parsed: unknown = JSON.parse(text); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) current = parsed as Record<string, unknown>; + } catch { + current = null; + } + if (exists && !current) { + return { status: "refused", error: `${file} is not a JSON object; not overwriting it` }; + } + if (!current) { + await mkdir(videoDir, { recursive: true }); + await writeJsonAtomic(file, info, { indent: 0, newline: false }); + onLog(`Wrote ${INFO_JSON} from the page (_source: browser).\n`); + return { status: "written", info, stored: storedMediaUrlFromInfo(info), claimId: claim.claim_id }; + } + const patch: Record<string, unknown> = {}; + const missing = (v: unknown) => v === undefined || v === null || v === ""; + for (const [k, v] of Object.entries(info)) { + if ((FORMAT_KEYS as readonly string[]).includes(k) || k === "_source" || k === "_browserLookupAt") continue; + if (missing(current[k])) patch[k] = v; + } + if (!storedMediaUrlFromInfo(current) && Array.isArray(info.formats)) { + for (const k of FORMAT_KEYS) if (info[k] !== undefined) patch[k] = info[k]; + } + if (Object.keys(patch).length === 0) { + onLog(`${INFO_JSON} already has everything the page named; nothing written.\n`); + return { status: "unchanged", info: current, stored: storedMediaUrlFromInfo(current), claimId: claim.claim_id }; + } + patch._browserLookupAt = at; + await patchMetadataInfo(videoDir, patch, { + by: "browser-lookup", + ...(opts.requestedBy ? { requestedBy: opts.requestedBy } : {}), + onLog, + }); + const next = { ...current, ...patch }; + onLog(`Patched ${INFO_JSON} from the page: ${Object.keys(patch).filter((k) => !k.startsWith("_")).join(", ")}.\n`); + return { status: "patched", info: next, stored: storedMediaUrlFromInfo(next), claimId: claim.claim_id }; +} + +// ---- The channel's filters, applied to what a browser lookup found ---- + +// yt-dlp's match filters in the channel's extra args, as `--match-filter(s) +// EXPR` or `--match-filter(s)=EXPR`. +export function matchFiltersOf(config: Pick<ChannelConfig, "ytdlpExtraArgs">): string[] { + const args = config.ytdlpExtraArgs ?? []; + const out: string[] = []; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + const m = /^--match-filters?=(.*)$/s.exec(a); + if (m) out.push(m[1]); + else if ((a === "--match-filter" || a === "--match-filters") && i + 1 < args.length) out.push(args[++i]); + } + return out; +} + +// One filter of the form yt-dlp's `title~='<regex>'` (re.search; an inline +// `(?i)` at the start is the case-insensitive flag). Anything else — another +// field, `&`, `!`, a comparison — is not readable here: null. +export function titleMatchFilter(expr: string): RegExp | null { + const m = /^\s*title\s*~=\s*(?:'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)")\s*$/s.exec(expr); + if (!m) return null; + let src = m[1] ?? m[2] ?? ""; + let flags = ""; + if (src.startsWith("(?i)")) { + src = src.slice(4); + flags = "i"; + } + try { + return new RegExp(src, flags); + } catch { + return null; + } +} + +export type BrowserLookupDecision = + | { ok: true } + | { ok: false; skip: true; filter: string; reason: string } + | { ok: false; skip: false; reason: string }; + +// Whether a record found by a browser lookup may be downloaded (or listed): +// the channel's readable match filters (yt-dlp ORs several), then the app's +// download filters. A match filter this cannot read refuses outright. +export function browserLookupDecision( + config: ChannelConfig, + info: Record<string, unknown>, + settings: { skipLiveDownloads: boolean }, + onLog?: (line: string) => void, +): BrowserLookupDecision { + const exprs = matchFiltersOf(config); + if (exprs.length > 0) { + const res = exprs.map(titleMatchFilter); + if (res.some((r) => r === null)) { + return { + ok: false, + skip: false, + reason: + `the channel's yt-dlp match filter (${exprs.join(" | ")}) cannot be applied to a browser lookup — ` + + `only title~='<regex>' can`, + }; + } + const title = typeof info.title === "string" ? info.title : ""; + if (!res.some((r) => r!.test(title))) { + return { ok: false, skip: true, filter: "ytdlpMatchFilter", reason: `the title does not match ${exprs.join(" | ")}` }; + } + } + const decision = evaluateDownloadFilters({ + metadata: info as never, + channelConfig: config, + settings, + ...(onLog ? { onLog } : {}), + }); + if (decision?.skip) return { ok: false, skip: true, filter: decision.filter, reason: decision.reason }; + return { ok: true }; +} diff --git a/common/ytdlp/odyseePageReader.ts b/common/ytdlp/odyseePageReader.ts @@ -0,0 +1,171 @@ +// READ AN ODYSEE PAGE THE WAY A BROWSER LOADS IT (release 32 R9). +// +// The live finding (2026-10-17): a headless Chromium page load of odysee.com +// gets 200 from Odysee's API where yt-dlp's lbry extractor gets 429. So when +// the lookup is refused, the page itself is opened — a fresh context, no +// cookies, the same headless Playwright as the player-page opener +// (storedUrlPageOpen.ts) — and every JSON answer of the API hosts +// (lib/odyseePageApi.ts ODYSEE_API_HOSTS) is kept with its request body, plus +// the URLs the player asks the CDN for. lib/odyseePageApi.ts reads them. +// +// A VIDEO page is played for a few seconds (so the player asks `get` and the +// CDN for the file — which is also the page open that unlocks the CDN for a +// stored-URL read that follows). A CHANNEL page is scrolled `scrolls` times, a +// few seconds apart, so it lists more of its uploads. +// +// INJECTED: callers take a `PageApiReader`; tests pass a fake built from +// recorded answers and never launch a browser. Under a test runner +// (NODE_TEST_CONTEXT) the real reader refuses. On the e2e server, +// E2E_ODYSEE_PAGE_FIXTURE names a JSON file of recorded reads keyed by page URL +// (`"*"` for any), answered instead of a browser. + +import { readFile } from "node:fs/promises"; +import { importPlaywright } from "../social/playwrightRuntime"; +import { isOdyseeApiUrl, type PageApiResponse } from "../lib/odyseePageApi"; + +export type PageApiRead = { + ok: boolean; + responses: PageApiResponse[]; + // The CDN URLs the player requested, in order. + mediaUrls: string[]; + error?: string; +}; + +export type PageApiReader = (opts: { + pageUrl: string; + signal: AbortSignal; + onLog: (s: string) => void; + // A video page: press play and let it play (the player asks for its file). + play?: boolean; + // A channel page: scroll to the end this many times. + scrolls?: number; +}) => Promise<PageApiRead>; + +export const PAGE_READ_SETTLE_MS = 10_000; +export const PAGE_READ_PLAY_MS = 8_000; +export const PAGE_READ_SCROLL_MS = 3_000; +export const PAGE_READ_GOTO_TIMEOUT_MS = 45_000; +// A bound on one channel read: a page that keeps loading forever is not read +// forever. +export const PAGE_READ_MAX_SCROLLS = 40; + +function wait(ms: number, signal: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal.aborted) return resolve(); + const t = setTimeout(() => { + signal.removeEventListener("abort", done); + resolve(); + }, ms); + function done() { + clearTimeout(t); + resolve(); + } + signal.addEventListener("abort", done, { once: true }); + }); +} + +// The e2e server's recorded reads (E2E_ODYSEE_PAGE_FIXTURE): `{ "<page url>": +// PageApiRead, "*": PageApiRead }`. Read on every call (a spec writes it). +async function fixtureRead(file: string, pageUrl: string): Promise<PageApiRead> { + try { + const all = JSON.parse(await readFile(file, "utf8")) as Record<string, PageApiRead>; + const hit = all[pageUrl] ?? all["*"]; + if (hit) return { ok: hit.ok !== false, responses: hit.responses ?? [], mediaUrls: hit.mediaUrls ?? [] }; + return { ok: false, responses: [], mediaUrls: [], error: `no recorded read for ${pageUrl}` }; + } catch (err) { + return { ok: false, responses: [], mediaUrls: [], error: (err as Error).message }; + } +} + +// The real reader. Never throws: a page that could not be read is `ok: false` +// with the reason, and the caller decides. +export const readOdyseePage: PageApiReader = async ({ pageUrl, signal, onLog, play, scrolls }) => { + const responses: PageApiResponse[] = []; + const mediaUrls: string[] = []; + const fixture = process.env.E2E_ODYSEE_PAGE_FIXTURE; + if (fixture) { + onLog(`Reading ${pageUrl} from the recorded page answers (E2E_ODYSEE_PAGE_FIXTURE).\n`); + return fixtureRead(fixture, pageUrl); + } + if (process.env.NODE_TEST_CONTEXT) { + onLog(`Not opening ${pageUrl} in a browser under a test runner.\n`); + return { ok: false, responses, mediaUrls, error: "not opened under a test runner" }; + } + let browser: { close: () => Promise<void> } | null = null; + const pending: Promise<void>[] = []; + try { + const { chromium } = await importPlaywright(); + const b = await chromium.launch({ headless: true }); + browser = b; + const ctx = await b.newContext({}); + const page = await ctx.newPage(); + type Resp = { + url: () => string; + status: () => number; + headers: () => Record<string, string>; + json: () => Promise<unknown>; + request: () => { postData: () => string | null; url: () => string }; + }; + page.on("request", ((req: { url: () => string }) => { + try { + const u = new URL(req.url()); + if (u.hostname.endsWith(".odycdn.com") && u.pathname.includes("/streams/")) mediaUrls.push(req.url()); + } catch { + /* not a URL */ + } + }) as never); + page.on("response", ((r: Resp) => { + const url = r.url(); + if (!isOdyseeApiUrl(url)) return; + if (!/json/i.test(r.headers()["content-type"] ?? "")) return; + pending.push( + (async () => { + let body: unknown; + try { + body = await r.json(); + } catch { + return; + } + let request: unknown; + try { + const raw = r.request().postData(); + request = raw ? JSON.parse(raw) : undefined; + } catch { + request = undefined; + } + responses.push({ url, status: r.status(), ...(request !== undefined ? { request } : {}), body }); + })(), + ); + }) as never); + onLog(`Opening ${pageUrl} in a headless browser to read its own API answers.\n`); + await page.goto(pageUrl, { waitUntil: "domcontentloaded", timeout: PAGE_READ_GOTO_TIMEOUT_MS }).catch(() => {}); + await wait(PAGE_READ_SETTLE_MS, signal); + if (play && !signal.aborted) { + await page + .evaluate( + `(() => { const b = document.querySelector(".vjs-big-play-button, [aria-label*='Play']"); if (b) { b.click(); return; } const v = document.querySelector("video"); if (v) { v.muted = true; v.play().catch(() => {}); } })()`, + ) + .catch(() => {}); + await wait(PAGE_READ_PLAY_MS, signal); + } + const n = Math.min(Math.max(0, scrolls ?? 0), PAGE_READ_MAX_SCROLLS); + for (let i = 0; i < n && !signal.aborted; i++) { + await page.evaluate("window.scrollTo(0, document.body.scrollHeight)").catch(() => {}); + await wait(PAGE_READ_SCROLL_MS, signal); + } + await Promise.allSettled(pending); + onLog( + `Read ${pageUrl}: ${responses.length} API answer(s) ` + + `(${responses.filter((r) => r.status >= 200 && r.status < 300).length} ok), ` + + `${mediaUrls.length} media request(s).\n`, + ); + return { ok: responses.some((r) => r.status >= 200 && r.status < 300), responses, mediaUrls }; + } catch (err) { + const error = (err as Error).message; + onLog(`Could not read ${pageUrl} in a browser: ${error}\n`); + await Promise.allSettled(pending); + return { ok: false, responses, mediaUrls, error }; + } finally { + await browser?.close().catch(() => {}); + } +}; diff --git a/common/ytdlp/storedUrlPageOpen.ts b/common/ytdlp/storedUrlPageOpen.ts @@ -66,6 +66,11 @@ export const openPlayerPage: PageOpener = async ({ pageUrl, cdnHost, signal, onL onLog(`Not opening the player's page under a test runner (${pageUrl}).\n`); return { ok: false, mediaStatuses, error: "not opened under a test runner" }; } + // Nor on the e2e server (which sets E2E_ODYSEE_PAGE_FIXTURE on every slot). + if (process.env.E2E_ODYSEE_PAGE_FIXTURE) { + onLog(`Not opening the player's page on the e2e server (${pageUrl}).\n`); + return { ok: false, mediaStatuses, error: "not opened on the e2e server" }; + } let browser: { close: () => Promise<void> } | null = null; try { const { chromium } = await importPlaywright(); diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -52,6 +52,11 @@ export function blueskyOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-bluesky-origin"); } +/** The slot's recorded Odysee page reads (browser-lookup.spec writes it). */ +export function odyseePageFixtureFile(transcriptsDir: string): string { + return join(transcriptsDir, ".fake-odysee-pages.json"); +} + /** The start-mode build directory (scripts/e2e-stamp.mjs PACKAGES.editor.distDir). */ export const E2E_DIST_DIR = ".next/e2e"; const EXPORT_SITES_DIR = join(EDITOR_ROOT, "e2e", "fixtures", "sites"); @@ -200,6 +205,10 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // Where a spec names its fake Bluesky's origin (capture-posts.spec): the // slot's own test data, so two slots never share one. editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir); + // The browser lookup's recorded page reads (browser-lookup.spec): set on + // every slot, so the e2e server never opens a headless browser on the + // network — the player-page opener refuses under it too. + editorEnv.E2E_ODYSEE_PAGE_FIXTURE = odyseePageFixtureFile(paths.transcriptsDir); // A start-mode server runs the stamped build (shared, read-only); a second // `next dev` needs a dist dir of its own (Next locks `<distDir>/dev/lock`). if (mode === "start" && !env.CI) editorEnv.E2E_NEXT_DIST_DIR = E2E_DIST_DIR; diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -34,6 +34,12 @@ import { currentSlot } from "./e2e/testPaths"; // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN // then are (common/social/blueskyEndpoints.ts) +// E2E_ODYSEE_PAGE_FIXTURE set per slot (e2e/servers.ts): the file of +// recorded Odysee page reads the browser lookup +// answers from (browser-lookup.spec); while it is +// set no headless browser opens a page at all +// (common/ytdlp/odyseePageReader.ts, +// storedUrlPageOpen.ts) // E2E_MODE `start` (the default): the editor runs under // `next start` from a build the stamp vouches for // (scripts/e2e-stamp.mjs — rebuilt through the