// 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 { localMediaMetadataRefusal } from "../lib/localMedia"; 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; // Test seam: the page reader and the gap. deps?: BrowserLookupDeps; }; export async function runBrowserLookupJob(opts: BrowserLookupJobOpts): Promise { 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(", ")}.` }; // A local media library channel or a local recording (review fix 5). for (const id of [undefined, ...ids]) { const localRefusal = localMediaMetadataRefusal(slug, channelConfig, id); if (localRefusal) return { ok: false, error: localRefusal }; } 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; } }