// 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:`). // // 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~=''`) 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, ): 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; }; export type BrowserLookupResult = | { status: "written" | "patched" | "unchanged"; info: Record; 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 { 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 | 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; } 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 = {}; 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): 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~=''` (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, 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~='' 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 }; }