// YouTube channel About / channel page captures (release 37 S3): how a // channel described itself at each capture → one `yt-about` draft per // capture, `itemId: "yt-about--"` (channel = its UC id // when the page gives it, else the name the URL uses): title, description, // links, joined date, subscriber and view counts as the page prints them. // Two kinds of markup: the 2012–2016 server-rendered layout // (`.about-description`, `.about-stats`, `.about-channel-link`) and the // 2017+ app, whose data is the `ytInitialData` JSON in a script — read as // JSON (located, brace-matched, parsed), never by pattern over the HTML. import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; import { absoluteUrl, classList, findAll, findFirst, hasClass, metaContent, pageTitle, parseHtml, pushUnique, renderBlock, squash, textOf, unwrapRedirect, unwrapWaybackHtml, unwrapWaybackUrl, type HtmlElement, } from "./util"; const YT_HOSTS = new Set(["youtube.com", "www.youtube.com", "m.youtube.com"]); const TAIL = "(?:/(?:about|featured))?/?$"; const CHANNEL_PATHS = [ new RegExp(`^/user/([^/]+)${TAIL}`), new RegExp(`^/c/([^/]+)${TAIL}`), new RegExp(`^/channel/(UC[A-Za-z0-9_-]{10,})${TAIL}`), new RegExp(`^/(@[^/]+)${TAIL}`), // A legacy custom URL's About page (youtube.com//about). /^\/([A-Za-z0-9_.-]+)\/about\/?$/, ]; const NOT_CHANNELS = new Set(["watch", "results", "playlist", "feed", "embed", "shorts", "live", "redirect", "t", "yt", "account"]); // The channel name a YouTube URL is a channel page of, or null. export function youtubeChannelOf(url: URL): string | null { if (!YT_HOSTS.has(url.hostname.toLowerCase())) return null; for (const re of CHANNEL_PATHS) { const m = re.exec(url.pathname); if (m && !NOT_CHANNELS.has(m[1].toLowerCase())) { try { return decodeURIComponent(m[1]); } catch { return m[1]; } } } return null; } // --- ytInitialData ------------------------------------------------------------------------- // The JSON object assigned after `marker` (`var ytInitialData = {…};`, // `window["ytInitialData"] = {…};`), parsed; null when absent or broken. export function jsonAfter(html: string, marker: RegExp): unknown { const m = marker.exec(html); if (!m) return null; const after = m.index + m[0].length; // Some captures assign the data as a JS string (`'\x7b\x22…'`, or // `JSON.parse("…")`): the string literal, unescaped, is the JSON. const lit = /^\s*(?:JSON\.parse\(\s*)?(['"])/.exec(html.slice(after, after + 64)); if (lit) { const s = jsStringAt(html, after + lit[0].length, lit[1]); if (s === null) return null; try { return JSON.parse(s); } catch { return null; } } let i = html.indexOf("{", after); if (i < 0) return null; // A string-aware brace match: braces inside JSON strings do not count. let depth = 0; let inStr = false; const start = i; for (; i < html.length; i++) { const c = html[i]; if (inStr) { if (c === "\\") i++; else if (c === '"') inStr = false; continue; } if (c === '"') inStr = true; else if (c === "{") depth++; else if (c === "}" && --depth === 0) { try { return JSON.parse(html.slice(start, i + 1)); } catch { return null; } } } return null; } // A JS string literal's value, read from just after its opening quote. function jsStringAt(src: string, i: number, quote: string): string | null { let out = ""; for (; i < src.length; i++) { const c = src[i]; if (c === quote) return out; if (c !== "\\") { out += c; continue; } const n = src[++i]; if (n === "x") { out += String.fromCharCode(parseInt(src.slice(i + 1, i + 3), 16)); i += 2; } else if (n === "u") { out += String.fromCharCode(parseInt(src.slice(i + 1, i + 5), 16)); i += 4; } else if (n === "n") out += "\n"; else if (n === "t") out += "\t"; else if (n === "r") out += "\r"; else out += n; } return null; } type J = Record; const obj = (v: unknown): J | undefined => (v && typeof v === "object" && !Array.isArray(v) ? (v as J) : undefined); const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []); // The first value stored under `key` anywhere in the tree (breadth first). function deepFind(root: unknown, key: string): unknown { const queue: unknown[] = [root]; for (let n = 0; n < queue.length && n < 200_000; n++) { const v = queue[n]; if (Array.isArray(v)) queue.push(...v); else if (v && typeof v === "object") { const o = v as J; if (key in o) return o[key]; for (const k in o) queue.push(o[k]); } } return undefined; } // YouTube's text shapes: {simpleText}, {runs:[{text}]}, {content}, a string. function ytText(v: unknown): string | undefined { if (typeof v === "string") return v.trim() || undefined; const o = obj(v); if (!o) return undefined; if (typeof o.simpleText === "string") return o.simpleText.trim() || undefined; if (Array.isArray(o.runs)) return o.runs.map((r) => String(obj(r)?.text ?? "")).join("").trim() || undefined; if (typeof o.content === "string") return o.content.trim() || undefined; return undefined; } type About = { channelId?: string; handle?: string; title?: string; description?: string; links: { title?: string; url: string }[]; joined?: string; subscribers?: string; views?: string; country?: string; }; function linkUrl(raw: string | undefined, base: string): string | undefined { return raw ? absoluteUrl(raw, base) : undefined; } function addLink(about: About, url: string | undefined, title?: string) { if (!url || about.links.some((l) => l.url === url)) return; about.links.push(title ? { title, url } : { url }); } function fromInitialData(data: unknown, base: string): About | null { const about = obj(deepFind(data, "channelAboutFullMetadataRenderer")) ?? obj(deepFind(data, "aboutChannelViewModel")); const header = obj(deepFind(data, "c4TabbedHeaderRenderer")) ?? obj(deepFind(data, "pageHeaderViewModel")); const meta = obj(deepFind(data, "channelMetadataRenderer")); if (!about && !header && !meta) return null; const out: About = { links: [] }; out.channelId = (typeof about?.channelId === "string" ? about.channelId : undefined) ?? (typeof meta?.externalId === "string" ? meta.externalId : undefined) ?? (typeof header?.channelId === "string" ? header.channelId : undefined); out.title = ytText(about?.title) ?? ytText(meta?.title) ?? ytText(header?.title) ?? ytText(obj(obj(header?.title)?.dynamicTextViewModel)?.text); out.description = ytText(about?.description) ?? ytText(meta?.description); out.joined = ytText(about?.joinedDateText) ?? ytText(about?.joinedDate); out.views = ytText(about?.viewCountText); out.subscribers = ytText(header?.subscriberCountText) ?? ytText(about?.subscriberCountText); out.country = ytText(about?.country); const handle = ytText(header?.channelHandleText) ?? ytText(about?.displayCanonicalChannelUrl)?.replace(/^.*\//, ""); if (handle?.startsWith("@")) out.handle = handle; const vanity = typeof meta?.vanityChannelUrl === "string" ? meta.vanityChannelUrl : undefined; if (!out.handle && vanity) out.handle = /\/(@[^/]+|user\/[^/]+|c\/[^/]+)$/.exec(vanity)?.[1]?.replace(/^(user|c)\//, ""); // The 2017–2022 About tab: primaryLinks with a urlEndpoint. for (const l of arr(about?.primaryLinks)) { const o = obj(l); const url = linkUrl(obj(obj(o?.navigationEndpoint)?.urlEndpoint)?.url as string | undefined, base); addLink(out, url, ytText(o?.title)); } // The 2023+ About panel: channelExternalLinkViewModel. for (const l of arr(about?.links)) { const vm = obj(obj(l)?.channelExternalLinkViewModel); if (!vm) continue; const link = obj(vm.link); const cmd = obj(obj(obj(arr(link?.commandRuns)[0])?.onTap)?.innertubeCommand); const raw = (obj(cmd?.urlEndpoint)?.url as string | undefined) ?? ytText(link); const url = raw && !/^https?:/i.test(raw) && !raw.startsWith("/") ? `https://${raw}` : raw; addLink(out, linkUrl(url, base), ytText(vm.title)); } // The header's links (the bare channel page shows them). const headerLinks = obj(obj(header?.headerLinks)?.channelHeaderLinksRenderer); for (const l of [...arr(headerLinks?.primaryLinks), ...arr(headerLinks?.secondaryLinks)]) { const o = obj(l); const url = linkUrl(obj(obj(o?.navigationEndpoint)?.urlEndpoint)?.url as string | undefined, base); addLink(out, url, ytText(o?.title)); } return out; } // --- the 2012–2016 layout ------------------------------------------------------------------------ function fromOldLayout(root: HtmlElement, base: string): About | null { const descEl = findFirst(root, (e) => hasClass(e, "about-description")); const stats = findAll(root, (e) => hasClass(e, "about-stat")); const linkEls = findAll(root, (e) => e.tag === "a" && (hasClass(e, "about-channel-link") || classList(e).some((c) => c.startsWith("about-custom-link")))); const headerTitle = textOf(findFirst(root, (e) => hasClass(e, "qualified-channel-title-text"))); const channelId = metaContent(root, "channelId") ?? /\/channel\/(UC[A-Za-z0-9_-]{10,})/.exec(findFirst(root, (e) => e.tag === "link" && e.attrs.rel === "canonical")?.attrs.href ?? "")?.[1]; if (!descEl && stats.length === 0 && linkEls.length === 0 && !headerTitle && !channelId) return null; const out: About = { links: [] }; out.channelId = channelId; out.title = headerTitle || metaContent(root, "og:title") || metaContent(root, "title") || (pageTitle(root) ?? "").replace(/\s+-\s+YouTube$/, "") || undefined; if (descEl) out.description = renderBlock(descEl, base).text || undefined; else out.description = metaContent(root, "og:description") ?? metaContent(root, "description"); for (const s of stats) { const t = squash(textOf(s)).replace(/^(?:[•·\s]|•|·)+/, ""); if (/^joined\b/i.test(t)) out.joined = t; else if (/subscriber/i.test(t)) out.subscribers = t; else if (/\bviews?\b/i.test(t)) out.views = t; } if (!out.subscribers) { const n = textOf(findFirst(root, (e) => classList(e).some((c) => c.startsWith("yt-subscription-button-subscriber-count")))); if (n) out.subscribers = `${n} subscribers`; } const country = textOf(findFirst(root, (e) => hasClass(e, "country-inline"))); if (country) out.country = country; for (const a of linkEls) { const url = absoluteUrl(a.attrs.href, base); addLink(out, url, a.attrs.title || textOf(a) || undefined); } return out; } // --- the draft --------------------------------------------------------------------------------------- export function extractYtAbout(input: PageExtractInput): PageRecordDraft[] { const html = unwrapWaybackHtml(input.html); const base = input.capture.originalUrl; const url = new URL(base); const fromUrl = youtubeChannelOf(url) ?? undefined; const data = jsonAfter(html, /(?:var\s+ytInitialData|window\[\s*["']ytInitialData["']\s*\]|ytInitialData)\s*=(?!=)\s*/) ?? null; const root = parseHtml(html); const about = (data ? fromInitialData(data, base) : null) ?? fromOldLayout(root, base); const channel = about?.channelId ?? fromUrl ?? url.pathname.replace(/\W+/g, "-"); const handle = about?.handle ?? (fromUrl && !fromUrl.startsWith("UC") ? fromUrl : undefined); const itemId = `yt-about-${channel}-${input.capture.captureTs}`; if (!about) { return [{ kind: "yt-about", itemId, ...(handle ? { author: handle } : {}), text: "This capture holds no channel description.", links: [], noContent: true, }]; } const lines: string[] = []; if (about.title) lines.push(about.title); if (about.description) lines.push(about.description); for (const l of about.links) lines.push(l.title ? `${l.title}: ${l.url}` : l.url); if (about.joined) lines.push(/^joined\b/i.test(about.joined) ? about.joined : `Joined ${about.joined}`); if (about.subscribers) lines.push(about.subscribers); if (about.views) lines.push(about.views); if (about.country) lines.push(`Country: ${about.country}`); const links: string[] = []; for (const l of about.links) pushUnique(links, unwrapRedirect(unwrapWaybackUrl(l.url))); const draft: PageRecordDraft = { kind: "yt-about", itemId, author: handle ?? about.channelId ?? channel, text: lines.join("\n"), links, }; if (about.title) { draft.title = about.title; draft.authorName = about.title; } if (!about.description && about.links.length === 0 && !about.joined && !about.subscribers && !about.views) draft.noContent = true; return [draft]; } export const ytAboutExtractor: PageExtractor = { name: "yt-about", version: 1, matches(originalUrl) { return youtubeChannelOf(originalUrl) !== null; }, extract: extractYtAbout, };