// Tumblr captures (release 37 S3): a blog's post page, index, archive, tagged // or page-N page → one `tumblr-post` draft per post on it, `itemId: // "tumblr-"`, so a post seen on an index and on its permalink is ONE // record. Themes are the blog's own HTML, so nothing here leans on a class // name alone: a post is found by its PERMALINK (`/post/` on the blog's // own host), and its container is the largest element around that permalink // holding no other post's permalink. Structural cues (`article.post`, // `id="post-"`, `data-post-id`) are taken first when the theme has them. // A page holding no post (an about or ask page) → one whole-page // `tumblr-index` draft with the page's text. import type { PostRef } from "../../posts"; import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; import { absoluteUrl, classList, findAll, findFirst, hasClass, isEl, isoFromIso, metaContent, pageTitle, parentMap, parseEnglishDate, parseHtml, pushUnique, renderBlock, textOf, unwrapWaybackHtml, type HtmlElement, } from "./util"; // A reblog points at another page record, so its ref is on that platform. const WEBPAGE = "webpage" as const; const NOT_BLOGS = /^(www|assets|static|api|secure|media|data|vt|va|vtt|\d+\.media|[a-z0-9]+\.media)\.tumblr\.com$/; export function isTumblrBlogHost(host: string): boolean { const h = host.toLowerCase(); return h.endsWith(".tumblr.com") && !NOT_BLOGS.test(h); } // The blog name of a *.tumblr.com host ("staff.tumblr.com" → "staff"). export function tumblrBlogName(host: string): string | undefined { const m = /^([a-z0-9-]+)\.tumblr\.com$/i.exec(host); return m ? m[1].toLowerCase() : undefined; } // A Tumblr theme on a custom domain: what Tumblr itself puts on every blog // page (its controls iframe, its asset hosts, its app links, its feed type). const THEME_MARKERS = [ /id=["']?tumblr_controls/i, /\b(?:assets|static|secure\.static)\.tumblr\.com\//i, /]+name=["']?tumblr-theme/i, /com\.tumblr\b/i, /tumblr-feed:/i, /\btumblelog(?:Name)?\b/i, ]; const POST_PATH_RE = /^\/post\/(\d+)(?:\/([^/?#]*))?/; // The post id a URL is the permalink of, on `host`; undefined for anything // else (another blog's post is a reblog source, not this page's post). function postIdOn(url: string | undefined, host: string): string | undefined { if (!url) return undefined; let u: URL; try { u = new URL(url); } catch { return undefined; } if (u.hostname.toLowerCase() !== host) return undefined; return POST_PATH_RE.exec(u.pathname)?.[1]; } function foreignPost(url: string | undefined, host: string): { id: string; url: string; blog: string } | null { if (!url) return null; let u: URL; try { u = new URL(url); } catch { return null; } const h = u.hostname.toLowerCase(); if (h === host) return null; const m = POST_PATH_RE.exec(u.pathname); if (!m) return null; return { id: m[1], url: `${u.origin}${u.pathname}`, blog: tumblrBlogName(h) ?? h }; } // The blog's name on a custom domain: Tumblr's controls iframe or app link // names it; else the host. function blogNameOf(root: HtmlElement, html: string, host: string): string { const own = tumblrBlogName(host); if (own) return own; const iframe = findFirst(root, (e) => e.tag === "iframe" && (e.attrs.id === "tumblr_controls" || /tumblr\.com\/(dashboard\/)?iframe/.test(e.attrs.src ?? ""))); const fromIframe = /[?&](?:name|tumblelogName)=([a-z0-9-]+)/i.exec(iframe?.attrs.src ?? "")?.[1]; if (fromIframe) return fromIframe.toLowerCase(); const fromApp = /blogName=([a-z0-9-]+)/i.exec(html)?.[1]; if (fromApp) return fromApp.toLowerCase(); return host.replace(/^www\./, ""); } const DATE_CLASS = /(^|[-_])(date|time|timestamp|posted|published|dateline)($|[-_])/i; const META_CLASS = /(^|[-_])(tags?|notes?|meta|permalink|post-?meta|post-?info|post-?footer|footer|reblog(?:ged)?|via|share|controls|date|time|timestamp|posted|dateline)($|[-_])/i; const isMetaEl = (e: HtmlElement): boolean => e.tag === "footer" || e.tag === "time" || e.tag === "script" || e.tag === "style" || classList(e).some((c) => META_CLASS.test(c)); // A structural post container the theme names. const isStructuralPost = (e: HtmlElement): boolean => /^post[-_]?\d+$/.test(e.attrs.id ?? "") || /^\d+$/.test(e.attrs["data-post-id"] ?? "") || (e.tag === "article" && (hasClass(e, "post") || hasClass(e, "entry"))); type Found = { id: string; container: HtmlElement; permalink: string }; function findPosts(root: HtmlElement, host: string, base: string, onlyId?: string): Found[] { const parents = parentMap(root); const anchors = findAll(root, (e) => e.tag === "a" && !!e.attrs.href); const permalinkOf = new Map(); for (const a of anchors) { const url = absoluteUrl(a.attrs.href, base); const id = postIdOn(url, host); if (id && url) permalinkOf.set(a, { id, url: url.replace(/[?#].*$/, "") }); } // The post ids under each element, counted once from the leaves up. const idsUnder = new Map>(); const collect = (el: HtmlElement): Set => { const s = new Set(); const own = permalinkOf.get(el); if (own) s.add(own.id); const structural = /^post[-_]?(\d+)$/.exec(el.attrs.id ?? "")?.[1] ?? (/^\d+$/.test(el.attrs["data-post-id"] ?? "") ? el.attrs["data-post-id"] : undefined); if (structural) s.add(structural); for (const c of el.children) if (isEl(c)) for (const id of collect(c)) s.add(id); idsUnder.set(el, s); return s; }; collect(root); const found: Found[] = []; const seen = new Set(); const add = (id: string, container: HtmlElement, permalink: string) => { if (seen.has(id) || (onlyId && id !== onlyId)) return; seen.add(id); found.push({ id, container, permalink }); }; // 1. The theme's own post containers. for (const el of findAll(root, isStructuralPost, isStructuralPost)) { const ids = idsUnder.get(el) ?? new Set(); const named = /^post[-_]?(\d+)$/.exec(el.attrs.id ?? "")?.[1] ?? el.attrs["data-post-id"]; const id = named && /^\d+$/.test(named) ? named : ids.size === 1 ? [...ids][0] : undefined; if (!id) continue; const link = [...permalinkOf].find(([a, p]) => p.id === id && isInside(a, el, parents))?.[1].url; add(id, el, link ?? `${new URL(base).origin}/post/${id}`); } // 2. Any other permalink: walk up while the parent holds no other post. for (const [a, p] of permalinkOf) { if (seen.has(p.id)) continue; let el: HtmlElement = a; for (;;) { const up = parents.get(el); if (!up || up.tag === "#root" || up.tag === "body" || up.tag === "html") break; const ids = idsUnder.get(up); if (!ids || ids.size > 1) break; el = up; } // A bare link (prev/next, "related posts") is not a post. if (el === a && !onlyId) continue; add(p.id, el, p.url); } return found; } function isInside(el: HtmlElement, container: HtmlElement, parents: Map): boolean { for (let cur: HtmlElement | undefined = el; cur; cur = parents.get(cur)) if (cur === container) return true; return false; } function postDate(container: HtmlElement, permalinkEls: HtmlElement[]): string | undefined { const time = findFirst(container, (e) => e.tag === "time" && !!e.attrs.datetime); const fromTime = isoFromIso(time?.attrs.datetime); if (fromTime) return fromTime; for (const a of permalinkEls) { const d = parseEnglishDate(a.attrs.title) ?? parseEnglishDate(textOf(a)); if (d) return d; } for (const el of findAll(container, (e) => classList(e).some((c) => DATE_CLASS.test(c)))) { const d = parseEnglishDate(el.attrs.title) ?? parseEnglishDate(textOf(el)); if (d) return d; } return undefined; } function postTags(container: HtmlElement, base: string): string[] { const tags: string[] = []; for (const a of findAll(container, (e) => e.tag === "a" && !!e.attrs.href)) { const url = absoluteUrl(a.attrs.href, base); const m = url ? /\/tagged\/([^/?#]+)/.exec(new URL(url).pathname) : null; if (!m) continue; const fromText = textOf(a).replace(/^#\s*/, ""); let fromUrl = m[1]; try { fromUrl = decodeURIComponent(m[1].replace(/\+/g, " ")); } catch { /* keep it */ } pushUnique(tags, fromText || fromUrl.replace(/-/g, " ")); } return tags; } // The post this one reblogs: a link to another blog's post that the theme // marks as the reblog source ("reblogged from", "via", "source"). function reblogOf(container: HtmlElement, host: string, base: string, parents: Map): PostRef | undefined { const MARK = /reblog|via|source/i; for (const a of findAll(container, (e) => e.tag === "a" && !!e.attrs.href)) { const target = foreignPost(absoluteUrl(a.attrs.href, base), host); if (!target) continue; const parent = parents.get(a); const marked = classList(a).some((c) => MARK.test(c)) || (parent ? classList(parent).some((c) => MARK.test(c)) : false) || (() => { if (!parent) return false; const i = parent.children.indexOf(a); const before = parent.children.slice(Math.max(0, i - 2), i).map((n) => (typeof n === "string" ? n : textOf(n))).join(" "); return /(reblogged from|via|source:?|reblogged)\s*$/i.test(before.trim()); })(); if (!marked) continue; return { platform: WEBPAGE, id: `tumblr-${target.id}`, url: target.url, author: target.blog }; } return undefined; } function postTitle(container: HtmlElement, isOwnPermalink: (a: HtmlElement) => boolean): string | undefined { const t = findFirst(container, (e) => /^h[1-4]$/.test(e.tag) && (hasClass(e, "title") || hasClass(e, "post-title") || hasClass(e, "entry-title"))) ?? findFirst(container, (e) => (e.tag === "div" || e.tag === "span") && (hasClass(e, "title") || hasClass(e, "post-title"))) // A classic theme's title: a heading that links to the post itself. ?? findFirst(container, (e) => /^h[1-4]$/.test(e.tag) && !!findFirst(e, (a) => a.tag === "a" && isOwnPermalink(a))); const s = textOf(t); return s || undefined; } export function extractTumblr(input: PageExtractInput): PageRecordDraft[] { const html = unwrapWaybackHtml(input.html); const base = input.capture.originalUrl; const pageUrl = new URL(base); const host = pageUrl.hostname.toLowerCase(); const root = parseHtml(html); const parents = parentMap(root); const blog = blogNameOf(root, html, host); const permalinkPage = POST_PATH_RE.exec(pageUrl.pathname)?.[1]; const body = findFirst(root, (e) => e.tag === "body") ?? root; let posts = findPosts(body, host, base, permalinkPage); // A permalink page whose theme does not link the post to itself: the // page's main content is the post. if (posts.length === 0 && permalinkPage) { const main = findFirst(body, isStructuralPost) ?? findFirst(body, (e) => e.tag === "main" || e.attrs.id === "content" || e.attrs.id === "posts" || hasClass(e, "posts")) ?? body; posts = [{ id: permalinkPage, container: main, permalink: `${pageUrl.origin}${pageUrl.pathname}` }]; } const drafts: PageRecordDraft[] = []; for (const p of posts) { const permalinkEls = findAll(p.container, (e) => e.tag === "a" && postIdOn(absoluteUrl(e.attrs.href, base), host) === p.id); let publishedAt = postDate(p.container, permalinkEls); if (!publishedAt && permalinkPage) { publishedAt = isoFromIso(metaContent(root, "article:published_time")) ?? parseEnglishDate(metaContent(root, "date")); } const tags = postTags(p.container, base); const repostOf = reblogOf(p.container, host, base, parents); const isOwnPermalink = (a: HtmlElement) => postIdOn(absoluteUrl(a.attrs.href, base), host) === p.id; const title = postTitle(p.container, isOwnPermalink); const rendered = renderBlock(p.container, base, (e) => isMetaEl(e), isOwnPermalink); // The permalink's own anchor text ("Permalink", a date) is not the body. const links = rendered.links.filter((l) => postIdOn(l, host) === undefined && !/\/tagged\//.test(l)); const draft: PageRecordDraft = { kind: "tumblr-post", itemId: `tumblr-${p.id}`, url: p.permalink, author: blog, text: rendered.text, links, }; if (title) draft.title = title; if (publishedAt) draft.publishedAt = publishedAt; if (rendered.media.length > 0) draft.media = rendered.media; if (tags.length > 0) draft.tags = tags; if (repostOf) { draft.repostOf = repostOf; draft.isRepost = true; } drafts.push(draft); } if (drafts.length > 0) return drafts; // No post on the page: the page itself, so the capture is accounted for. const main = findFirst(body, (e) => e.tag === "main" || e.attrs.id === "content" || hasClass(e, "content")) ?? body; const rendered = renderBlock(main, base, (e) => e.tag === "nav" || e.tag === "script" || e.tag === "style" || e.tag === "iframe"); const title = pageTitle(root); const draft: PageRecordDraft = { kind: "tumblr-index", author: blog, text: rendered.text || "This capture holds no Tumblr posts.", links: rendered.links, }; if (title) draft.title = title; if (!rendered.text) draft.noContent = true; if (rendered.media.length > 0) draft.media = rendered.media; return [draft]; } export const tumblrExtractor: PageExtractor = { name: "tumblr", version: 1, matches(originalUrl, html) { if (isTumblrBlogHost(originalUrl.hostname)) return true; // A custom domain: a Tumblr theme, with post permalinks or on one. if (!THEME_MARKERS.some((re) => re.test(html))) return false; return POST_PATH_RE.test(originalUrl.pathname) || /href=["']?[^"'\s>]*\/post\/\d+/i.test(html); }, extract: extractTumblr, };