// Helpers the site extractors share (release 37 S3). Pure: no network, no // disk, no clock. The HTML is read with the repo's small reader // (social/htmlReader.ts) and a body is turned into text by the forum parser's // renderer (social/xenforoParse.ts `forumBodyToText`), so every extractor // writes text, links and media the way forum posts already do. import { parseHtml, type HtmlElement, type HtmlNode } from "../../../social/htmlReader"; import { forumBodyToText } from "../../../social/xenforoParse"; import { parseWaybackUrl } from "../../wayback"; import type { PostMedia } from "../../posts"; export { parseHtml, type HtmlElement, type HtmlNode }; // --- the tree --------------------------------------------------------------------- export const isEl = (n: HtmlNode): n is HtmlElement => typeof n !== "string"; export const classList = (el: HtmlElement): string[] => (el.attrs.class ?? "").split(/\s+/).filter(Boolean); export const hasClass = (el: HtmlElement, c: string): boolean => classList(el).includes(c); export function findAll( el: HtmlElement, pred: (e: HtmlElement) => boolean, skip?: (e: HtmlElement) => boolean, out: HtmlElement[] = [], ): HtmlElement[] { for (const c of el.children) { if (!isEl(c)) continue; if (pred(c)) out.push(c); if (skip?.(c)) continue; findAll(c, pred, skip, out); } return out; } export function findFirst( el: HtmlElement, pred: (e: HtmlElement) => boolean, skip?: (e: HtmlElement) => boolean, ): HtmlElement | null { for (const c of el.children) { if (!isEl(c)) continue; if (pred(c)) return c; if (skip?.(c)) continue; const hit = findFirst(c, pred, skip); if (hit) return hit; } return null; } // Every element's parent, for walking up (the reader keeps no parent links). export function parentMap(root: HtmlElement): Map { const parents = new Map(); const walk = (el: HtmlElement) => { for (const c of el.children) { if (!isEl(c)) continue; parents.set(c, el); walk(c); } }; walk(root); return parents; } // Plain text of a node: scripts and styles dropped, nothing collapsed. export function rawText(node: HtmlNode): string { if (!isEl(node)) return node; if (node.tag === "script" || node.tag === "style" || node.tag === "template" || node.tag === "noscript") return ""; return node.children.map(rawText).join(""); } export const squash = (s: string): string => s.replace(/[\s ]+/g, " ").trim(); // Plain text, whitespace collapsed to single spaces. export const textOf = (node: HtmlNode | null | undefined): string => (node ? squash(rawText(node)) : ""); export function metaContent(root: HtmlElement, key: string): string | undefined { const m = findFirst( root, (e) => e.tag === "meta" && (e.attrs.property === key || e.attrs.name === key || e.attrs.itemprop === key), ); const v = m?.attrs.content?.trim(); return v || undefined; } export function pageTitle(root: HtmlElement): string | undefined { const t = textOf(findFirst(root, (e) => e.tag === "title")); return t || undefined; } // --- URLs -------------------------------------------------------------------------- // A URL a Wayback replay rewrote (`https://web.archive.org/web//`) // as the original; any other URL as it is. export function unwrapWaybackUrl(url: string): string { return parseWaybackUrl(url)?.originalUrl ?? url; } // A page body with Wayback's replay rewriting undone: the toolbar block // removed, and every attribute URL of the form `[https://web.archive.org]/web/ // [mod_]/` turned back into ``. A raw (`id_`) body has // neither and passes through unchanged. export function unwrapWaybackHtml(html: string): string { return html .replace(/[\s\S]*?/gi, "") .replace(/(=\s*["']?)(?:(?:https?:)?\/\/(?:web|wayback)\.archive\.org)?\/web\/\d{1,14}(?:[a-z]{2}_)?\//gi, "$1"); } // A link a site wrapped in its own redirector (Google's /url?q=, YouTube's // /redirect?q=, Tumblr's t.umblr.com/redirect?z=) as its target. export function unwrapRedirect(url: string): string { let u: URL; try { u = new URL(url); } catch { return url; } const host = u.hostname.toLowerCase(); const target = ((host === "www.google.com" || host === "google.com") && u.pathname === "/url" && (u.searchParams.get("q") || u.searchParams.get("url"))) || ((host === "www.youtube.com" || host === "youtube.com" || host === "m.youtube.com") && u.pathname === "/redirect" && u.searchParams.get("q")) || (host === "t.umblr.com" && u.pathname === "/redirect" && u.searchParams.get("z")) || null; return target && /^https?:\/\//i.test(target) ? target : url; } // An href from the page, absolute against `base`, unwrapped from Wayback and // from the site's redirector; undefined for an anchor, a script or data URL. export function absoluteUrl(raw: string | undefined, base: string): string | undefined { const v = raw?.trim(); if (!v || v.startsWith("#") || /^(javascript|data|mailto|tel):/i.test(v)) return undefined; let abs: string; try { abs = new URL(v.startsWith("//") ? `https:${v}` : v, base).href; } catch { return undefined; } return unwrapRedirect(unwrapWaybackUrl(abs)); } // A URL the page states in full (an expanded t.co link, a website field), // kept exactly as written, unwrapped from Wayback and from a redirector. export function statedUrl(raw: string | undefined, base: string): string | undefined { const v = raw?.trim(); if (v && /^https?:\/\/[^\s]+$/i.test(v)) return unwrapRedirect(unwrapWaybackUrl(v)); return absoluteUrl(v, base); } // Rewrite every href/src in a subtree to its absolute, unwrapped form (in // place), so the shared body renderer sees the URLs a reader would follow. export function absolutizeTree(el: HtmlElement, base: string): void { for (const k of ["href", "src", "data-src", "data-url"]) { if (el.attrs[k] !== undefined) { const abs = absoluteUrl(el.attrs[k], base); if (abs) el.attrs[k] = abs; } } for (const c of el.children) if (isEl(c)) absolutizeTree(c, base); } // --- a block of content → text ------------------------------------------------------ export type RenderedBlock = { text: string; links: string[]; media: PostMedia[] }; // An element's readable text (headings, paragraphs and list items as lines, // a link as "text (url)", an image as "[image]"), its outbound links and its // media. `drop` removes subtrees first (a post's date line, its tags); // `unlink` turns matching anchors into plain text (a post's link to itself). export function renderBlock( el: HtmlElement, base: string, drop?: (e: HtmlElement) => boolean, unlink?: (e: HtmlElement) => boolean, ): RenderedBlock { const prune = (node: HtmlElement): HtmlElement => ({ ...node, tag: node.tag === "a" && unlink?.(node) ? "span" : node.tag, attrs: { ...node.attrs }, children: node.children .filter((c) => !isEl(c) || !drop?.(c)) .map((c) => (isEl(c) ? prune(c) : c)), }); const copy = prune(el); absolutizeTree(copy, base); const out = forumBodyToText(copy); const links: string[] = []; for (const l of out.links) { const u = unwrapRedirect(unwrapWaybackUrl(l)); if (!links.includes(u)) links.push(u); } const media: PostMedia[] = []; for (const m of out.media) { const url = unwrapWaybackUrl(m.url); if (!media.some((x) => x.url === url && x.kind === m.kind)) media.push({ ...m, url }); } return { text: out.text, links, media }; } // --- dates --------------------------------------------------------------------------- export function isoFromEpochSeconds(v: string | number | undefined): string | undefined { const n = typeof v === "number" ? v : Number(v); if (!Number.isFinite(n) || n <= 0) return undefined; // Milliseconds when the number is too big to be seconds. const ms = n > 1e11 ? n : n * 1000; return new Date(ms).toISOString(); } // An ISO-8601 date or date-time as a full ISO string (UTC), else undefined. export function isoFromIso(v: string | undefined): string | undefined { const s = v?.trim(); if (!s || !/^\d{4}-\d{2}-\d{2}/.test(s)) return undefined; // A bare date, or a date-time with no zone, is read as UTC (never local). const withZone = /T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(s) ? `${s}Z` : /^\d{4}-\d{2}-\d{2}$/.test(s) ? `${s}T00:00:00Z` : s; const norm = withZone.replace(/([+-]\d{2})(\d{2})$/, "$1:$2"); const ms = Date.parse(norm); return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined; } const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; function monthIndex(name: string): number { return MONTHS.indexOf(name.slice(0, 3).toLowerCase()); } // An English date as a theme or a page prints it — "May 3rd, 2012", // "3 May 2012", "March 2, 2014 10:00am", "Sun, 02 Mar 2014 10:00:00 GMT", // "3:04 PM - 5 Jun 2015" — read as UTC (a page names no zone). ISO first. export function parseEnglishDate(s: string | undefined): string | undefined { if (!s) return undefined; const iso = isoFromIso(s); if (iso) return iso; const t = s.replace(/(\d)(st|nd|rd|th)\b/gi, "$1").replace(/[\s ]+/g, " "); const MON = "(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)"; let y: number | undefined; let mo: number | undefined; let d: number | undefined; const a = new RegExp(`\\b${MON}\\.? (\\d{1,2}),? (\\d{4})\\b`, "i").exec(t); const b = new RegExp(`\\b(\\d{1,2}) ${MON}\\.?,? (\\d{4})\\b`, "i").exec(t); if (a) { mo = monthIndex(a[1]); d = Number(a[2]); y = Number(a[3]); } else if (b) { d = Number(b[1]); mo = monthIndex(b[2]); y = Number(b[3]); } if (y === undefined || mo === undefined || mo < 0 || d === undefined || d < 1 || d > 31) return undefined; let hh = 0; let mm = 0; let ss = 0; const time = /\b(\d{1,2}):(\d{2})(?::(\d{2}))?\s*([ap]\.?m\.?)?/i.exec(t); if (time) { hh = Number(time[1]); mm = Number(time[2]); ss = Number(time[3] ?? 0); const ap = time[4]?.toLowerCase().replace(/\./g, ""); if (ap === "pm" && hh < 12) hh += 12; if (ap === "am" && hh === 12) hh = 0; if (hh > 23 || mm > 59 || ss > 59) hh = mm = ss = 0; } const ms = Date.UTC(y, mo, d, hh, mm, ss); return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined; } // --- small things ---------------------------------------------------------------------- export function pushUnique(arr: T[], v: T | undefined): void { if (v !== undefined && v !== "" && !arr.includes(v)) arr.push(v); }