// X / Twitter captures (release 37 S3). The server-rendered layouts the // Wayback Machine holds for 2012–2022 — the desktop timeline (`div.tweet` // with `data-tweet-id`, `data-screen-name`, `._timestamp[data-time]`, // `p.tweet-text`) and the legacy mobile site (`table.tweet`) — → one `tweet` // draft per tweet, `itemId: "tweet-"`, carrying the fields an // X-channel record of the same status carries (author = handle, authorName, // text with links expanded, reply / quote / retweet refs on platform // "twitter" with the status id), so the two line up. A profile's header (bio, // location, website, joined, counts) → one `x-profile` draft per capture. A // capture of the JavaScript app that holds only its shell → one whole-page // draft with `noContent: true` (no itemId: a shell must never stand in for a // tweet a better capture holds). import type { PostMedia, PostRef } from "../../posts"; import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; import { absoluteUrl, classList, findAll, findFirst, hasClass, isEl, isoFromEpochSeconds, parentMap, parseEnglishDate, parseHtml, pushUnique, squash, statedUrl, textOf, unwrapWaybackHtml, type HtmlElement, type HtmlNode, } from "./util"; const X_HOSTS = new Set([ "twitter.com", "www.twitter.com", "mobile.twitter.com", "m.twitter.com", "x.com", "www.x.com", "mobile.x.com", ]); export function isXHost(host: string): boolean { return X_HOSTS.has(host.toLowerCase()); } // First path segments that are X's own pages, never a handle. const RESERVED = new Set([ "i", "search", "hashtag", "intent", "home", "explore", "settings", "share", "login", "logout", "signup", "about", "tos", "privacy", "notifications", "messages", "account", "download", "who_to_follow", "lists", "compose", "jobs", "help", "session", "oauth", "web", ]); export type XUrl = { handle?: string; statusId?: string }; // The handle and status id an X URL names (a profile, its tabs, a status). export function parseXUrl(url: URL): XUrl { const segs = url.pathname.split("/").filter(Boolean); if (segs[0] === "i" && segs[1] === "web" && segs[2] === "status" && /^\d+$/.test(segs[3] ?? "")) { return { statusId: segs[3] }; } if (segs[0] === "i" && segs[1] === "status" && /^\d+$/.test(segs[2] ?? "")) return { statusId: segs[2] }; const handle = segs[0]; if (!handle || RESERVED.has(handle.toLowerCase()) || !/^[A-Za-z0-9_]{1,20}$/.test(handle)) return {}; if ((segs[1] === "status" || segs[1] === "statuses") && /^\d+$/.test(segs[2] ?? "")) { return { handle, statusId: segs[2] }; } return { handle }; } export function statusUrl(handle: string | undefined, id: string): string { return handle ? `https://twitter.com/${handle}/status/${id}` : `https://twitter.com/i/status/${id}`; } function ref(id: string, handle?: string): PostRef { return { platform: "twitter", id, url: statusUrl(handle, id), ...(handle ? { author: handle } : {}) }; } // A status id's own time: ids since November 2010 are snowflakes, whose top // bits are milliseconds since Twitter's epoch. const TWITTER_EPOCH = 1288834974657n; export function snowflakeIso(id: string): string | undefined { if (!/^\d{15,20}$/.test(id)) return undefined; const ms = Number((BigInt(id) >> 22n) + TWITTER_EPOCH); // Below this the id is a pre-snowflake sequence number, not a time. if (ms < Date.UTC(2010, 10, 4)) return undefined; return new Date(ms).toISOString(); } // --- a tweet's text ----------------------------------------------------------------- const isStatusMediaLink = (url: string) => /\/status(?:es)?\/\d+\/(photo|video)\/\d+/.test(url); // The tweet's text as X's own record has it: an emoji image as its // character, a t.co link as the URL it expands to, a mention or hashtag as // its text, the pic.twitter.com tail dropped. function tweetText(el: HtmlElement, base: string): { text: string; links: string[] } { const links: string[] = []; const out: string[] = []; const walk = (node: HtmlNode) => { if (!isEl(node)) { out.push(node.replace(/[ \t\r ]+/g, " ")); return; } const e = node; if (e.tag === "script" || e.tag === "style") return; if (e.tag === "br") { out.push("\n"); return; } if (e.tag === "img") { out.push(e.attrs.alt ?? ""); return; } if (e.tag === "a") { if (hasClass(e, "u-hidden") || e.attrs["data-pre-embedded"] === "true") return; const expanded = e.attrs["data-expanded-url"] || e.attrs["data-url"] || e.attrs.title; const mention = hasClass(e, "twitter-atreply") || hasClass(e, "twitter-hashtag") || hasClass(e, "twitter-cashtag") || /^[@#$]/.test(textOf(e)); if (!mention && expanded && /^https?:\/\//i.test(expanded)) { const url = statedUrl(expanded, base) ?? expanded; if (isStatusMediaLink(url)) return; pushUnique(links, url); out.push(url); return; } if (!mention) { const href = absoluteUrl(e.attrs.href, base); if (href && !/^https?:\/\/t\.co\//.test(href) && !isXHost(new URL(href).hostname)) pushUnique(links, href); } for (const c of e.children) walk(c); return; } if (hasClass(e, "tco-ellipsis") || hasClass(e, "invisible")) { for (const c of e.children) walk(c); return; } for (const c of e.children) walk(c); }; for (const c of el.children) walk(c); const text = out .join("") .split("\n") .map((l) => l.replace(/ {2,}/g, " ").trim()) .join("\n") .replace(/\n{3,}/g, "\n\n") .trim(); return { text, links }; } // --- the desktop layout ----------------------------------------------------------------- const isDesktopTweet = (e: HtmlElement) => !!e.attrs["data-tweet-id"] && hasClass(e, "tweet"); const isQuoteBox = (e: HtmlElement) => classList(e).some((c) => c.startsWith("QuoteTweet")); type Section = "ancestor" | "main" | "reply" | "timeline"; type RawTweet = { el: HtmlElement; id: string; handle?: string; name?: string; publishedAt?: string; text: string; links: string[]; media: PostMedia[]; conversationId?: string; replyingTo: string[]; isReplyMarked: boolean; quoted?: PostRef; retweet?: { id: string; by: string }; section: Section; group?: HtmlElement; }; function tweetMedia(el: HtmlElement, base: string): PostMedia[] { const media: PostMedia[] = []; const add = (url: string | undefined, kind: PostMedia["kind"] = "image") => { const u = url ? absoluteUrl(url, base) : undefined; if (u && !media.some((m) => m.url === u)) media.push({ kind, url: u }); }; for (const e of findAll(el, (x) => !!x.attrs["data-image-url"], isQuoteBox)) add(e.attrs["data-image-url"]); for (const c of findAll(el, (x) => hasClass(x, "AdaptiveMedia-photoContainer") || hasClass(x, "media-thumbnail"), isQuoteBox)) { add(c.attrs["data-resolved-url-large"] ?? c.attrs["data-url"]); const img = findFirst(c, (x) => x.tag === "img"); if (!c.attrs["data-image-url"] && img) add(img.attrs.src); } return media; } function desktopTweet(el: HtmlElement, base: string, section: Section, group?: HtmlElement): RawTweet { const id = el.attrs["data-tweet-id"]; const handle = el.attrs["data-screen-name"] || textOf(findFirst(el, (e) => hasClass(e, "username"), isQuoteBox)).replace(/^@/, "") || undefined; const name = el.attrs["data-name"] || textOf(findFirst(el, (e) => hasClass(e, "fullname"), isQuoteBox)) || undefined; const stamp = findFirst(el, (e) => hasClass(e, "_timestamp") && !!(e.attrs["data-time"] || e.attrs["data-time-ms"]), isQuoteBox); const stampLink = findFirst(el, (e) => e.tag === "a" && hasClass(e, "tweet-timestamp"), isQuoteBox); const metadata = findFirst(el, (e) => hasClass(e, "metadata"), isQuoteBox); const publishedAt = isoFromEpochSeconds(stamp?.attrs["data-time-ms"] ?? stamp?.attrs["data-time"]) ?? parseEnglishDate(stampLink?.attrs.title) ?? parseEnglishDate(textOf(metadata)) ?? snowflakeIso(id); const textEl = findFirst(el, (e) => hasClass(e, "tweet-text") || hasClass(e, "js-tweet-text"), isQuoteBox); const { text, links } = textEl ? tweetText(textEl, base) : { text: "", links: [] }; const replyingTo: string[] = []; const replyCtx = findFirst(el, (e) => hasClass(e, "ReplyingToContextBelowAuthor") || hasClass(e, "tweet-reply-context"), isQuoteBox); if (replyCtx) { for (const a of findAll(replyCtx, (e) => e.tag === "a")) pushUnique(replyingTo, textOf(a).replace(/^@/, "") || undefined); } let quoted: PostRef | undefined; const quoteInner = findFirst(el, (e) => isQuoteBox(e) && !!(e.attrs["data-item-id"] || e.attrs.href)); if (quoteInner) { const qHref = quoteInner.attrs.href ? absoluteUrl(quoteInner.attrs.href, base) : undefined; const fromHref = qHref ? parseXUrl(new URL(qHref)) : {}; const qId = quoteInner.attrs["data-item-id"] || fromHref.statusId; const qHandle = quoteInner.attrs["data-screen-name"] || fromHref.handle; if (qId && /^\d+$/.test(qId)) quoted = ref(qId, qHandle); } if (quoted) { const qid = quoted.id; for (let i = links.length - 1; i >= 0; i--) if (new RegExp(`/status(?:es)?/${qid}(?:$|[/?#])`).test(links[i])) links.splice(i, 1); } const retweetId = el.attrs["data-retweet-id"]; const retweeter = el.attrs["data-retweeter"]; return { el, id, handle, name, publishedAt, text, links, media: tweetMedia(el, base), conversationId: el.attrs["data-conversation-id"] || undefined, replyingTo, isReplyMarked: el.attrs["data-is-reply-to"] === "true" || el.attrs["data-has-parent-tweet"] === "true", quoted, retweet: retweetId && /^\d+$/.test(retweetId) && retweeter ? { id: retweetId, by: retweeter } : undefined, section, group, }; } // --- the legacy mobile layout --------------------------------------------------------------- const isMobileTweet = (e: HtmlElement) => e.tag === "table" && hasClass(e, "tweet"); function mobileTweet(el: HtmlElement, base: string): RawTweet | null { const href = el.attrs.href ? absoluteUrl(el.attrs.href, base) : undefined; const fromHref = href ? parseXUrl(new URL(href)) : {}; const textEl = findFirst(el, (e) => hasClass(e, "tweet-text")); const id = textEl?.attrs["data-id"] || fromHref.statusId || /^tweet_(\d+)$/.exec(findFirst(el, (e) => e.tag === "a" && /^tweet_\d+$/.test(e.attrs.name ?? ""))?.attrs.name ?? "")?.[1]; if (!id) return null; const handle = fromHref.handle || textOf(findFirst(el, (e) => hasClass(e, "username"))).replace(/^@/, "") || undefined; const name = textOf(findFirst(el, (e) => hasClass(e, "fullname"))) || undefined; const { text, links } = textEl ? tweetText(textEl, base) : { text: "", links: [] }; const replyingTo: string[] = []; const replyCtx = findFirst(el, (e) => hasClass(e, "tweet-reply-context")); if (replyCtx) for (const a of findAll(replyCtx, (e) => e.tag === "a")) pushUnique(replyingTo, textOf(a).replace(/^@/, "") || undefined); const media: PostMedia[] = []; for (const img of findAll(el, (e) => e.tag === "img" && /pbs\.twimg\.com\/media\//.test(e.attrs.src ?? ""))) { const u = absoluteUrl(img.attrs.src, base); if (u && !media.some((m) => m.url === u)) media.push({ kind: "image", url: u.replace(/:small$|:thumb$/, "") }); } return { el, id, handle, name, // The mobile site prints a relative time ("3h", "Jun 5"); the id's own // time is exact. publishedAt: snowflakeIso(id), text, links, media, replyingTo, isReplyMarked: replyingTo.length > 0, section: "timeline", }; } // --- the profile header ------------------------------------------------------------------------ type Profile = { handle: string; name?: string; bio?: string; location?: string; website?: string; joined?: string; counts: [string, string][]; links: string[]; }; function countOf(root: HtmlElement, navClass: string): string | undefined { const item = findFirst(root, (e) => hasClass(e, navClass)); if (!item) return undefined; const v = findFirst(item, (e) => hasClass(e, "ProfileNav-value")); const n = v?.attrs["data-count"]; if (n && /^\d+$/.test(n)) return n.replace(/\B(?=(\d{3})+$)/g, ","); return textOf(v) || undefined; } function profileOf(root: HtmlElement, base: string, urlHandle: string | undefined): Profile | null { const card = findFirst(root, (e) => hasClass(e, "ProfileHeaderCard")) ?? findFirst(root, (e) => hasClass(e, "profile-card-inner") || hasClass(e, "profile-header-inner")) ?? findFirst(root, (e) => e.tag === "table" && hasClass(e, "profile-details")); if (!card) return null; const pick = (...classes: string[]) => { for (const c of classes) { const t = textOf(findFirst(card, (e) => hasClass(e, c))); if (t) return t; } return undefined; }; const handle = (pick("ProfileHeaderCard-screenname", "screen-name", "username") ?? "").replace(/^@/, "").trim() || urlHandle; if (!handle) return null; const links: string[] = []; const bioEl = findFirst(card, (e) => hasClass(e, "ProfileHeaderCard-bio") || hasClass(e, "bio")); const bio = bioEl ? tweetText(bioEl, base) : undefined; for (const l of bio?.links ?? []) pushUnique(links, l); const urlEl = findFirst(card, (e) => hasClass(e, "ProfileHeaderCard-urlText") || hasClass(e, "url")); const urlA = urlEl ? (urlEl.tag === "a" ? urlEl : findFirst(urlEl, (e) => e.tag === "a")) : null; const website = urlA ? statedUrl(urlA.attrs["data-expanded-url"] || urlA.attrs["data-url"] || urlA.attrs.title || urlA.attrs.href, base) : undefined; if (website) pushUnique(links, website); const joinEl = findFirst(card, (e) => hasClass(e, "ProfileHeaderCard-joinDateText")); const joinedExact = parseEnglishDate(joinEl?.attrs.title); const joined = joinedExact ? `Joined ${joinedExact.slice(0, 10)}` : textOf(joinEl) || undefined; const counts: [string, string][] = []; const nav: [string, string][] = [ ["ProfileNav-item--tweets", "Tweets"], ["ProfileNav-item--following", "Following"], ["ProfileNav-item--followers", "Followers"], ["ProfileNav-item--favorites", "Likes"], ]; for (const [cls, label] of nav) { const v = countOf(root, cls); if (v) counts.push([label, v]); } if (counts.length === 0) { // 2012–2013: ul.stats with data-element-term; mobile: .statnum / .statlabel. for (const a of findAll(root, (e) => !!e.attrs["data-element-term"] && /_stats$/.test(e.attrs["data-element-term"]))) { const label = { tweet_stats: "Tweets", following_stats: "Following", follower_stats: "Followers" }[a.attrs["data-element-term"]]; const v = textOf(findFirst(a, (e) => e.tag === "strong")); if (label && v) counts.push([label, v]); } for (const td of findAll(root, (e) => !!findFirst(e, (x) => hasClass(x, "statnum")) && e.tag === "td")) { const v = textOf(findFirst(td, (x) => hasClass(x, "statnum"))); const label = textOf(findFirst(td, (x) => hasClass(x, "statlabel"))); if (v && label) counts.push([label.replace(/^\w/, (c) => c.toUpperCase()), v]); } } return { handle, name: pick("ProfileHeaderCard-nameLink", "ProfileHeaderCard-name", "fullname"), bio: bio?.text || undefined, location: pick("ProfileHeaderCard-locationText", "location"), website, joined, counts, links, }; } function profileDraft(p: Profile, captureTs: string): PageRecordDraft { const lines = [p.name ? `${p.name} (@${p.handle})` : `@${p.handle}`]; if (p.bio) lines.push(p.bio); if (p.location) lines.push(`Location: ${p.location}`); if (p.website) lines.push(`Website: ${p.website}`); if (p.joined) lines.push(p.joined); if (p.counts.length > 0) lines.push(p.counts.map(([k, v]) => `${k}: ${v}`).join(" · ")); return { kind: "x-profile", itemId: `x-profile-${p.handle.toLowerCase()}-${captureTs}`, url: `https://twitter.com/${p.handle}`, title: p.name ? `${p.name} (@${p.handle})` : `@${p.handle}`, author: p.handle, ...(p.name ? { authorName: p.name } : {}), text: lines.join("\n"), links: p.links, }; } // --- the page ------------------------------------------------------------------------------------ const SHELL_MARKERS = [/id=["']?react-root/i, /JavaScript is not available/i, /detected that JavaScript is disabled/i]; export function extractX(input: PageExtractInput): PageRecordDraft[] { const html = unwrapWaybackHtml(input.html); const base = input.capture.originalUrl; const pageUrl = new URL(base); const target = parseXUrl(pageUrl); const root = parseHtml(html); const parents = parentMap(root); const sectionOf = (el: HtmlElement): { section: Section; group?: HtmlElement } => { let group: HtmlElement | undefined; for (let cur = parents.get(el); cur; cur = parents.get(cur)) { if (!group && classList(cur).some((c) => c === "ThreadedConversation" || c.startsWith("ThreadedConversation--"))) group = cur; if (cur.attrs.id === "ancestors" || hasClass(cur, "permalink-in-reply-tos")) return { section: "ancestor" }; if (hasClass(cur, "replies-to") || cur.attrs.id === "descendants") return { section: "reply", group }; } if (hasClass(el, "permalink-tweet") || (target.statusId && el.attrs["data-tweet-id"] === target.statusId)) return { section: "main" }; return { section: "timeline" }; }; const raws: RawTweet[] = []; for (const el of findAll(root, isDesktopTweet, isDesktopTweet)) { const { section, group } = sectionOf(el); raws.push(desktopTweet(el, base, section, group)); } for (const el of findAll(root, isMobileTweet, isMobileTweet)) { const t = mobileTweet(el, base); if (t) { if (target.statusId && t.id === target.statusId) t.section = "main"; raws.push(t); } } // Who each tweet answers. A status page shows the chain: an ancestor // answers the one before it, the page's tweet the last ancestor, a reply // the page's tweet (or the reply before it in its threaded group). const main = raws.find((t) => t.section === "main"); const ancestors = raws.filter((t) => t.section === "ancestor"); const replyOf = new Map(); ancestors.forEach((t, i) => { if (i > 0) replyOf.set(t, ref(ancestors[i - 1].id, ancestors[i - 1].handle)); }); if (main && ancestors.length > 0) { const last = ancestors[ancestors.length - 1]; replyOf.set(main, ref(last.id, last.handle)); } if (main) { const lastInGroup = new Map(); for (const t of raws.filter((x) => x.section === "reply")) { const prev = t.group ? lastInGroup.get(t.group) : undefined; replyOf.set(t, prev ? ref(prev.id, prev.handle) : ref(main.id, main.handle)); if (t.group) lastInGroup.set(t.group, t); } } const profile = target.statusId ? null : profileOf(root, base, target.handle); const drafts: PageRecordDraft[] = []; if (profile) drafts.push(profileDraft(profile, input.capture.captureTs)); const seen = new Set(); for (const t of raws) { const own = t.retweet ? t.retweet.id : t.id; if (seen.has(own)) continue; seen.add(own); const author = t.retweet ? t.retweet.by : t.handle ?? target.handle ?? ""; const authorName = t.retweet ? profile && profile.handle.toLowerCase() === t.retweet.by.toLowerCase() ? profile.name : undefined : t.name; let replyTo = replyOf.get(t); if (!replyTo && !t.retweet && t.conversationId && t.conversationId !== t.id) replyTo = ref(t.conversationId); if (!replyTo && !t.retweet && t.isReplyMarked && t.replyingTo.length === 0 && t.conversationId) replyTo = ref(t.conversationId); const isReply = !t.retweet && (Boolean(replyTo) || t.isReplyMarked); const publishedAt = t.retweet ? snowflakeIso(t.retweet.id) ?? t.publishedAt : t.publishedAt; const draft: PageRecordDraft = { kind: "tweet", itemId: `tweet-${own}`, url: statusUrl(author || undefined, own), author, text: t.text, links: t.links, isReply, isRepost: Boolean(t.retweet), }; if (authorName) draft.authorName = authorName; if (publishedAt) draft.publishedAt = publishedAt; if (t.media.length > 0) draft.media = t.media; if (replyTo && isReply) draft.replyTo = replyTo; if (t.quoted) draft.quoted = t.quoted; if (t.retweet) draft.repostOf = ref(t.id, t.handle); drafts.push(draft); } if (drafts.length > 0) return drafts; // No tweet and no header: the JavaScript app's shell, or a notice // ("Account suspended", "Sorry, that page doesn't exist!"). const shell = SHELL_MARKERS.some((re) => re.test(html)); const notice = shell ? undefined : textOf( findFirst( root, (e) => /^h[12]$/.test(e.tag) && !classList(e).some((c) => /logo/i.test(c)), (e) => e.tag === "nav" || e.tag === "header" || classList(e).some((c) => /topbar|global-nav|navbar/i.test(c)), ), ) || undefined; const what = target.statusId ? "this tweet" : "any posts"; const text = shell ? `This capture holds no posts: it is X's JavaScript app, and the capture did not keep ${what}.` : notice ? `This capture holds no posts. The page says: "${squash(notice)}".` : "This capture holds no posts."; const draft: PageRecordDraft = { kind: target.statusId ? "tweet" : "x-profile", text, links: [], noContent: true, }; if (target.handle) draft.author = target.handle; return [draft]; } export const xExtractor: PageExtractor = { name: "x", version: 1, matches(originalUrl) { return isXHost(originalUrl.hostname); }, extract: extractX, };