// 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: {: 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=` 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; signing_channel?: { claim_id?: string; name?: string; value?: Record }; }; const obj = (v: unknown): Record | null => v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : 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 { const out = new Map(); 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 (`…/:`) 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, 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//` (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> = { "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 | 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 { 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 = { 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/:`). 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; }