Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit cd0a77058439413f2a0d618fc1cad17b907543f9
parent 2436ad41311b6419487a524cf1cb7f956abb0fc1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 20 Oct 2026 09:49:54 -0400

wayback pages: the site extractors — Tumblr, X/Twitter, XenForo, Google Docs, YouTube About (release 37 S3)

Five pure PageExtractor modules registered in SITE_EXTRACTORS, most
specific first (gdoc, yt-about, x, xenforo, tumblr). Each turns one capture
into drafts with the source's own ids (tumblr-<id>, tweet-<id>, the bare
forum post id, yt-about-<channel>-<ts>), so one item seen in two captures is
one record; a shell capture is a noContent whole-page draft. Bodies are
read with the shared HTML reader and the forum parser's renderer; XenForo
reuses parseXenforoThreadPage. Synthetic fixtures only; 34 unit tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/lib/waybackPages/extractors/__fixtures__/capture.ts | 19+++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/gdoc-edit-shell.html | 12++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/gdoc-mobilebasic.html | 16++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/gdoc-pub.html | 16++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/tumblr-2012-classic-index.html | 32++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/tumblr-2012-classic-post.html | 33+++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/tumblr-2014-article-index.html | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/tumblr-about.html | 6++++++
Acommon/lib/waybackPages/extractors/__fixtures__/tumblr-minimal-tagged.html | 23+++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/x-2012-profile.html | 47+++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/x-2015-profile.html | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/x-2016-status.html | 47+++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/x-2022-shell.html | 9+++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/x-mobile-profile.html | 32++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/x-suspended.html | 10++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/xenforoCaptures.ts | 41+++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/yt-about-2013.html | 32++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/yt-about-2019-polymer.html | 8++++++++
Acommon/lib/waybackPages/extractors/__fixtures__/yt-about-2024-handle.html | 7+++++++
Acommon/lib/waybackPages/extractors/__fixtures__/yt-channel-2021.html | 7+++++++
Acommon/lib/waybackPages/extractors/gdoc.test.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/gdoc.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/index.test.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/waybackPages/extractors/index.ts | 16+++++++++++++++-
Acommon/lib/waybackPages/extractors/tumblr.test.ts | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/tumblr.ts | 329+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/util.ts | 270+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/x.test.ts | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/x.ts | 521+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/xenforo.test.ts | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/xenforo.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/ytAbout.test.ts | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/waybackPages/extractors/ytAbout.ts | 319+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
33 files changed, 2824 insertions(+), 1 deletion(-)

diff --git a/common/lib/waybackPages/extractors/__fixtures__/capture.ts b/common/lib/waybackPages/extractors/__fixtures__/capture.ts @@ -0,0 +1,19 @@ +// The capture a test hands an extractor, and a fixture file's text. + +import { readFileSync } from "node:fs"; +import type { PageExtractInput } from "../../types"; + +export function captureOf(originalUrl: string, captureTs: string): PageExtractInput["capture"] { + return { + originalUrl, + captureTs, + waybackUrl: `https://web.archive.org/web/${captureTs}/${originalUrl}`, + rawUrl: `https://web.archive.org/web/${captureTs}id_/${originalUrl}`, + mimetype: "text/html", + status: 200, + }; +} + +export function fixture(name: string): string { + return readFileSync(new URL(`./${name}`, import.meta.url), "utf8"); +} diff --git a/common/lib/waybackPages/extractors/__fixtures__/gdoc-edit-shell.html b/common/lib/waybackPages/extractors/__fixtures__/gdoc-edit-shell.html @@ -0,0 +1,12 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Google Docs /edit capture: the editor's frame, no document text. --> +<html lang="en" dir="ltr"><head><title>Teapot Society Minutes - Google Docs</title> +<meta property="og:title" content="Teapot Society Minutes"><meta property="og:type" content="article"><meta itemprop="name" content="Teapot Society Minutes"> +<script nonce="x">var DOCS_timing = {}; DOCS_timing['pls'] = new Date().getTime();</script></head> +<body class="docs-gm docs-material" itemscope itemtype="http://schema.org/CreativeWork/DocumentObject"> +<noscript><div class="jfk-butterBar jfk-butterBar-shown jfk-butterBar-warning">JavaScript isn't enabled in your browser, so this file can't be opened. Enable and reload.</div></noscript> +<div id="docs-header-container" class="docs-header-container"><div id="docs-titlebar-container"><div class="docs-title-outer"><input class="docs-title-input" value="Teapot Society Minutes" aria-label="Rename"></div></div> +<div id="docs-menubar" class="docs-menubar"><div id="docs-file-menu" class="menu-button">File</div><div id="docs-edit-menu" class="menu-button">Edit</div><div id="docs-view-menu" class="menu-button">View</div></div></div> +<div id="docs-editor-container"><div id="docs-editor" class="kix-appview-editor"><div class="kix-zoomdocumentplugin-outer"></div></div></div> +<script nonce="x">DOCS_modelChunk = undefined;</script> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/gdoc-mobilebasic.html b/common/lib/waybackPages/extractors/__fixtures__/gdoc-mobilebasic.html @@ -0,0 +1,16 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Google Docs mobilebasic capture (2019-era markup). The document and its words are invented. --> +<html><head><meta name="viewport" content="width=device-width, initial-scale=1"><title>Teapot Society Minutes - Google Docs</title> +<style>.app-container{margin:0}</style></head> +<body><div class="app-container"> +<div class="doc-header"><div class="doc-title">Teapot Society Minutes</div></div> +<div class="doc"><div class="doc-content"><style type="text/css">ol{margin:0;padding:0}.c1{color:#000}</style> +<p class="c2 title" id="h.title"><span class="c4">Teapot Society Minutes</span></p> +<h1 class="c3" id="h.attendance"><span class="c5">Attendance</span></h1> +<p class="c1"><span>Five members came. One sent apologies.</span></p> +<h2 class="c3" id="h.decisions"><span class="c5">Decisions</span></h2> +<ul class="c6 lst-kix_list_1-0 start"><li class="c1 c7"><span>Buy a new kettle.</span></li><li class="c1 c7"><span>Meet again in June.</span></li></ul> +<p class="c1"><span>Minutes are kept at </span><span class="c8"><a class="c9" href="https://www.google.com/url?q=https://teapot-society.example/minutes&amp;sa=D&amp;source=editors&amp;ust=1560000000000000&amp;usg=AFQjCNEexample">the society site</a></span><span>.</span></p> +<p class="c1"><span></span></p> +</div></div> +</div></body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/gdoc-pub.html b/common/lib/waybackPages/extractors/__fixtures__/gdoc-pub.html @@ -0,0 +1,16 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Google Docs "published to the web" capture (pub). The document and its words are invented. --> +<html><head><meta content="text/html; charset=UTF-8" http-equiv="content-type"><title>Teapot Society Minutes</title> +<link rel="stylesheet" href="https://ssl.gstatic.com/docs/documents/client/css/1234-published.css"></head> +<body> +<div id="banners"><div id="publish-banner"><div id="publish-banner-text">Published using Google Docs</div><a href="https://docs.google.com/abuse?id=x">Report abuse</a><a href="https://support.google.com/docs/answer/183965">Learn more</a></div></div> +<div id="header"><div id="title" class="docs-title">Teapot Society Minutes</div><div id="interval"><span>Updated automatically every 5 minutes</span></div></div> +<div id="contents"><style type="text/css">.c0{font-weight:700}</style> +<h1 class="c2" id="h.attendance"><span class="c0">Attendance</span></h1> +<p class="c1"><span>Five members came. One sent apologies.</span></p> +<h2 class="c2" id="h.decisions"><span class="c0">Decisions</span></h2> +<ol class="c4 lst-kix_list_2-0 start" start="1"><li class="c1"><span>Buy a new kettle.</span></li><li class="c1"><span>Meet again in June.</span></li></ol> +<p class="c1"><img alt="" src="https://lh3.googleusercontent.com/teapot-society-photo" title=""></p> +</div> +<div id="footer"><div id="footer-inner">Published by <a href="https://docs.google.com">Google Docs</a> – <a href="https://docs.google.com/abuse?id=x">Report abuse</a> – Updated automatically every 5 minutes</div></div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/tumblr-2012-classic-index.html b/common/lib/waybackPages/extractors/__fixtures__/tumblr-2012-classic-index.html @@ -0,0 +1,32 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: the same 2012 classic theme, the blog's index page. --> +<html> +<head> +<title>Teapot Notes</title> +<link rel="stylesheet" href="http://static.tumblr.com/abc123/theme.css" /> +</head> +<body> +<iframe id="tumblr_controls" src="http://assets.tumblr.com/iframe.html?lang=en_US&amp;name=teapot-notes" width="1" height="1"></iframe> +<div id="header"><h1><a href="/">Teapot Notes</a></h1></div> +<div id="content"> + <div class="post"> + <h3><a href="http://teapot-notes.tumblr.com/post/20000000002/on-handles">On handles</a></h3> + <p>Handles should be warm to the touch.</p> + <div class="date"><a href="http://teapot-notes.tumblr.com/post/20000000002/on-handles">May 10th, 2012</a></div> + </div> + <div class="post"> + <h3><a href="http://teapot-notes.tumblr.com/post/20000000001/on-spouts">On spouts</a></h3> + <p>A good spout <b>never</b> drips.</p> + <p>See the <a href="http://www.google.com/url?q=http%3A%2F%2Fexample.com%2Fspouts&amp;sa=D">spout survey</a> for more.</p> + <img src="http://24.media.tumblr.com/tumblr_m3abc_500.jpg" alt="a brown teapot" /> + <div class="date"><a href="http://teapot-notes.tumblr.com/post/20000000001/on-spouts">May 3rd, 2012</a></div> + <div class="tags"> + <a href="http://teapot-notes.tumblr.com/tagged/teapots">#teapots</a> + <a href="http://teapot-notes.tumblr.com/tagged/kitchen+history">#kitchen history</a> + </div> + <div class="notes">12 notes</div> + </div> + <div id="navigation"><a href="/page/2">Older &rarr;</a></div> +</div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/tumblr-2012-classic-post.html b/common/lib/waybackPages/extractors/__fixtures__/tumblr-2012-classic-post.html @@ -0,0 +1,33 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2012-era classic Tumblr theme, permalink page. Blog, posts and words are invented. --> +<html> +<head> +<title>Teapot Notes — On spouts</title> +<meta name="description" content="A blog about teapots." /> +<link rel="alternate" type="application/rss+xml" href="http://teapot-notes.tumblr.com/rss" /> +<link rel="stylesheet" href="http://static.tumblr.com/abc123/theme.css" /> +</head> +<body> +<iframe id="tumblr_controls" src="http://assets.tumblr.com/iframe.html?src=http%3A%2F%2Fteapot-notes.tumblr.com%2Fpost%2F20000000001&amp;lang=en_US&amp;name=teapot-notes" width="1" height="1"></iframe> +<div id="header"><h1><a href="/">Teapot Notes</a></h1><p class="description">Spouts, lids and handles.</p></div> +<div id="content"> + <div class="post"> + <h3><a href="http://teapot-notes.tumblr.com/post/20000000001/on-spouts">On spouts</a></h3> + <p>A good spout <b>never</b> drips.</p> + <p>See the <a href="http://www.google.com/url?q=http%3A%2F%2Fexample.com%2Fspouts&amp;sa=D">spout survey</a> for more.</p> + <img src="http://24.media.tumblr.com/tumblr_m3abc_500.jpg" alt="a brown teapot" /> + <div class="date"><a href="http://teapot-notes.tumblr.com/post/20000000001/on-spouts">May 3rd, 2012</a></div> + <div class="tags"> + <a href="http://teapot-notes.tumblr.com/tagged/teapots">#teapots</a> + <a href="http://teapot-notes.tumblr.com/tagged/kitchen+history">#kitchen history</a> + </div> + <div class="notes">12 notes</div> + </div> + <div id="navigation"> + <a href="http://teapot-notes.tumblr.com/post/20000000000/on-lids">&larr; Previous</a> + <a href="http://teapot-notes.tumblr.com/post/20000000002/on-handles">Next &rarr;</a> + </div> +</div> +<div id="footer">Powered by Tumblr</div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/tumblr-2014-article-index.html b/common/lib/waybackPages/extractors/__fixtures__/tumblr-2014-article-index.html @@ -0,0 +1,53 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2014-era Tumblr theme with article.post, on a custom domain, page 2 of the index. + Captured through Wayback's replay (the toolbar and rewritten URLs left in on purpose). --> +<html lang="en"> +<head> +<meta charset="utf-8"> +<title>Kettle Studio — Page 2</title> +<meta property="og:type" content="tumblr-feed:entry" /> +<meta name="tumblr-theme" content="12345" /> +<script src="https://web.archive.org/web/20140405060708js_/https://assets.tumblr.com/assets/scripts/pre_tumblelog.js"></script> +</head> +<body> +<!-- BEGIN WAYBACK TOOLBAR INSERT --> +<div id="wm-ipp">The Wayback Machine - https://web.archive.org/web/20140405060708/http://blog.kettle-studio.example/page/2 <a href="/web/20140405060708/http://blog.kettle-studio.example/post/40000000009">a toolbar link</a></div> +<!-- END WAYBACK TOOLBAR INSERT --> +<iframe id="tumblr_controls" src="https://web.archive.org/web/20140405060708if_/https://www.tumblr.com/dashboard/iframe?src=x&amp;lang=en_US&amp;name=kettlestudio" width="1" height="1"></iframe> +<header class="blog-header"><h1><a href="/web/20140405060708/http://blog.kettle-studio.example/">Kettle Studio</a></h1></header> +<main id="posts"> + <article class="post text" id="post-40000000003" data-post-id="40000000003"> + <header><h2 class="title"><a href="/web/20140405060708/http://blog.kettle-studio.example/post/40000000003/glazes">Three glazes</a></h2></header> + <div class="body"> + <p>We tried three glazes this week:</p> + <ul><li>celadon</li><li>tenmoku</li><li>shino</li></ul> + <p>Notes on the <a href="https://web.archive.org/web/20140405060708/http://glaze-wiki.example/celadon">celadon page</a>.</p> + </div> + <footer class="post-footer"> + <a class="permalink" href="/web/20140405060708/http://blog.kettle-studio.example/post/40000000003/glazes"><time datetime="2014-03-02T10:15:00-05:00">March 2, 2014</time></a> + <ul class="tags"><li><a href="/web/20140405060708/http://blog.kettle-studio.example/tagged/glaze">glaze</a></li><li><a href="/web/20140405060708/http://blog.kettle-studio.example/tagged/kiln-day">kiln day</a></li></ul> + <span class="note-count">4 notes</span> + </footer> + </article> + <article class="post photo" id="post-40000000002" data-post-id="40000000002"> + <div class="photo-wrapper"><img src="https://web.archive.org/web/20140405060708im_/http://31.media.tumblr.com/tumblr_n1photo_1280.jpg" alt="kiln shelf"></div> + <div class="caption"><p>Fresh out of the kiln.</p></div> + <footer class="post-footer"> + <a class="permalink" href="/web/20140405060708/http://blog.kettle-studio.example/post/40000000002"><time datetime="2014-02-27T08:00:00Z">February 27, 2014</time></a> + </footer> + </article> + <article class="post text reblogged" id="post-40000000001" data-post-id="40000000001"> + <div class="reblog-header">Reblogged from <a class="reblog-link" href="/web/20140405060708/http://clay-friends.tumblr.com/post/39999999999/wheel-tips">clay-friends</a></div> + <div class="body"> + <blockquote><p>Center the clay before you open it.</p></blockquote> + <p>Always good advice.</p> + </div> + <footer class="post-footer"> + <a class="permalink" href="/web/20140405060708/http://blog.kettle-studio.example/post/40000000001/wheel-tips"><time datetime="2014-02-20">February 20, 2014</time></a> + <ul class="tags"><li><a href="/web/20140405060708/http://blog.kettle-studio.example/tagged/wheel">wheel</a></li></ul> + </footer> + </article> +</main> +<nav class="pagination"><a href="/web/20140405060708/http://blog.kettle-studio.example/page/1">Newer</a> <a href="/web/20140405060708/http://blog.kettle-studio.example/page/3">Older</a></nav> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/tumblr-about.html b/common/lib/waybackPages/extractors/__fixtures__/tumblr-about.html @@ -0,0 +1,6 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a Tumblr blog's about page (no posts on it). --> +<html><head><title>About — quiet kettle</title></head> +<body> +<div id="content"><h2>About</h2><p>A blog about kettles, run by one person.</p></div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/tumblr-minimal-tagged.html b/common/lib/waybackPages/extractors/__fixtures__/tumblr-minimal-tagged.html @@ -0,0 +1,23 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a minimal Tumblr theme (no post classes), a tagged page. --> +<html> +<head><title>quiet kettle</title> +<script type="text/javascript" src="http://assets.tumblr.com/assets/scripts/tumblelog.js"></script> +</head> +<body> +<div id="wrap"> + <h1>quiet kettle</h1> + <div> + <div> + <p>Steam is just water being dramatic.</p> + <p class="meta"><span class="posted">Posted on March 2nd, 2013 at 10:00am</span> · <a href="http://quiet-kettle.tumblr.com/post/30000000002">permalink</a> · <a href="http://quiet-kettle.tumblr.com/tagged/steam">#steam</a></p> + </div> + <div> + <p>The whistle is a feature.</p> + <p>Not a bug.</p> + <p class="meta"><span class="posted">Posted on February 28th, 2013 at 9:30pm</span> · <a href="http://quiet-kettle.tumblr.com/post/30000000001">permalink</a> · <a href="http://quiet-kettle.tumblr.com/tagged/steam">#steam</a> <a href="http://quiet-kettle.tumblr.com/tagged/whistles">#whistles</a></p> + </div> + </div> +</div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/x-2012-profile.html b/common/lib/waybackPages/extractors/__fixtures__/x-2012-profile.html @@ -0,0 +1,47 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: the 2012 desktop Twitter profile layout. Accounts, ids and words are invented. --> +<html lang="en"><head><meta charset="utf-8"><title>Kettle Friend (kettlefriend) on Twitter</title></head> +<body class="t1 logged-out"> +<div id="doc"><div id="page-outer"><div id="page-container" class="wrapper wrapper-profile"> +<div class="dashboard"> + <div class="module profile-card component profile-header"> + <div class="profile-header-inner flex-module clearfix"> + <div class="profile-card-inner" data-screen-name="kettlefriend" data-user-id="1002"> + <h1 class="fullname editable-group"><span class="profile-field">Kettle Friend</span></h1> + <h2 class="username"><a href="/kettlefriend" class="pretty-link"><s>@</s><span class="screen-name">kettlefriend</span></a></h2> + <div class="bio-container editable-group"><p class="bio profile-field">Boiling water since 2009.</p></div> + <p class="location-and-url"><span class="location-container editable-group"><span class="location profile-field">Kettlewell</span></span><span class="divider">·</span><span class="url editable-group"><span class="profile-field"><a target="_blank" rel="me nofollow" href="http://t.co/kf" title="http://kettle.example">http://kettle.example</a></span></span></p> + </div> + </div> + <div class="flex-module profile-banner-footer clearfix"> + <ul class="stats js-mini-profile-stats" data-user-id="1002"> + <li><a data-element-term="tweet_stats" href="/kettlefriend" data-nav="profile"><strong>2,001</strong> Tweets</a></li> + <li><a data-element-term="following_stats" href="/kettlefriend/following" data-nav="following"><strong>150</strong> Following</a></li> + <li><a data-element-term="follower_stats" href="/kettlefriend/followers" data-nav="followers"><strong>3,456</strong> Followers</a></li> + </ul> + </div> + </div> +</div> +<div class="content-main" id="timeline"> +<div class="stream-container"><div class="stream"><div id="stream-items-id" class="stream-items"> + <div class="js-stream-item stream-item expanding-stream-item" data-item-id="186732198097850369" data-item-type="tweet"> + <div class="tweet original-tweet js-original-tweet js-stream-tweet js-actionable-tweet js-profile-popup-actionable" data-tweet-id="186732198097850369" data-item-id="186732198097850369" data-screen-name="kettlefriend" data-name="Kettle Friend" data-user-id="1002"> + <div class="content"> + <div class="stream-item-header"><a class="account-group js-account-group js-action-profile js-user-profile-link" href="/kettlefriend" data-user-id="1002"><strong class="fullname js-action-profile-name show-popup-with-id">Kettle Friend</strong><span>&rlm;</span><span class="username js-action-profile-name"><s>@</s><b>kettlefriend</b></span></a> + <small class="time"><a href="/kettlefriend/status/186732198097850369" class="tweet-timestamp js-permalink js-nav" title="8:30 AM - 2 Apr 12"><span class="_timestamp js-short-timestamp js-relative-timestamp" data-time="1333355400" data-long-form="true">2 Apr</span></a></small></div> + <p class="js-tweet-text">Water boils at 100 degrees. Mostly. <a href="http://t.co/boil" class="twitter-timeline-link" data-expanded-url="http://physics.example/boiling" title="http://physics.example/boiling" dir="ltr"><span class="invisible">http://</span><span class="js-display-url">physics.example/boiling</span><span class="invisible"></span><span class="tco-ellipsis"><span class="invisible">&nbsp;</span></span></a></p> + </div> + </div> + </div> + <div class="js-stream-item stream-item expanding-stream-item" data-item-id="186422658462650369" data-item-type="tweet"> + <div class="tweet original-tweet js-original-tweet js-stream-tweet" data-tweet-id="186422658462650369" data-item-id="186422658462650369" data-screen-name="kettlefriend" data-name="Kettle Friend" data-user-id="1002"> + <div class="content"> + <div class="stream-item-header"><small class="time"><a href="/kettlefriend/status/186422658462650369" class="tweet-timestamp js-permalink" title="12:00 PM - 1 Apr 12"><span class="_timestamp js-short-timestamp" data-time="1333281600">1 Apr</span></a></small></div> + <p class="js-tweet-text">No jokes today, only <a href="/search?q=%23tea&amp;src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr"><s>#</s><b>tea</b></a>.</p> + </div> + </div> + </div> +</div></div></div> +</div> +</div></div></div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/x-2015-profile.html b/common/lib/waybackPages/extractors/__fixtures__/x-2015-profile.html @@ -0,0 +1,84 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: the 2014–2019 desktop Twitter profile layout. Accounts, ids and words are invented. --> +<html lang="en" data-scribe-reduced-action-queue="true"> +<head><meta charset="utf-8"><title>Teapot Fan (@TeapotFan) | Twitter</title> +<link rel="canonical" href="https://twitter.com/TeapotFan"></head> +<body class="three-col logged-out user-style-TeapotFan" data-fouc-class-names="swift-loading"> +<div id="doc" class="route-profile"> +<div class="ProfileCanopy ProfileCanopy--withNav"> + <div class="ProfileCanopy-navBar"><div class="ProfileNav" role="navigation" data-user-id="1001"><ul class="ProfileNav-list"> + <li class="ProfileNav-item ProfileNav-item--tweets is-active"><a class="ProfileNav-stat ProfileNav-stat--link u-borderUserColor u-textCenter js-tooltip js-nav" title="1,234 Tweets" data-nav="tweets"><span class="ProfileNav-label">Tweets</span><span class="ProfileNav-value" data-count="1234" data-is-compact="false">1,234</span></a></li> + <li class="ProfileNav-item ProfileNav-item--following"><a class="ProfileNav-stat" href="/TeapotFan/following"><span class="ProfileNav-label">Following</span><span class="ProfileNav-value" data-count="56">56</span></a></li> + <li class="ProfileNav-item ProfileNav-item--followers"><a class="ProfileNav-stat" href="/TeapotFan/followers"><span class="ProfileNav-label">Followers</span><span class="ProfileNav-value" data-count="7890">7,890</span></a></li> + <li class="ProfileNav-item ProfileNav-item--favorites"><a class="ProfileNav-stat" href="/TeapotFan/likes"><span class="ProfileNav-label">Likes</span><span class="ProfileNav-value" data-count="12">12</span></a></li> + </ul></div></div> +</div> +<div class="AppContainer"><div class="AppContent-main content-main u-cf" role="main"> +<div class="Grid Grid--withGutter"> +<div class="Grid-cell u-size1of3 u-lg-size1of4"><div class="ProfileSidebar ProfileSidebar--withLeftAlignment"> + <div class="ProfileHeaderCard"> + <h1 class="ProfileHeaderCard-name"><a href="/TeapotFan" class="ProfileHeaderCard-nameLink u-textInheritColor js-nav">Teapot Fan</a></h1> + <h2 class="ProfileHeaderCard-screenname u-inlineBlock u-dir" dir="ltr"><a class="ProfileHeaderCard-screennameLink u-linkComplex js-nav" href="/TeapotFan"><span class="username u-dir" dir="ltr">@<b class="u-linkComplex-target">TeapotFan</b></span></a></h2> + <p class="ProfileHeaderCard-bio u-dir" dir="ltr">I collect teapots. Kettles too, ask <a href="/kettlefriend" class="twitter-atreply pretty-link js-nav" dir="ltr"><s>@</s><b>kettlefriend</b></a>. More at <a href="https://t.co/site" rel="nofollow noopener" dir="ltr" data-expanded-url="https://teapots.example" class="twitter-timeline-link" target="_blank" title="https://teapots.example"><span class="invisible">https://</span><span class="js-display-url">teapots.example</span></a></p> + <div class="ProfileHeaderCard-location "><span class="Icon Icon--geo Icon--medium" aria-hidden="true" role="presentation"></span><span class="ProfileHeaderCard-locationText u-dir" dir="ltr">Leeds</span></div> + <div class="ProfileHeaderCard-url "><span class="Icon Icon--url Icon--medium" aria-hidden="true" role="presentation"></span><span class="ProfileHeaderCard-urlText u-dir"><a class="u-textUserColor" target="_blank" rel="me nofollow" href="https://t.co/site" title="https://teapots.example">teapots.example</a></span></div> + <div class="ProfileHeaderCard-joinDate"><span class="Icon Icon--calendar Icon--medium" aria-hidden="true" role="presentation"></span><span class="ProfileHeaderCard-joinDateText js-tooltip u-dir" dir="ltr" title="3:04 PM - 5 Jun 2009">Joined June 2009</span></div> + </div> +</div></div> +<div class="Grid-cell u-size2of3 u-lg-size3of4"><div class="ProfileTimeline"> +<ol class="stream-items js-navigable-stream" id="stream-items-id"> + <li class="js-stream-item stream-item stream-item js-pinned" data-item-id="606838887674810369" id="stream-item-tweet-606838887674810369" data-item-type="tweet"> + <div class="tweet js-stream-tweet js-actionable-tweet user-pinned original-tweet" data-tweet-id="606838887674810369" data-item-id="606838887674810369" data-permalink-path="/TeapotFan/status/606838887674810369" data-conversation-id="606838887674810369" data-screen-name="TeapotFan" data-name="Teapot Fan" data-user-id="1001"> + <div class="context"><div class="tweet-context with-icn"><span class="Icon Icon--small Icon--pinned"></span><span class="js-pinned-text">Pinned Tweet</span></div></div> + <div class="content"> + <div class="stream-item-header"><a class="account-group js-account-group" href="/TeapotFan" data-user-id="1001"><strong class="fullname show-popup-with-id" data-aria-label-part>Teapot Fan</strong><span class="username u-dir" dir="ltr">@<b>TeapotFan</b></span></a> + <small class="time"><a href="/TeapotFan/status/606838887674810369" class="tweet-timestamp js-permalink js-nav js-tooltip" title="3:04 PM - 5 Jun 2015"><span class="_timestamp js-short-timestamp" data-aria-label-part="last" data-time="1433516640" data-time-ms="1433516640000" data-long-form="true">Jun 5</span></a></small></div> + <div class="js-tweet-text-container"><p class="TweetTextSize TweetTextSize--normal js-tweet-text tweet-text" lang="en" data-aria-label-part="0">Brewing the first pot of the day <img class="Emoji Emoji--forText" src="https://abs.twimg.com/emoji/v2/72x72/2615.png" draggable="false" alt="☕" title="Hot beverage" aria-label="Emoji: Hot beverage"> with <a href="/kettlefriend" class="twitter-atreply pretty-link js-nav" dir="ltr" data-mentioned-user-id="1002"><s>@</s><b>kettlefriend</b></a> <a href="/hashtag/tea?src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr"><s>#</s><b>tea</b></a> <a href="https://t.co/brew" rel="nofollow noopener" dir="ltr" data-expanded-url="https://example.com/brew" class="twitter-timeline-link" target="_blank" title="https://example.com/brew"><span class="tco-ellipsis"></span><span class="invisible">https://</span><span class="js-display-url">example.com/brew</span><span class="invisible"></span><span class="tco-ellipsis"><span class="invisible">&nbsp;</span></span></a><a href="https://t.co/pic" class="twitter-timeline-link u-hidden" data-pre-embedded="true" dir="ltr">pic.twitter.com/pic</a></p></div> + <div class="AdaptiveMediaOuterContainer"><div class="AdaptiveMedia is-square"><div class="AdaptiveMedia-container"><div class="AdaptiveMedia-singlePhoto"><div class="AdaptiveMedia-photoContainer js-adaptive-photo" data-image-url="https://pbs.twimg.com/media/CGteapotA.jpg" data-element-context="platform_photo_card"><img data-aria-label-part src="https://pbs.twimg.com/media/CGteapotA.jpg" alt=""></div></div></div></div></div> + <div class="stream-item-footer"><div class="ProfileTweet-actionCountList u-hiddenVisually"><span class="ProfileTweet-action--retweet u-hiddenVisually"><span class="ProfileTweet-actionCount" data-tweet-stat-count="3">3 retweets</span></span></div></div> + </div> + </div> + </li> + <li class="js-stream-item stream-item stream-item" data-item-id="606838887674810369" data-item-type="tweet"> + <div class="tweet js-stream-tweet js-actionable-tweet original-tweet" data-tweet-id="606838887674810369" data-conversation-id="606838887674810369" data-screen-name="TeapotFan" data-name="Teapot Fan" data-user-id="1001"> + <div class="content"><div class="stream-item-header"><small class="time"><a href="/TeapotFan/status/606838887674810369" class="tweet-timestamp"><span class="_timestamp" data-time="1433516640">Jun 5</span></a></small></div> + <div class="js-tweet-text-container"><p class="tweet-text">Brewing the first pot of the day (the same tweet, shown again below the pin)</p></div></div> + </div> + </li> + <li class="js-stream-item stream-item stream-item" data-item-id="606384896209850369" data-item-type="tweet"> + <div class="tweet js-stream-tweet js-actionable-tweet original-tweet" data-tweet-id="606384896209850369" data-item-id="606384896209850369" data-permalink-path="/TeapotFan/status/606384896209850369" data-conversation-id="186422658462650369" data-is-reply-to="true" data-has-parent-tweet="true" data-screen-name="TeapotFan" data-name="Teapot Fan" data-user-id="1001"> + <div class="content"> + <div class="stream-item-header"><small class="time"><a href="/TeapotFan/status/606384896209850369" class="tweet-timestamp js-permalink" title="9:00 AM - 4 Jun 2015"><span class="_timestamp js-short-timestamp" data-time="1433408400" data-time-ms="1433408400000">Jun 4</span></a></small></div> + <div class="ReplyingToContextBelowAuthor" data-aria-label-part>Replying to <a class="pretty-link js-user-profile-link" href="/kettlefriend" data-user-id="1002" rel="noopener" dir="ltr"><span class="username u-dir" dir="ltr">@<b>kettlefriend</b></span></a></div> + <div class="js-tweet-text-container"><p class="TweetTextSize js-tweet-text tweet-text" lang="en">Agreed, a warm pot matters. +Always warm it first.</p></div> + </div> + </div> + </li> + <li class="js-stream-item stream-item stream-item" data-item-id="606163436958650369" data-item-type="tweet"> + <div class="tweet js-stream-tweet js-actionable-tweet original-tweet retweeted" data-tweet-id="605267533624250369" data-item-id="605267533624250369" data-permalink-path="/kettlefriend/status/605267533624250369" data-conversation-id="605267533624250369" data-retweet-id="606163436958650369" data-retweeter="TeapotFan" data-screen-name="kettlefriend" data-name="Kettle Friend" data-user-id="1002"> + <div class="context"><div class="tweet-context with-icn"><span class="Icon Icon--small Icon--retweeted"></span><span class="js-retweet-text"><a class="pretty-link js-user-profile-link" href="/TeapotFan" data-user-id="1001" rel="noopener"><b>Teapot Fan</b></a> Retweeted</span></div></div> + <div class="content"> + <div class="stream-item-header"><a class="account-group" href="/kettlefriend"><strong class="fullname">Kettle Friend</strong><span class="username">@<b>kettlefriend</b></span></a><small class="time"><a href="/kettlefriend/status/605267533624250369" class="tweet-timestamp"><span class="_timestamp" data-time="1433142000">Jun 1</span></a></small></div> + <div class="js-tweet-text-container"><p class="TweetTextSize js-tweet-text tweet-text" lang="en">Descaling day. Vinegar works.</p></div> + </div> + </div> + </li> + <li class="js-stream-item stream-item stream-item" data-item-id="604605924111290369" data-item-type="tweet"> + <div class="tweet js-stream-tweet js-actionable-tweet original-tweet has-quoted-tweet" data-tweet-id="604605924111290369" data-item-id="604605924111290369" data-conversation-id="604605924111290369" data-screen-name="TeapotFan" data-name="Teapot Fan" data-user-id="1001"> + <div class="content"> + <div class="stream-item-header"><small class="time"><a href="/TeapotFan/status/604605924111290369" class="tweet-timestamp"><span class="_timestamp" data-time="1432984260">May 30</span></a></small></div> + <div class="js-tweet-text-container"><p class="TweetTextSize js-tweet-text tweet-text" lang="en">Still true three years later <a href="https://t.co/q" class="twitter-timeline-link u-hidden" data-expanded-url="https://twitter.com/kettlefriend/status/186732198097850369" dir="ltr">twitter.com/kettlefriend/s…</a></p></div> + <div class="QuoteTweet u-block js-tweet-details-fixer"><div class="QuoteTweet-container"><a class="QuoteTweet-link js-nav" href="/kettlefriend/status/186732198097850369" data-conversation-id="186732198097850369"></a> + <div class="QuoteTweet-innerContainer u-cf js-permalink js-media-container" data-item-id="186732198097850369" data-item-type="tweet" data-screen-name="kettlefriend" data-user-id="1002" href="/kettlefriend/status/186732198097850369" tabindex="0"> + <div class="tweet-content"><div class="QuoteTweet-authorAndText u-alignTop"><div class="QuoteTweet-originalAuthor u-cf u-textTruncate stream-item-header account-group js-user-profile-link"><b class="QuoteTweet-fullname u-linkComplex-target">Kettle Friend</b><span class="username u-dir" dir="ltr">@<b>kettlefriend</b></span></div> + <div class="QuoteTweet-text tweet-text u-dir js-ellipsis" lang="en" data-aria-label-part="2" dir="ltr">Water boils at 100 degrees. Mostly.</div></div></div> + </div></div></div> + </div> + </div> + </li> +</ol> +</div></div> +</div></div></div></div> +</body> +</html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/x-2016-status.html b/common/lib/waybackPages/extractors/__fixtures__/x-2016-status.html @@ -0,0 +1,47 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2016 desktop Twitter status page: ancestors, the tweet, replies. Accounts, ids and words are invented. --> +<html lang="en"><head><meta charset="utf-8"><title>Teapot Fan on Twitter: "Brown hides the tea stains."</title> +<link rel="canonical" href="https://twitter.com/TeapotFan/status/697374449464250369"></head> +<body class="three-col logged-out PermalinkPage"> +<div id="doc" class="route-permalink"> +<div class="PermalinkOverlay-content"><div class="permalink-container"> +<div class="permalink light-inline-actions stream-uncapped has-replies original-permalink-page" role="main"> + <div class="permalink-in-reply-tos" id="ancestors"> + <ol class="stream-items js-navigable-stream"> + <li class="js-stream-item stream-item" data-item-id="697359349969850369"><div class="tweet js-stream-tweet ancestor" data-tweet-id="697359349969850369" data-conversation-id="697359349969850369" data-screen-name="kettlefriend" data-name="Kettle Friend"> + <div class="content"><small class="time"><a class="tweet-timestamp" href="/kettlefriend/status/697359349969850369"><span class="_timestamp" data-time="1455098400">Feb 10</span></a></small><div class="js-tweet-text-container"><p class="tweet-text">Which teapot is best?</p></div></div></div></li> + <li class="js-stream-item stream-item" data-item-id="697360608261050369"><div class="tweet js-stream-tweet ancestor" data-tweet-id="697360608261050369" data-conversation-id="697359349969850369" data-has-parent-tweet="true" data-screen-name="TeapotFan" data-name="Teapot Fan"> + <div class="content"><small class="time"><a class="tweet-timestamp" href="/TeapotFan/status/697360608261050369"><span class="_timestamp" data-time="1455098700">Feb 10</span></a></small><div class="js-tweet-text-container"><p class="tweet-text"><a href="/kettlefriend" class="twitter-atreply pretty-link"><s>@</s><b>kettlefriend</b></a> The brown one, obviously.</p></div></div></div></li> + <li class="js-stream-item stream-item" data-item-id="697364383134650369"><div class="tweet js-stream-tweet ancestor" data-tweet-id="697364383134650369" data-conversation-id="697359349969850369" data-has-parent-tweet="true" data-screen-name="kettlefriend" data-name="Kettle Friend"> + <div class="content"><small class="time"><a class="tweet-timestamp" href="/kettlefriend/status/697364383134650369"><span class="_timestamp" data-time="1455099600">Feb 10</span></a></small><div class="js-tweet-text-container"><p class="tweet-text">Why brown?</p></div></div></div></li> + </ol> + </div> + <div class="permalink-inner permalink-tweet-container"> + <div class="tweet permalink-tweet js-actionable-user js-actionable-tweet js-original-tweet has-cards" data-tweet-id="697374449464250369" data-item-id="697374449464250369" data-screen-name="TeapotFan" data-name="Teapot Fan" data-user-id="1001" data-conversation-id="697359349969850369" data-has-parent-tweet="true"> + <div class="content clearfix"><div class="permalink-header"><a class="account-group" href="/TeapotFan"><strong class="fullname">Teapot Fan</strong><span class="username">@<b>TeapotFan</b></span></a></div></div> + <div class="js-tweet-text-container"><p class="TweetTextSize TweetTextSize--jumbo js-tweet-text tweet-text" lang="en">Brown hides the tea stains.</p></div> + <div class="js-tweet-details-fixer tweet-details-fixer"><div class="client-and-actions"><span class="metadata"><span>11:00 AM - 10 Feb 2016</span></span></div></div> + </div> + </div> + <div class="replies-to permalink-inner permalink-replies" data-component-context="replies"> + <div class="stream-container"><div class="stream"><ol class="stream-items js-navigable-stream" id="stream-items-id"> + <li class="ThreadedConversation"> + <ol class="stream-items"> + <li class="js-stream-item stream-item" data-item-id="697381999211450369"><div class="tweet js-stream-tweet" data-tweet-id="697381999211450369" data-conversation-id="697359349969850369" data-has-parent-tweet="true" data-screen-name="kettlefriend" data-name="Kettle Friend"> + <div class="content"><small class="time"><a class="tweet-timestamp" href="/kettlefriend/status/697381999211450369"><span class="_timestamp" data-time="1455103800">Feb 10</span></a></small><div class="js-tweet-text-container"><p class="tweet-text">Fair point.</p></div></div></div></li> + <li class="js-stream-item stream-item" data-item-id="697389548958650369"><div class="tweet js-stream-tweet" data-tweet-id="697389548958650369" data-conversation-id="697359349969850369" data-has-parent-tweet="true" data-screen-name="TeapotFan" data-name="Teapot Fan"> + <div class="content"><small class="time"><a class="tweet-timestamp" href="/TeapotFan/status/697389548958650369"><span class="_timestamp" data-time="1455105600">Feb 10</span></a></small><div class="js-tweet-text-container"><p class="tweet-text">Thank you.</p></div></div></div></li> + </ol> + </li> + <li class="ThreadedConversation--loneTweet"> + <ol class="stream-items"> + <li class="js-stream-item stream-item" data-item-id="697381999211450370"><div class="tweet js-stream-tweet" data-tweet-id="697381999211450370" data-conversation-id="697359349969850369" data-has-parent-tweet="true" data-screen-name="mugperson" data-name="Mug Person"> + <div class="content"><small class="time"><a class="tweet-timestamp" href="/mugperson/status/697381999211450370"><span class="_timestamp" data-time="1455103800">Feb 10</span></a></small><div class="js-tweet-text-container"><p class="tweet-text">Mugs are better.</p></div></div></div></li> + </ol> + </li> + </ol></div></div> + </div> +</div> +</div></div> +</div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/x-2022-shell.html b/common/lib/waybackPages/extractors/__fixtures__/x-2022-shell.html @@ -0,0 +1,9 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a capture of X's JavaScript app (2022): the shell only. --> +<html dir="ltr" lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Twitter</title> +<style>body{margin:0}</style></head> +<body style="background-color:#FFFFFF"> +<noscript><form action="https://mobile.twitter.com/i/nojs_router?path=%2FTeapotFan" method="POST" style="background-color:#fff;position:fixed;top:0;left:0;right:0;bottom:0;z-index:200"><div><div class="errorContainer"><h1>JavaScript is not available.</h1><p>We’ve detected that JavaScript is disabled in this browser. Please enable JavaScript or switch to a supported browser to continue using twitter.com.</p></div></div></form></noscript> +<div id="react-root" style="height:100%;display:flex;"><div class="css-1dbjc4n r-13awgt0 r-12vffkv"><div class="css-1dbjc4n r-13awgt0 r-12vffkv"><div aria-label="Loading…" class="css-1dbjc4n r-1awozwy r-1p0dtai"></div></div></div></div> +<script src="https://abs.twimg.com/responsive-web/client-web/main.abc123.js" nonce="x"></script> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/x-mobile-profile.html b/common/lib/waybackPages/extractors/__fixtures__/x-mobile-profile.html @@ -0,0 +1,32 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: the legacy mobile.twitter.com profile layout (table.tweet). Accounts, ids and words are invented. --> +<html><head><title>Teapot Fan (@TeapotFan) on Twitter</title></head> +<body> +<div id="container"><div id="main_content"> +<div class="profile"> + <table class="profile-details"> + <tr><td class="avatar"><img alt="Teapot Fan" src="https://pbs.twimg.com/profile_images/1/teapot_normal.jpg"></td> + <td class="user-info"><div class="fullname">Teapot Fan</div><div class="username"><span class="screen-name">TeapotFan</span></div></td></tr> + <tr><td colspan="2" class="details"><div class="location">Leeds</div><div class="bio"><div class="dir-ltr" dir="ltr">I collect teapots.</div></div><div class="url"><div class="dir-ltr" dir="ltr"><a href="https://t.co/site" data-url="https://teapots.example" class="twitter_external_link dir-ltr tco-link" rel="nofollow" target="_blank">teapots.example</a></div></div></td></tr> + </table> + <table class="profile-stats"> + <tr><td><div class="statnum">1,500</div><div class="statlabel"> Tweets </div></td><td><div class="statnum">60</div><div class="statlabel"> Following </div></td><td><div class="statnum">8,001</div><div class="statlabel"> Followers </div></td></tr> + </table> +</div> +<div class="timeline"> + <table class="tweet " href="/TeapotFan/status/1038715922543546369?p=v"> + <tr class="tweet-header "><td class="avatar" rowspan="3"><a href="/TeapotFan?p=s"><img alt="Teapot Fan" src="https://pbs.twimg.com/profile_images/1/teapot_normal.jpg"></a></td> + <td class="user-info"><a href="/TeapotFan?p=s"><strong class="fullname">Teapot Fan</strong><div class="username"><span>@</span>TeapotFan</div></a></td> + <td class="timestamp"><a name="tweet_1038715922543546369" href="/TeapotFan/status/1038715922543546369?p=p">9h</a></td></tr> + <tr class="tweet-container"><td colspan="2" class="tweet-content"><div class="tweet-text" data-id="1038715922543546369"><div class="dir-ltr" dir="ltr"> New shelf for the collection <a href="https://t.co/oak" data-url="https://shelves.example/oak" class="twitter_external_link dir-ltr tco-link" rel="nofollow" target="_blank" title="https://shelves.example/oak">shelves.example/oak</a> + <div class="media"><img src="https://pbs.twimg.com/media/DmShelf.jpg:small"></div></div></div></td></tr> + </table> + <table class="tweet " href="/TeapotFan/status/1038517326443450369?p=v"> + <tr class="tweet-header "><td class="avatar" rowspan="3"></td> + <td class="user-info"><a href="/TeapotFan?p=s"><strong class="fullname">Teapot Fan</strong><div class="username"><span>@</span>TeapotFan</div></a></td> + <td class="timestamp"><a name="tweet_1038517326443450369" href="/TeapotFan/status/1038517326443450369?p=p">Sep 8</a></td></tr> + <tr class="tweet-container"><td colspan="2" class="tweet-content"><div class="tweet-reply-context username">replying to <a href="/kettlefriend">@kettlefriend</a></div><div class="tweet-text" data-id="1038517326443450369"><div class="dir-ltr" dir="ltr"><a href="/kettlefriend" class="twitter-atreply dir-ltr" data-mentioned-user-id="1002" data-screenname="kettlefriend">@kettlefriend</a> Oak, not pine.</div></div></td></tr> + </table> +</div> +</div></div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/x-suspended.html b/common/lib/waybackPages/extractors/__fixtures__/x-suspended.html @@ -0,0 +1,10 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: an old-layout Twitter "account suspended" page. --> +<html lang="en"><head><meta charset="utf-8"><title>Twitter / Account Suspended</title></head> +<body class="logged-out"> +<div class="topbar js-topbar"><div class="global-nav"><h1 class="logo">Twitter</h1></div></div> +<div id="doc"><div class="route-account_suspended"><div class="flex-module"> + <h1>Account suspended</h1> + <p>This account has been suspended. <a href="https://support.twitter.com/articles/18311">Learn more</a> about why Twitter suspends accounts.</p> +</div></div></div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/xenforoCaptures.ts b/common/lib/waybackPages/extractors/__fixtures__/xenforoCaptures.ts @@ -0,0 +1,41 @@ +// SYNTHETIC XenForo captures for the forum extractor: the forum parser's own +// synthetic thread page (social/__fixtures__/xenforoPages.ts), as a live +// fetch gets it and as the Wayback Machine's replay serves it (its toolbar +// inserted, every same-site URL rewritten to a /web/<ts>/ URL). The forum, +// the thread, the members and every word are invented. + +import { ORIGIN, RICH_BODY, threadPage, type FakePost } from "../../../../social/__fixtures__/xenforoPages"; + +export { ORIGIN, THREAD_URL } from "../../../../social/__fixtures__/xenforoPages"; + +const T0 = 1_700_000_000; + +export const POSTS: FakePost[] = [ + { id: 1001, author: "Marigold", userId: 7, ts: T0, position: 21, body: "The blue one is a reproduction.<br />Look at the glaze." }, + { id: 1002, author: "Basil", userId: 8, ts: T0 + 600, position: 22, body: RICH_BODY, editedTs: T0 + 900 }, + { id: 1003, author: "Marigold", userId: 7, ts: T0 + 1200, position: 23, body: `Agreed. See <a href="https://teapots.example/glaze" class="link link--external">the glaze guide</a>.` }, +]; + +// The thread's page 2, as the forum serves it. +export const LIVE_PAGE = threadPage({ page: 2, last: 5, posts: POSTS }); + +export const CAPTURE_TS = "20240102030405"; + +// The same page as Wayback's replay serves it. +export function replayOf(html: string, ts = CAPTURE_TS): string { + const prefix = `/web/${ts}/`; + return html + .replace(/(href|src)="\/(?!\/)/g, `$1="${prefix}${ORIGIN}/`) + .replace(new RegExp(`(href|src|itemid)="${ORIGIN.replace(/\./g, "\\.")}`, "g"), `$1="https://web.archive.org${prefix}${ORIGIN}`) + .replace( + /<body([^>]*)>/, + `<body$1>\n<!-- BEGIN WAYBACK TOOLBAR INSERT -->\n<div id="wm-ipp-base"><a href="${prefix}${ORIGIN}/threads/elsewhere.99/">toolbar</a></div>\n<!-- END WAYBACK TOOLBAR INSERT -->`, + ); +} + +export const REPLAY_PAGE = replayOf(LIVE_PAGE); + +// A captured login wall on the same forum. +export const LOGIN_WALL = `<!DOCTYPE html> +<html id="XF" lang="en-US" data-xf="2.2" data-template="login"><head><title>Log in | Example Forum</title></head> +<body data-template="login"><div class="blockMessage">You must be logged-in to do that.</div></body></html>`; diff --git a/common/lib/waybackPages/extractors/__fixtures__/yt-about-2013.html b/common/lib/waybackPages/extractors/__fixtures__/yt-about-2013.html @@ -0,0 +1,32 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2013-era YouTube channel About page (the c4 layout). The channel and its words are invented. --> +<html lang="en" data-cast-api-enabled="true"><head> +<title>Teapot Channel - YouTube</title> +<meta name="title" content="Teapot Channel"> +<meta property="og:title" content="Teapot Channel"> +<meta property="og:description" content="Videos about teapots."> +<link rel="canonical" href="http://www.youtube.com/user/teapotchannel"> +<meta itemprop="channelId" content="UCteapot0000000000000001"> +</head> +<body class="date-20131001 en_US ltr site-left-aligned" dir="ltr"> +<div id="masthead-container"><div id="masthead"><a id="logo-container" href="/" title="YouTube home"></a></div></div> +<div id="c4-header-bg-container"></div> +<div class="primary-header-contents" id="c4-primary-header-contents"> + <h1 class="branded-page-header-title"><span class="qualified-channel-title ellipsized"><span class="qualified-channel-title-text"><a dir="ltr" href="/user/teapotchannel" class="spf-link branded-page-header-title-link yt-uix-sessionlink" title="Teapot Channel">Teapot Channel</a></span></span></h1> + <span class="yt-subscription-button-subscriber-count-branded-horizontal" title="12,345" tabindex="0">12,345</span> +</div> +<div id="browse-items-primary"><div class="about-metadata-container"> + <div class="about-description branded-page-box-padding"><pre>Videos about teapots, every Sunday. +Business enquiries through the website.</pre></div> + <div class="about-metadata branded-page-box-padding"> + <div class="about-stats"><span class="about-stat"><b>12,345</b> subscribers</span><span class="about-stat"> &bull; <b>1,234,567</b> views</span><span class="about-stat">Joined Jan 5, 2010</span></div> + <div class="country-inline">United Kingdom</div> + </div> + <div class="about-custom-links branded-page-box-padding"><h2 class="about-section-header">Links</h2> + <ul class="about-custom-links-list"> + <li class="channel-links-item"><a href="/redirect?q=https%3A%2F%2Ftwitter.com%2FTeapotFan&amp;redir_token=abc" class="about-channel-link yt-uix-redirect-link about-channel-link-with-icon" rel="me nofollow" target="_blank" title="Twitter"><img src="//s2.googleusercontent.com/s2/favicons?domain=twitter.com" class="about-channel-link-favicon" alt=""><span class="about-channel-link-text">Twitter</span></a></li> + <li class="channel-links-item"><a href="http://www.teapot-channel.example/" class="about-channel-link" rel="me nofollow" target="_blank" title="Website"><span class="about-channel-link-text">Website</span></a></li> + </ul> + </div> +</div></div> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/yt-about-2019-polymer.html b/common/lib/waybackPages/extractors/__fixtures__/yt-about-2019-polymer.html @@ -0,0 +1,8 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2019 YouTube channel About tab (the Polymer app; its data in ytInitialData). The channel and its words are invented. --> +<html lang="en" style="font-size: 10px;font-family: Roboto, Arial, sans-serif;" system-icons typography><head><title>Teapot Channel - YouTube</title> +<meta property="og:title" content="Teapot Channel"></head> +<body dir="ltr" no-y-overflow><ytd-app></ytd-app> +<script nonce="x">window["ytInitialData"] = {"responseContext": {"serviceTrackingParams": [{"service": "GFEEDBACK", "params": [{"key": "browse_id", "value": "UCteapot0000000000000001"}]}]}, "contents": {"twoColumnBrowseResultsRenderer": {"tabs": [{"tabRenderer": {"title": "Home"}}, {"tabRenderer": {"title": "About", "selected": true, "content": {"sectionListRenderer": {"contents": [{"itemSectionRenderer": {"contents": [{"channelAboutFullMetadataRenderer": {"description": {"simpleText": "Videos about teapots {and lids}, every Sunday.\nNow with kettles."}, "primaryLinks": [{"navigationEndpoint": {"urlEndpoint": {"url": "https://www.youtube.com/redirect?event=channel_banner&redir_token=x&q=https%3A%2F%2Ftwitter.com%2FTeapotFan"}}, "title": {"simpleText": "Twitter"}}, {"navigationEndpoint": {"urlEndpoint": {"url": "https://www.youtube.com/redirect?q=https%3A%2F%2Fwww.teapot-channel.example%2F"}}, "title": {"simpleText": "Website"}}], "viewCountText": {"simpleText": "2,345,678 views"}, "joinedDateText": {"runs": [{"text": "Joined "}, {"text": "Jan 5, 2010"}]}, "title": {"simpleText": "Teapot Channel"}, "country": {"simpleText": "United Kingdom"}, "channelId": "UCteapot0000000000000001"}}]}}]}}}}]}}, "header": {"c4TabbedHeaderRenderer": {"channelId": "UCteapot0000000000000001", "title": "Teapot Channel", "subscriberCountText": {"simpleText": "45K subscribers"}}}, "metadata": {"channelMetadataRenderer": {"title": "Teapot Channel", "description": "Videos about teapots {and lids}, every Sunday.\nNow with kettles.", "externalId": "UCteapot0000000000000001", "vanityChannelUrl": "http://www.youtube.com/c/TeapotChannel"}}}; +window["ytInitialPlayerResponse"] = null;</script> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/yt-about-2024-handle.html b/common/lib/waybackPages/extractors/__fixtures__/yt-about-2024-handle.html @@ -0,0 +1,7 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2024 YouTube @handle About capture (ytInitialData assigned as an escaped string). The channel and its words are invented. --> +<html lang="en" style="font-size: 10px;font-family: Roboto, Arial, sans-serif;" system-icons typography><head><title>Teapot Channel - YouTube</title> +<meta property="og:title" content="Teapot Channel"></head> +<body dir="ltr" no-y-overflow><ytd-app></ytd-app> +<script nonce="x">var ytInitialData = '\x7b\x22onResponseReceivedEndpoints\x22: \x5b\x7b\x22appendContinuationItemsAction\x22: \x7b\x22continuationItems\x22: \x5b\x7b\x22aboutChannelRenderer\x22: \x7b\x22metadata\x22: \x7b\x22aboutChannelViewModel\x22: \x7b\x22description\x22: \x22Teapots, kettles and the occasional mug.\x5cnSince 2010.\x22, \x22subscriberCountText\x22: \x2280.1K subscribers\x22, \x22viewCountText\x22: \x223,456,789 views\x22, \x22joinedDate\x22: \x7b\x22content\x22: \x22Joined Jan 5, 2010\x22\x7d, \x22country\x22: \x22United Kingdom\x22, \x22canonicalChannelUrl\x22: \x22http://www.youtube.com/@TeapotChannel\x22, \x22displayCanonicalChannelUrl\x22: \x22www.youtube.com/@TeapotChannel\x22, \x22channelId\x22: \x22UCteapot0000000000000001\x22, \x22links\x22: \x5b\x7b\x22channelExternalLinkViewModel\x22: \x7b\x22title\x22: \x7b\x22content\x22: \x22Website\x22\x7d, \x22link\x22: \x7b\x22content\x22: \x22teapot-channel.example\x22, \x22commandRuns\x22: \x5b\x7b\x22startIndex\x22: 0, \x22length\x22: 22, \x22onTap\x22: \x7b\x22innertubeCommand\x22: \x7b\x22urlEndpoint\x22: \x7b\x22url\x22: \x22https://www.youtube.com/redirect?event=channel_description&q=https%3A%2F%2Fteapot-channel.example%2F\x22\x7d\x7d\x7d\x7d\x5d\x7d\x7d\x7d\x5d\x7d\x7d\x7d\x7d\x5d\x7d\x7d\x5d, \x22header\x22: \x7b\x22pageHeaderRenderer\x22: \x7b\x22content\x22: \x7b\x22pageHeaderViewModel\x22: \x7b\x22title\x22: \x7b\x22dynamicTextViewModel\x22: \x7b\x22text\x22: \x7b\x22content\x22: \x22Teapot Channel\x22\x7d\x7d\x7d\x7d\x7d\x7d\x7d, \x22metadata\x22: \x7b\x22channelMetadataRenderer\x22: \x7b\x22title\x22: \x22Teapot Channel\x22, \x22externalId\x22: \x22UCteapot0000000000000001\x22, \x22vanityChannelUrl\x22: \x22http://www.youtube.com/@TeapotChannel\x22\x7d\x7d\x7d';</script> +</body></html> diff --git a/common/lib/waybackPages/extractors/__fixtures__/yt-channel-2021.html b/common/lib/waybackPages/extractors/__fixtures__/yt-channel-2021.html @@ -0,0 +1,7 @@ +<!DOCTYPE html> +<!-- SYNTHETIC: a 2021 YouTube bare channel page (Home tab; ytInitialData as a var). The channel and its words are invented. --> +<html lang="en" style="font-size: 10px;font-family: Roboto, Arial, sans-serif;" system-icons typography><head><title>Teapot Channel - YouTube</title> +<meta property="og:title" content="Teapot Channel"></head> +<body dir="ltr" no-y-overflow><ytd-app></ytd-app> +<script nonce="x">var ytInitialData = {"contents": {"twoColumnBrowseResultsRenderer": {"tabs": [{"tabRenderer": {"title": "Home", "selected": true}}]}}, "header": {"c4TabbedHeaderRenderer": {"channelId": "UCteapot0000000000000001", "title": "Teapot Channel", "subscriberCountText": {"simpleText": "61.2K subscribers"}, "headerLinks": {"channelHeaderLinksRenderer": {"primaryLinks": [{"navigationEndpoint": {"urlEndpoint": {"url": "https://www.youtube.com/redirect?q=https%3A%2F%2Fwww.teapot-channel.example%2Fshop"}}, "title": {"simpleText": "Shop"}}], "secondaryLinks": [{"navigationEndpoint": {"urlEndpoint": {"url": "https://www.youtube.com/redirect?q=https%3A%2F%2Ftwitter.com%2FTeapotFan"}}, "title": {"simpleText": "Twitter"}}]}}}}, "metadata": {"channelMetadataRenderer": {"title": "Teapot Channel", "description": "Teapots, kettles and the occasional mug.", "externalId": "UCteapot0000000000000001", "vanityChannelUrl": "http://www.youtube.com/c/TeapotChannel"}}};</script> +</body></html> diff --git a/common/lib/waybackPages/extractors/gdoc.test.ts b/common/lib/waybackPages/extractors/gdoc.test.ts @@ -0,0 +1,77 @@ +// The Google Docs extractor over SYNTHETIC captures (__fixtures__/gdoc-*): +// mobilebasic, pub, and the /edit shell. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/gdoc.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { extractGdoc, gdocExtractor, googleDocId, mobilebasicUrl } from "./gdoc"; +import { captureOf, fixture } from "./__fixtures__/capture"; + +const ID = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"; +const run = (file: string, url: string) => extractGdoc({ html: fixture(file), capture: captureOf(url, "20200101000000") }); + +test("ids: /d/<id>/, the old pub?id=, and the published-to-web /d/e/<id>/", () => { + assert.deepEqual(googleDocId(new URL(`https://docs.google.com/document/d/${ID}/edit?usp=sharing`)), { id: ID }); + assert.deepEqual(googleDocId(new URL(`https://docs.google.com/document/pub?id=${ID}`)), { id: ID }); + assert.deepEqual(googleDocId(new URL("https://docs.google.com/document/d/e/2PACX-1vTeapot/pub?embedded=true")), { id: "2PACX-1vTeapot", published: true }); + assert.deepEqual(googleDocId(new URL("https://docs.google.com/document/u/0/")), {}); + assert.equal(mobilebasicUrl(ID), `https://docs.google.com/document/d/${ID}/mobilebasic`); +}); + +test("mobilebasic: the title, headings and list items as lines, links unwrapped from Google's redirector", () => { + const drafts = run("gdoc-mobilebasic.html", `https://docs.google.com/document/d/${ID}/mobilebasic`); + assert.deepEqual(drafts, [ + { + kind: "gdoc", + title: "Teapot Society Minutes", + text: [ + "Teapot Society Minutes", + "Attendance", + "Five members came. One sent apologies.", + "Decisions", + "- Buy a new kettle.", + "- Meet again in June.", + "Minutes are kept at the society site (https://teapot-society.example/minutes).", + ].join("\n"), + links: ["https://teapot-society.example/minutes"], + }, + ]); +}); + +test("pub (embedded): the document's body without Google's banner, header and footer", () => { + const [d] = run("gdoc-pub.html", "https://docs.google.com/document/d/e/2PACX-1vTeapot/pub?embedded=true"); + assert.equal(d.kind, "gdoc"); + assert.equal(d.title, "Teapot Society Minutes"); + assert.equal(d.text, "Attendance\nFive members came. One sent apologies.\nDecisions\n- Buy a new kettle.\n- Meet again in June.\n[image]"); + assert.deepEqual(d.links, []); + assert.deepEqual(d.media, [{ kind: "image", url: "https://lh3.googleusercontent.com/teapot-society-photo" }]); + assert.equal(d.noContent, undefined); + assert.ok(!/Report abuse|Updated automatically|Published using/.test(d.text)); +}); + +test("the /edit shell: noContent, the text naming the mobilebasic URL to look for", () => { + const drafts = run("gdoc-edit-shell.html", `https://docs.google.com/document/d/${ID}/edit`); + assert.deepEqual(drafts, [ + { + kind: "gdoc", + title: "Teapot Society Minutes", + text: `This capture holds only the Google Docs editor, not the document's text. Look for a capture of https://docs.google.com/document/d/${ID}/mobilebasic`, + links: [`https://docs.google.com/document/d/${ID}/mobilebasic`], + noContent: true, + }, + ]); + // A published-to-web id has no mobilebasic form to suggest. + const pub = extractGdoc({ html: fixture("gdoc-edit-shell.html"), capture: captureOf("https://docs.google.com/document/d/e/2PACX-1vTeapot/pub", "20200101000000") }); + assert.equal(pub[0].text, "This capture holds no document text."); + assert.deepEqual(pub[0].links, []); +}); + +test("matches: docs.google.com documents only", () => { + const m = (u: string) => gdocExtractor.matches(new URL(u), ""); + assert.equal(m(`https://docs.google.com/document/d/${ID}/preview`), true); + assert.equal(m(`https://docs.google.com/spreadsheets/d/${ID}/edit`), false); + assert.equal(m("https://drive.google.com/file/d/x/view"), false); + assert.equal(gdocExtractor.name, "gdoc"); + assert.equal(gdocExtractor.version, 1); +}); diff --git a/common/lib/waybackPages/extractors/gdoc.ts b/common/lib/waybackPages/extractors/gdoc.ts @@ -0,0 +1,94 @@ +// Google Docs captures (release 37 S3): a document's `mobilebasic`, `pub` +// (also `pub?embedded=true`) or `preview` capture → one `gdoc` draft: the +// document's title and its text, headings and list items kept as lines, its +// links unwrapped from Google's /url?q= redirector. An `/edit` capture holds +// only the editor's JavaScript app → one draft with `noContent: true` whose +// text names the `mobilebasic` URL to look for instead. The record is the +// whole page (no itemId): a document changes between captures, and each +// capture is a version of it. + +import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; +import { + findFirst, + hasClass, + metaContent, + pageTitle, + parseHtml, + renderBlock, + textOf, + unwrapWaybackHtml, + type HtmlElement, +} from "./util"; + +export function isGoogleDocsUrl(url: URL): boolean { + return url.hostname.toLowerCase() === "docs.google.com" && /^\/document\//.test(url.pathname); +} + +// The document's id (`/document/d/<id>/…`, the older `/document/pub?id=<id>`), +// and whether the URL is a published-to-web id (`/document/d/e/<id>/pub`), +// which has no mobilebasic form. +export function googleDocId(url: URL): { id?: string; published?: boolean } { + const pub = /^\/document\/d\/e\/([A-Za-z0-9_-]+)/.exec(url.pathname); + if (pub) return { id: pub[1], published: true }; + const d = /^\/document\/d\/([A-Za-z0-9_-]{10,})/.exec(url.pathname); + if (d) return { id: d[1] }; + const q = url.searchParams.get("id") ?? url.searchParams.get("docid"); + if (q && /^[A-Za-z0-9_-]{10,}$/.test(q)) return { id: q }; + return {}; +} + +export function mobilebasicUrl(id: string): string { + return `https://docs.google.com/document/d/${id}/mobilebasic`; +} + +const isContents = (e: HtmlElement) => + e.attrs.id === "contents" || e.attrs.id === "doc-contents" || hasClass(e, "doc-content"); + +const DROP = (e: HtmlElement) => + e.tag === "style" || e.tag === "script" || e.attrs.id === "header" || e.attrs.id === "footer" || e.attrs.id === "banners"; + +function docTitle(root: HtmlElement): string | undefined { + const own = + textOf(findFirst(root, (e) => e.attrs.id === "title" || hasClass(e, "doc-title") || e.attrs.id === "doc-title")) || + findFirst(root, (e) => e.tag === "input" && hasClass(e, "docs-title-input"))?.attrs.value?.trim() || + metaContent(root, "og:title") || + metaContent(root, "name") || + (pageTitle(root) ?? "").replace(/\s+-\s+Google (Docs|Drive)$/, ""); + return own || undefined; +} + +export function extractGdoc(input: PageExtractInput): PageRecordDraft[] { + const html = unwrapWaybackHtml(input.html); + const url = new URL(input.capture.originalUrl); + const root = parseHtml(html); + const title = docTitle(root); + const contents = findFirst(root, isContents); + const rendered = contents ? renderBlock(contents, url.href, DROP) : null; + if (rendered && rendered.text) { + const draft: PageRecordDraft = { kind: "gdoc", text: rendered.text, links: rendered.links }; + if (title) draft.title = title; + if (rendered.media.length > 0) draft.media = rendered.media; + return [draft]; + } + const { id, published } = googleDocId(url); + const look = id && !published ? mobilebasicUrl(id) : undefined; + const draft: PageRecordDraft = { + kind: "gdoc", + text: look + ? `This capture holds only the Google Docs editor, not the document's text. Look for a capture of ${look}` + : "This capture holds no document text.", + links: look ? [look] : [], + noContent: true, + }; + if (title) draft.title = title; + return [draft]; +} + +export const gdocExtractor: PageExtractor = { + name: "gdoc", + version: 1, + matches(originalUrl) { + return isGoogleDocsUrl(originalUrl); + }, + extract: extractGdoc, +}; diff --git a/common/lib/waybackPages/extractors/index.test.ts b/common/lib/waybackPages/extractors/index.test.ts @@ -0,0 +1,73 @@ +// The site-extractor registry: each synthetic capture goes to the extractor +// made for it, an unknown page to none (the generic extractor's), and every +// extractor is pure — the same input gives the same drafts, and the input is +// left as it was. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/index.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { SITE_EXTRACTORS } from "./index"; +import { PAGE_KINDS } from "../types"; +import { captureOf, fixture } from "./__fixtures__/capture"; +import { LIVE_PAGE, LOGIN_WALL, REPLAY_PAGE, THREAD_URL } from "./__fixtures__/xenforoCaptures"; + +const GDOC = "https://docs.google.com/document/d/1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789"; + +const CASES: [html: string, url: string, expected: string | null][] = [ + [fixture("tumblr-2012-classic-post.html"), "http://teapot-notes.tumblr.com/post/20000000001/on-spouts", "tumblr"], + [fixture("tumblr-2012-classic-index.html"), "http://teapot-notes.tumblr.com/", "tumblr"], + [fixture("tumblr-2014-article-index.html"), "http://blog.kettle-studio.example/page/2", "tumblr"], + [fixture("tumblr-minimal-tagged.html"), "http://quiet-kettle.tumblr.com/tagged/steam", "tumblr"], + [fixture("x-2015-profile.html"), "https://twitter.com/TeapotFan", "x"], + [fixture("x-2012-profile.html"), "https://twitter.com/kettlefriend", "x"], + [fixture("x-2016-status.html"), "https://twitter.com/TeapotFan/status/697374449464250369", "x"], + [fixture("x-mobile-profile.html"), "https://mobile.twitter.com/TeapotFan", "x"], + [fixture("x-2022-shell.html"), "https://x.com/TeapotFan", "x"], + [LIVE_PAGE, `${THREAD_URL}page-2`, "xenforo"], + [REPLAY_PAGE, `${THREAD_URL}page-2`, "xenforo"], + [LOGIN_WALL, `${THREAD_URL}page-2`, "xenforo"], + [fixture("gdoc-mobilebasic.html"), `${GDOC}/mobilebasic`, "gdoc"], + [fixture("gdoc-pub.html"), "https://docs.google.com/document/d/e/2PACX-1vTeapot/pub?embedded=true", "gdoc"], + [fixture("gdoc-edit-shell.html"), `${GDOC}/edit`, "gdoc"], + [fixture("yt-about-2013.html"), "http://www.youtube.com/user/teapotchannel/about", "yt-about"], + [fixture("yt-about-2019-polymer.html"), "https://www.youtube.com/channel/UCteapot0000000000000001/about", "yt-about"], + [fixture("yt-channel-2021.html"), "https://www.youtube.com/c/TeapotChannel", "yt-about"], + [fixture("yt-about-2024-handle.html"), "https://www.youtube.com/@TeapotChannel/about", "yt-about"], + // Pages no site extractor claims: an article, a personal site, a video page. + [`<!DOCTYPE html><html><head><title>A story</title></head><body><article><h1>A story</h1><p>Words.</p></article></body></html>`, "https://news.example/2014/05/a-story", null], + [`<html><body><h1>My homepage</h1><a href="/post/12">a post</a></body></html>`, "http://home.example/", null], + [`<html><body>video</body></html>`, "https://www.youtube.com/watch?v=AbCdEfGhIjK", null], +]; + +const pick = (html: string, url: string) => SITE_EXTRACTORS.find((e) => e.matches(new URL(url), html))?.name ?? null; + +test("the registry sends each capture to its extractor, and an unknown page to none", () => { + for (const [html, url, expected] of CASES) assert.equal(pick(html, url), expected, url); +}); + +test("the registry: five extractors, unique names, version 1, most specific first", () => { + assert.deepEqual(SITE_EXTRACTORS.map((e) => e.name), ["gdoc", "yt-about", "x", "xenforo", "tumblr"]); + for (const e of SITE_EXTRACTORS) assert.equal(e.version, 1); +}); + +test("every extractor is pure: the same drafts twice, kinds from the contract, ids unique per capture", () => { + for (const [html, url, expected] of CASES) { + if (!expected) continue; + const ex = SITE_EXTRACTORS.find((e) => e.name === expected)!; + const input = { html, capture: captureOf(url, "20200101000000") }; + const before = JSON.stringify(input); + const a = ex.extract(input); + const b = ex.extract(input); + assert.deepEqual(a, b, url); + assert.equal(JSON.stringify(input), before, url); + assert.ok(a.length > 0, url); + for (const d of a) { + assert.ok((PAGE_KINDS as readonly string[]).includes(d.kind), `${url}: ${d.kind}`); + assert.equal(typeof d.text, "string"); + assert.ok(Array.isArray(d.links)); + } + const ids = a.map((d) => d.itemId).filter(Boolean); + assert.equal(new Set(ids).size, ids.length, url); + } +}); diff --git a/common/lib/waybackPages/extractors/index.ts b/common/lib/waybackPages/extractors/index.ts @@ -3,5 +3,19 @@ // S3 adds one import + one entry per kind here; nothing else edits this list. import type { PageExtractor } from "../types"; +import { gdocExtractor } from "./gdoc"; +import { tumblrExtractor } from "./tumblr"; +import { xExtractor } from "./x"; +import { xenforoExtractor } from "./xenforo"; +import { ytAboutExtractor } from "./ytAbout"; -export const SITE_EXTRACTORS: readonly PageExtractor[] = []; +// Most specific first: the three that match by host (Google Docs, YouTube, +// X), then XenForo by its markup on any host, then Tumblr (its own host, or +// a custom domain whose markup is a Tumblr theme). +export const SITE_EXTRACTORS: readonly PageExtractor[] = [ + gdocExtractor, + ytAboutExtractor, + xExtractor, + xenforoExtractor, + tumblrExtractor, +]; diff --git a/common/lib/waybackPages/extractors/tumblr.test.ts b/common/lib/waybackPages/extractors/tumblr.test.ts @@ -0,0 +1,112 @@ +// The Tumblr extractor over SYNTHETIC theme pages (__fixtures__/tumblr-*): +// a 2012 classic theme (permalink and index), a 2014 article.post theme on a +// custom domain served through Wayback's replay, a minimal theme's tagged +// page, and a page with no post. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/tumblr.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { extractTumblr, isTumblrBlogHost, tumblrBlogName, tumblrExtractor } from "./tumblr"; +import { captureOf, fixture } from "./__fixtures__/capture"; + +const run = (file: string, url: string, ts: string) => extractTumblr({ html: fixture(file), capture: captureOf(url, ts) }); + +test("a classic theme's permalink page: one post, its own fields, none of the page around it", () => { + const drafts = run("tumblr-2012-classic-post.html", "http://teapot-notes.tumblr.com/post/20000000001/on-spouts", "20120601000000"); + assert.equal(drafts.length, 1); + const [d] = drafts; + assert.equal(d.kind, "tumblr-post"); + assert.equal(d.itemId, "tumblr-20000000001"); + assert.equal(d.url, "http://teapot-notes.tumblr.com/post/20000000001/on-spouts"); + assert.equal(d.author, "teapot-notes"); + assert.equal(d.title, "On spouts"); + assert.equal(d.publishedAt, "2012-05-03T00:00:00.000Z"); + assert.deepEqual(d.tags, ["teapots", "kitchen history"]); + // Google's redirector unwrapped; the post's own permalinks are not links. + assert.deepEqual(d.links, ["http://example.com/spouts"]); + assert.deepEqual(d.media, [{ kind: "image", url: "http://24.media.tumblr.com/tumblr_m3abc_500.jpg", name: "a brown teapot" }]); + assert.equal( + d.text, + "On spouts\nA good spout never drips.\nSee the spout survey (http://example.com/spouts) for more.\n[image]", + ); + assert.equal(d.noContent, undefined); + assert.equal(d.isRepost, undefined); +}); + +test("an index page: one draft per post, and a post on it is the SAME draft as on its permalink", () => { + const index = run("tumblr-2012-classic-index.html", "http://teapot-notes.tumblr.com/", "20120601000000"); + assert.deepEqual(index.map((d) => d.itemId), ["tumblr-20000000002", "tumblr-20000000001"]); + assert.equal(index[0].publishedAt, "2012-05-10T00:00:00.000Z"); + assert.equal(index[0].text, "On handles\nHandles should be warm to the touch."); + const [permalink] = run("tumblr-2012-classic-post.html", "http://teapot-notes.tumblr.com/post/20000000001/on-spouts", "20120601000000"); + assert.deepEqual(index[1], permalink); +}); + +test("a 2014 article.post theme on a custom domain, through Wayback's replay: three posts, a reblog, a photo", () => { + const drafts = run("tumblr-2014-article-index.html", "http://blog.kettle-studio.example/page/2", "20140405060708"); + // The toolbar's own link to another post is gone with the toolbar. + assert.deepEqual(drafts.map((d) => d.itemId), ["tumblr-40000000003", "tumblr-40000000002", "tumblr-40000000001"]); + const [text, photo, reblog] = drafts; + for (const d of drafts) assert.equal(d.author, "kettlestudio"); + assert.equal(text.title, "Three glazes"); + assert.equal(text.url, "http://blog.kettle-studio.example/post/40000000003/glazes"); + assert.equal(text.publishedAt, "2014-03-02T15:15:00.000Z"); + assert.deepEqual(text.tags, ["glaze", "kiln day"]); + assert.deepEqual(text.links, ["http://glaze-wiki.example/celadon"]); + assert.equal( + text.text, + "Three glazes\nWe tried three glazes this week:\n- celadon\n- tenmoku\n- shino\nNotes on the celadon page (http://glaze-wiki.example/celadon).", + ); + assert.equal(photo.publishedAt, "2014-02-27T08:00:00.000Z"); + assert.equal(photo.url, "http://blog.kettle-studio.example/post/40000000002"); + assert.deepEqual(photo.media, [{ kind: "image", url: "http://31.media.tumblr.com/tumblr_n1photo_1280.jpg", name: "kiln shelf" }]); + assert.equal(photo.text, "[image]\nFresh out of the kiln."); + assert.equal(reblog.isRepost, true); + assert.deepEqual(reblog.repostOf, { + platform: "webpage", + id: "tumblr-39999999999", + url: "http://clay-friends.tumblr.com/post/39999999999/wheel-tips", + author: "clay-friends", + }); + assert.equal(reblog.text, "Center the clay before you open it.\nAlways good advice."); + assert.equal(reblog.publishedAt, "2014-02-20T00:00:00.000Z"); + assert.deepEqual(reblog.tags, ["wheel"]); +}); + +test("a minimal theme with no post markup: posts found by their permalinks, dates from the theme's line", () => { + const drafts = run("tumblr-minimal-tagged.html", "http://quiet-kettle.tumblr.com/tagged/steam", "20130310000000"); + assert.deepEqual( + drafts.map((d) => [d.itemId, d.publishedAt, d.text, d.tags]), + [ + ["tumblr-30000000002", "2013-03-02T10:00:00.000Z", "Steam is just water being dramatic.", ["steam"]], + ["tumblr-30000000001", "2013-02-28T21:30:00.000Z", "The whistle is a feature.\nNot a bug.", ["steam", "whistles"]], + ], + ); + assert.equal(drafts[0].author, "quiet-kettle"); +}); + +test("a page holding no post: one whole-page tumblr-index draft with its text", () => { + const drafts = run("tumblr-about.html", "http://quiet-kettle.tumblr.com/about", "20130310000000"); + assert.equal(drafts.length, 1); + assert.equal(drafts[0].kind, "tumblr-index"); + assert.equal(drafts[0].itemId, undefined); + assert.equal(drafts[0].text, "About\nA blog about kettles, run by one person."); + assert.equal(drafts[0].noContent, undefined); + const empty = extractTumblr({ html: "<html><body></body></html>", capture: captureOf("http://quiet-kettle.tumblr.com/ask", "20130310000000") }); + assert.equal(empty[0].noContent, true); + assert.equal(empty[0].text, "This capture holds no Tumblr posts."); +}); + +test("matches: a blog host, a Tumblr theme on its own domain; not Tumblr's own hosts or other pages", () => { + const m = (url: string, html = "<html></html>") => tumblrExtractor.matches(new URL(url), html); + assert.equal(m("http://teapot-notes.tumblr.com/"), true); + assert.equal(m("https://www.tumblr.com/dashboard"), false); + assert.equal(m("https://64.media.tumblr.com/x.jpg"), false); + assert.equal(m("http://blog.kettle-studio.example/page/2", fixture("tumblr-2014-article-index.html")), true); + assert.equal(m("https://news.example/story", `<a href="https://news.example/post/123">x</a>`), false); + assert.equal(isTumblrBlogHost("STAFF.tumblr.com"), true); + assert.equal(tumblrBlogName("staff.tumblr.com"), "staff"); + assert.equal(tumblrExtractor.name, "tumblr"); + assert.equal(tumblrExtractor.version, 1); +}); diff --git a/common/lib/waybackPages/extractors/tumblr.ts b/common/lib/waybackPages/extractors/tumblr.ts @@ -0,0 +1,329 @@ +// 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-<postId>"`, 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/<id>` 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-<id>"`, `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, PostPlatform } 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"; + +// Lane A registers "webpage" as a PostPlatform; a reblog points at another +// page record, so its ref is on that platform. +const WEBPAGE = "webpage" as PostPlatform; + +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, + /<meta[^>]+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<HtmlElement, { id: string; url: string }>(); + 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<HtmlElement, Set<string>>(); + const collect = (el: HtmlElement): Set<string> => { + const s = new Set<string>(); + 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<string>(); + 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<HtmlElement, HtmlElement>): 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<HtmlElement, HtmlElement>): 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, +}; diff --git a/common/lib/waybackPages/extractors/util.ts b/common/lib/waybackPages/extractors/util.ts @@ -0,0 +1,270 @@ +// 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<HtmlElement, HtmlElement> { + const parents = new Map<HtmlElement, HtmlElement>(); + 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/<ts>/<orig>`) +// 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/ +// <ts>[mod_]/<original>` turned back into `<original>`. A raw (`id_`) body has +// neither and passes through unchanged. +export function unwrapWaybackHtml(html: string): string { + return html + .replace(/<!--\s*BEGIN WAYBACK TOOLBAR INSERT\s*-->[\s\S]*?<!--\s*END WAYBACK TOOLBAR INSERT\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<T>(arr: T[], v: T | undefined): void { + if (v !== undefined && v !== "" && !arr.includes(v)) arr.push(v); +} diff --git a/common/lib/waybackPages/extractors/x.test.ts b/common/lib/waybackPages/extractors/x.test.ts @@ -0,0 +1,211 @@ +// The X / Twitter extractor over SYNTHETIC captures (__fixtures__/x-*): the +// 2012 and 2015 desktop profile layouts, a 2016 status page with its +// conversation, the legacy mobile site, the 2022 JavaScript shell and a +// suspended account's notice. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/x.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { extractX, parseXUrl, snowflakeIso, statusUrl, xExtractor } from "./x"; +import { captureOf, fixture } from "./__fixtures__/capture"; + +const run = (file: string, url: string, ts: string) => extractX({ html: fixture(file), capture: captureOf(url, ts) }); + +test("URLs: profile, status and the i/ forms; X's own pages are not handles", () => { + assert.deepEqual(parseXUrl(new URL("https://twitter.com/TeapotFan")), { handle: "TeapotFan" }); + assert.deepEqual(parseXUrl(new URL("https://twitter.com/TeapotFan/with_replies")), { handle: "TeapotFan" }); + assert.deepEqual(parseXUrl(new URL("https://mobile.twitter.com/TeapotFan/status/123456789012345678")), { handle: "TeapotFan", statusId: "123456789012345678" }); + assert.deepEqual(parseXUrl(new URL("https://twitter.com/TeapotFan/statuses/123")), { handle: "TeapotFan", statusId: "123" }); + assert.deepEqual(parseXUrl(new URL("https://x.com/i/web/status/123")), { statusId: "123" }); + assert.deepEqual(parseXUrl(new URL("https://twitter.com/search?q=tea")), {}); + assert.deepEqual(parseXUrl(new URL("https://twitter.com/")), {}); + assert.equal(statusUrl("a", "1"), "https://twitter.com/a/status/1"); + assert.equal(statusUrl(undefined, "1"), "https://twitter.com/i/status/1"); +}); + +test("a status id's own time (snowflake); none before snowflakes", () => { + assert.equal(snowflakeIso("606838887674810369"), "2015-06-05T15:04:00.000Z"); + assert.equal(snowflakeIso("1038715922543546369"), "2018-09-09T09:09:09.000Z"); + assert.equal(snowflakeIso("20"), undefined); + assert.equal(snowflakeIso("12345678901234"), undefined); +}); + +test("a 2015 profile: the header, then one tweet per tweet — pinned repeat once, reply, retweet, quote", () => { + const drafts = run("x-2015-profile.html", "https://twitter.com/TeapotFan", "20150606000000"); + assert.deepEqual(drafts.map((d) => d.itemId), [ + "x-profile-teapotfan-20150606000000", + "tweet-606838887674810369", + "tweet-606384896209850369", + "tweet-606163436958650369", + "tweet-604605924111290369", + ]); + const [profile, plain, reply, retweet, quote] = drafts; + + assert.equal(profile.kind, "x-profile"); + assert.equal(profile.url, "https://twitter.com/TeapotFan"); + assert.equal(profile.author, "TeapotFan"); + assert.equal(profile.authorName, "Teapot Fan"); + assert.equal(profile.publishedAt, undefined); + assert.equal( + profile.text, + [ + "Teapot Fan (@TeapotFan)", + "I collect teapots. Kettles too, ask @kettlefriend. More at https://teapots.example", + "Location: Leeds", + "Website: https://teapots.example", + "Joined 2009-06-05", + "Tweets: 1,234 · Following: 56 · Followers: 7,890 · Likes: 12", + ].join("\n"), + ); + assert.deepEqual(profile.links, ["https://teapots.example"]); + + assert.equal(plain.kind, "tweet"); + assert.equal(plain.url, "https://twitter.com/TeapotFan/status/606838887674810369"); + assert.equal(plain.author, "TeapotFan"); + assert.equal(plain.authorName, "Teapot Fan"); + assert.equal(plain.publishedAt, "2015-06-05T15:04:00.000Z"); + // The emoji as its character, a mention and a hashtag as text, the t.co + // link expanded, the pic.twitter.com tail dropped. + assert.equal(plain.text, "Brewing the first pot of the day ☕ with @kettlefriend #tea https://example.com/brew"); + assert.deepEqual(plain.links, ["https://example.com/brew"]); + assert.deepEqual(plain.media, [{ kind: "image", url: "https://pbs.twimg.com/media/CGteapotA.jpg" }]); + assert.equal(plain.isReply, false); + assert.equal(plain.isRepost, false); + + assert.equal(reply.isReply, true); + assert.deepEqual(reply.replyTo, { platform: "twitter", id: "186422658462650369", url: "https://twitter.com/i/status/186422658462650369" }); + assert.equal(reply.text, "Agreed, a warm pot matters.\nAlways warm it first."); + + // A retweet is the retweet's own status, by the timeline's owner, at the + // retweet's time, pointing at the original. + assert.equal(retweet.author, "TeapotFan"); + assert.equal(retweet.url, "https://twitter.com/TeapotFan/status/606163436958650369"); + assert.equal(retweet.publishedAt, "2015-06-03T18:20:00.000Z"); + assert.equal(retweet.isRepost, true); + assert.equal(retweet.isReply, false); + assert.deepEqual(retweet.repostOf, { + platform: "twitter", + id: "605267533624250369", + url: "https://twitter.com/kettlefriend/status/605267533624250369", + author: "kettlefriend", + }); + assert.equal(retweet.text, "Descaling day. Vinegar works."); + + assert.deepEqual(quote.quoted, { + platform: "twitter", + id: "186732198097850369", + url: "https://twitter.com/kettlefriend/status/186732198097850369", + author: "kettlefriend", + }); + assert.equal(quote.text, "Still true three years later"); + assert.deepEqual(quote.links, []); +}); + +test("a 2012 profile: the old header and timeline", () => { + const drafts = run("x-2012-profile.html", "https://twitter.com/kettlefriend", "20120403000000"); + assert.deepEqual( + drafts.map((d) => [d.kind, d.itemId, d.publishedAt ?? null]), + [ + ["x-profile", "x-profile-kettlefriend-20120403000000", null], + ["tweet", "tweet-186732198097850369", "2012-04-02T08:30:00.000Z"], + ["tweet", "tweet-186422658462650369", "2012-04-01T12:00:00.000Z"], + ], + ); + assert.equal( + drafts[0].text, + "Kettle Friend (@kettlefriend)\nBoiling water since 2009.\nLocation: Kettlewell\nWebsite: http://kettle.example\nTweets: 2,001 · Following: 150 · Followers: 3,456", + ); + assert.equal(drafts[1].text, "Water boils at 100 degrees. Mostly. http://physics.example/boiling"); + assert.deepEqual(drafts[1].links, ["http://physics.example/boiling"]); + assert.equal(drafts[2].text, "No jokes today, only #tea."); + assert.equal(drafts[2].authorName, "Kettle Friend"); +}); + +test("a status page: the tweet and its conversation, each answering the one it replies to", () => { + const drafts = run("x-2016-status.html", "https://twitter.com/TeapotFan/status/697374449464250369", "20160211000000"); + assert.ok(drafts.every((d) => d.kind === "tweet")); + assert.deepEqual( + drafts.map((d) => [d.itemId, d.author, d.replyTo?.id ?? null, d.isReply]), + [ + ["tweet-697359349969850369", "kettlefriend", null, false], + ["tweet-697360608261050369", "TeapotFan", "697359349969850369", true], + ["tweet-697364383134650369", "kettlefriend", "697360608261050369", true], + ["tweet-697374449464250369", "TeapotFan", "697364383134650369", true], + // A threaded group: the first answers the page's tweet, the next the first. + ["tweet-697381999211450369", "kettlefriend", "697374449464250369", true], + ["tweet-697389548958650369", "TeapotFan", "697381999211450369", true], + ["tweet-697381999211450370", "mugperson", "697374449464250369", true], + ], + ); + const main = drafts[3]; + // The permalink tweet's time is its printed line (no _timestamp on it). + assert.equal(main.publishedAt, "2016-02-10T11:00:00.000Z"); + assert.equal(main.text, "Brown hides the tea stains."); + assert.equal(main.authorName, "Teapot Fan"); + assert.deepEqual(main.replyTo, { + platform: "twitter", + id: "697364383134650369", + url: "https://twitter.com/kettlefriend/status/697364383134650369", + author: "kettlefriend", + }); +}); + +test("the legacy mobile layout: header, tweets timed by their ids, links from data-url", () => { + const drafts = run("x-mobile-profile.html", "https://mobile.twitter.com/TeapotFan", "20180910000000"); + assert.deepEqual(drafts.map((d) => d.itemId), [ + "x-profile-teapotfan-20180910000000", + "tweet-1038715922543546369", + "tweet-1038517326443450369", + ]); + assert.equal( + drafts[0].text, + "Teapot Fan (@TeapotFan)\nI collect teapots.\nLocation: Leeds\nWebsite: https://teapots.example\nTweets: 1,500 · Following: 60 · Followers: 8,001", + ); + const [, shelf, reply] = drafts; + assert.equal(shelf.publishedAt, "2018-09-09T09:09:09.000Z"); + assert.equal(shelf.text, "New shelf for the collection https://shelves.example/oak"); + assert.deepEqual(shelf.links, ["https://shelves.example/oak"]); + assert.deepEqual(shelf.media, [{ kind: "image", url: "https://pbs.twimg.com/media/DmShelf.jpg" }]); + assert.equal(shelf.url, "https://twitter.com/TeapotFan/status/1038715922543546369"); + assert.equal(reply.text, "@kettlefriend Oak, not pine."); + assert.equal(reply.isReply, true); + assert.equal(reply.publishedAt, "2018-09-08T20:00:00.000Z"); +}); + +test("the JavaScript app's shell: one noContent draft, no item id, profile or status by the URL", () => { + const profile = run("x-2022-shell.html", "https://twitter.com/TeapotFan", "20221101000000"); + assert.deepEqual(profile, [ + { + kind: "x-profile", + text: "This capture holds no posts: it is X's JavaScript app, and the capture did not keep any posts.", + links: [], + noContent: true, + author: "TeapotFan", + }, + ]); + const status = run("x-2022-shell.html", "https://twitter.com/TeapotFan/status/1038715922543546369", "20221101000000"); + assert.equal(status.length, 1); + assert.equal(status[0].kind, "tweet"); + assert.equal(status[0].itemId, undefined); + assert.equal(status[0].noContent, true); + assert.equal(status[0].text, "This capture holds no posts: it is X's JavaScript app, and the capture did not keep this tweet."); +}); + +test("a notice page: no posts, the notice quoted", () => { + const drafts = run("x-suspended.html", "https://twitter.com/GoneAccount", "20170101000000"); + assert.equal(drafts.length, 1); + assert.equal(drafts[0].kind, "x-profile"); + assert.equal(drafts[0].noContent, true); + assert.equal(drafts[0].text, 'This capture holds no posts. The page says: "Account suspended".'); +}); + +test("matches: twitter.com, mobile.twitter.com and x.com only", () => { + const m = (u: string) => xExtractor.matches(new URL(u), ""); + assert.equal(m("https://twitter.com/TeapotFan"), true); + assert.equal(m("http://mobile.twitter.com/TeapotFan"), true); + assert.equal(m("https://x.com/TeapotFan"), true); + assert.equal(m("https://nottwitter.com/TeapotFan"), false); + assert.equal(xExtractor.name, "x"); + assert.equal(xExtractor.version, 1); +}); diff --git a/common/lib/waybackPages/extractors/x.ts b/common/lib/waybackPages/extractors/x.ts @@ -0,0 +1,521 @@ +// 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-<statusId>"`, 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<RawTweet, PostRef>(); + 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<HtmlElement, RawTweet>(); + 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<string>(); + 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, +}; diff --git a/common/lib/waybackPages/extractors/xenforo.test.ts b/common/lib/waybackPages/extractors/xenforo.test.ts @@ -0,0 +1,76 @@ +// The XenForo extractor over SYNTHETIC captures (__fixtures__/xenforoCaptures.ts, +// built on the forum parser's own synthetic thread page): a capture's posts +// are the posts a live forum channel stores for the same page — same ids, +// same `forum`, same text — and a captured wall is accounted for. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/xenforo.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { parseXenforoThreadPage } from "../../../social/xenforoParse"; +import { extractXenforo, xenforoExtractor } from "./xenforo"; +import { captureOf } from "./__fixtures__/capture"; +import { CAPTURE_TS, LIVE_PAGE, LOGIN_WALL, REPLAY_PAGE, THREAD_URL } from "./__fixtures__/xenforoCaptures"; + +const PAGE_URL = `${THREAD_URL}page-2`; + +test("a replayed capture's posts line up with the live channel's posts of the same page", () => { + const live = parseXenforoThreadPage(LIVE_PAGE, { channelSlug: "teapots", pageUrl: PAGE_URL }).posts; + const drafts = extractXenforo({ html: REPLAY_PAGE, capture: captureOf(PAGE_URL, CAPTURE_TS) }); + assert.deepEqual(drafts.map((d) => d.itemId), ["1001", "1002", "1003"]); + assert.deepEqual(drafts.map((d) => d.itemId), live.map((p) => p.id)); + drafts.forEach((d, i) => { + const p = live[i]; + assert.equal(d.kind, "forum-post"); + assert.equal(d.url, p.url); + assert.equal(d.author, p.author); + assert.equal(d.publishedAt, p.createdAt); + assert.equal(d.text, p.text); + assert.deepEqual(d.links, p.links); + assert.deepEqual(d.media, p.media); + assert.deepEqual(d.forum, p.forum); + assert.deepEqual(d.replyTo, p.replyTo); + assert.deepEqual(d.quoted, p.quoted); + assert.equal(d.isReply, p.isReply); + assert.equal(d.title, "The Teapot Collectors Thread"); + }); + assert.equal(drafts[0].publishedAt, "2023-11-14T22:13:20.000Z"); + assert.equal(drafts[0].text, "The blue one is a reproduction.\nLook at the glaze."); + assert.deepEqual(drafts[0].forum, { + host: "forum.example", + threadId: "4242", + page: 2, + threadTitle: "The Teapot Collectors Thread", + threadUrl: THREAD_URL, + position: 21, + authorId: "7", + }); + // A quote is a reply ref to the quoted post, on the forum's platform. + assert.deepEqual(drafts[1].quoted, { platform: "xenforo", id: "1001", url: "https://forum.example/posts/1001/", author: "Marigold" }); + // No URL in a draft points back into the Wayback Machine. + const urls = drafts.flatMap((d) => [d.url ?? "", ...d.links, ...(d.media ?? []).map((m) => m.url)]); + assert.ok(urls.every((u) => !u.includes("web.archive.org")), urls.join(" ")); +}); + +test("a captured login wall: one whole-page noContent draft saying so", () => { + const drafts = extractXenforo({ html: LOGIN_WALL, capture: captureOf(PAGE_URL, CAPTURE_TS) }); + assert.deepEqual(drafts, [ + { + kind: "generic", + text: "This capture holds no forum posts. The forum asked for a login.", + links: [], + noContent: true, + title: "Log in | Example Forum", + }, + ]); +}); + +test("matches: XenForo's markup on any host, nothing else", () => { + const m = (html: string) => xenforoExtractor.matches(new URL("https://forum.example/threads/x.1/"), html); + assert.equal(m(LIVE_PAGE), true); + assert.equal(m(REPLAY_PAGE), true); + assert.equal(m(LOGIN_WALL), true); + assert.equal(m("<html><body><article class=\"post\">x</article></body></html>"), false); + assert.equal(xenforoExtractor.name, "xenforo"); + assert.equal(xenforoExtractor.version, 1); +}); diff --git a/common/lib/waybackPages/extractors/xenforo.ts b/common/lib/waybackPages/extractors/xenforo.ts @@ -0,0 +1,71 @@ +// XenForo captures (release 37 S3): a captured thread page → one +// `forum-post` draft per post, read by THE forum parser +// (social/xenforoParse.ts `parseXenforoThreadPage`, not a fork of it). The +// item id is the bare post id — the id a live forum channel stores for the +// same post (xenforoFetcher.ts hands the parser's posts straight to the +// store) — and `forum` is the parser's own, so a capture's posts and a live +// channel's posts of the same thread line up. A captured page that stands in +// the thread's way (a login wall, a browser check, "not found") → one +// whole-page draft with `noContent: true` saying which. + +import { classifyForumPage, parseXenforoThreadPage } from "../../../social/xenforoParse"; +import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types"; +import { unwrapWaybackHtml, unwrapWaybackUrl } from "./util"; + +const XF_MARKERS = [/data-template=["']?thread_view/i, /<html[^>]*\bid=["']?XF\b/i, /class=["'][^"']*\bmessage--post\b/i]; + +export function extractXenforo(input: PageExtractInput): PageRecordDraft[] { + const html = unwrapWaybackHtml(input.html); + const page = parseXenforoThreadPage(html, { channelSlug: "page", pageUrl: input.capture.originalUrl }); + const drafts: PageRecordDraft[] = []; + for (const p of page.posts) { + const draft: PageRecordDraft = { + kind: "forum-post", + itemId: p.id, + url: p.url, + author: p.author, + publishedAt: p.createdAt, + text: p.text, + links: p.links.map(unwrapWaybackUrl), + isReply: p.isReply, + isRepost: p.isRepost, + }; + if (page.threadTitle) draft.title = page.threadTitle; + if (p.authorName) draft.authorName = p.authorName; + if (p.media) draft.media = p.media.map((m) => ({ ...m, url: unwrapWaybackUrl(m.url) })); + if (p.replyTo) draft.replyTo = p.replyTo; + if (p.quoted) draft.quoted = p.quoted; + if (p.forum) draft.forum = p.forum; + drafts.push(draft); + } + if (drafts.length > 0) return drafts; + + const block = classifyForumPage(html, input.capture.status); + const WHY: Record<string, string> = { + login: " The forum asked for a login.", + challenge: " It is a browser check, not the thread.", + captcha: " It is a captcha page, not the thread.", + blocked: " The forum refused the request.", + "not-found": " The forum said the thread could not be found.", + }; + const what = (block && WHY[block.kind]) ?? ""; + const draft: PageRecordDraft = { + kind: "generic", + text: `This capture holds no forum posts.${what}`, + links: [], + noContent: true, + }; + // A wall's own title ("Log in | Example Forum"); a thread page's when no wall. + const title = block?.title ?? page.threadTitle; + if (title) draft.title = title; + return [draft]; +} + +export const xenforoExtractor: PageExtractor = { + name: "xenforo", + version: 1, + matches(_originalUrl, html) { + return XF_MARKERS.some((re) => re.test(html)); + }, + extract: extractXenforo, +}; diff --git a/common/lib/waybackPages/extractors/ytAbout.test.ts b/common/lib/waybackPages/extractors/ytAbout.test.ts @@ -0,0 +1,122 @@ +// The YouTube About extractor over SYNTHETIC captures (__fixtures__/yt-*): +// the 2013 server-rendered About page, a 2019 Polymer About tab, a 2021 +// bare channel page and a 2024 @handle About capture whose ytInitialData is +// an escaped string. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/waybackPages/extractors/ytAbout.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { extractYtAbout, jsonAfter, youtubeChannelOf, ytAboutExtractor } from "./ytAbout"; +import { captureOf, fixture } from "./__fixtures__/capture"; + +const CID = "UCteapot0000000000000001"; +const run = (file: string, url: string, ts: string) => extractYtAbout({ html: fixture(file), capture: captureOf(url, ts) }); + +test("channel URLs: /user, /c, /channel, /@handle, a custom name's /about; not a watch page", () => { + const c = (u: string) => youtubeChannelOf(new URL(u)); + assert.equal(c("http://www.youtube.com/user/teapotchannel/about"), "teapotchannel"); + assert.equal(c("https://www.youtube.com/c/TeapotChannel"), "TeapotChannel"); + assert.equal(c(`https://www.youtube.com/channel/${CID}/about`), CID); + assert.equal(c("https://www.youtube.com/@TeapotChannel/about"), "@TeapotChannel"); + assert.equal(c("https://www.youtube.com/@TeapotChannel"), "@TeapotChannel"); + assert.equal(c("https://www.youtube.com/teapotchannel/about"), "teapotchannel"); + assert.equal(c("https://m.youtube.com/user/teapotchannel/featured"), "teapotchannel"); + assert.equal(c("https://www.youtube.com/watch?v=AbCdEfGhIjK"), null); + assert.equal(c("https://www.youtube.com/user/teapotchannel/videos"), null); + assert.equal(c("https://www.youtube.com/results/about"), null); + assert.equal(c("https://example.com/user/x/about"), null); +}); + +test("jsonAfter: brace-matched past braces inside strings; an escaped string literal; garbage is null", () => { + assert.deepEqual(jsonAfter(`<script>var ytInitialData = {"a":"}{","b":{"c":1}};var x = {};</script>`, /ytInitialData\s*=\s*/), { a: "}{", b: { c: 1 } }); + assert.deepEqual(jsonAfter(`ytInitialData = '\\x7b\\x22a\\x22:1\\x7d';`, /ytInitialData\s*=\s*/), { a: 1 }); + assert.equal(jsonAfter(`ytInitialData = {"a": nope};`, /ytInitialData\s*=\s*/), null); + assert.equal(jsonAfter(`nothing here`, /ytInitialData\s*=\s*/), null); +}); + +test("the 2013 About page: description, links, joined, counts, country", () => { + const drafts = run("yt-about-2013.html", "http://www.youtube.com/user/teapotchannel/about", "20131001000000"); + assert.deepEqual(drafts, [ + { + kind: "yt-about", + itemId: `yt-about-${CID}-20131001000000`, + author: "teapotchannel", + authorName: "Teapot Channel", + title: "Teapot Channel", + text: [ + "Teapot Channel", + "Videos about teapots, every Sunday.", + "Business enquiries through the website.", + "Twitter: https://twitter.com/TeapotFan", + "Website: http://www.teapot-channel.example/", + "Joined Jan 5, 2010", + "12,345 subscribers", + "1,234,567 views", + "Country: United Kingdom", + ].join("\n"), + links: ["https://twitter.com/TeapotFan", "http://www.teapot-channel.example/"], + }, + ]); +}); + +test("a 2019 Polymer About tab: read from ytInitialData", () => { + const [d] = run("yt-about-2019-polymer.html", `https://www.youtube.com/channel/${CID}/about`, "20190101000000"); + assert.equal(d.itemId, `yt-about-${CID}-20190101000000`); + assert.equal(d.author, "TeapotChannel"); + assert.equal(d.title, "Teapot Channel"); + assert.equal( + d.text, + [ + "Teapot Channel", + "Videos about teapots {and lids}, every Sunday.", + "Now with kettles.", + "Twitter: https://twitter.com/TeapotFan", + "Website: https://www.teapot-channel.example/", + "Joined Jan 5, 2010", + "45K subscribers", + "2,345,678 views", + "Country: United Kingdom", + ].join("\n"), + ); + assert.deepEqual(d.links, ["https://twitter.com/TeapotFan", "https://www.teapot-channel.example/"]); + assert.equal(d.noContent, undefined); +}); + +test("a 2021 bare channel page: the metadata's description and the header's links", () => { + const [d] = run("yt-channel-2021.html", "https://www.youtube.com/c/TeapotChannel", "20210101000000"); + assert.equal(d.itemId, `yt-about-${CID}-20210101000000`); + assert.equal( + d.text, + "Teapot Channel\nTeapots, kettles and the occasional mug.\nShop: https://www.teapot-channel.example/shop\nTwitter: https://twitter.com/TeapotFan\n61.2K subscribers", + ); + assert.deepEqual(d.links, ["https://www.teapot-channel.example/shop", "https://twitter.com/TeapotFan"]); +}); + +test("a 2024 @handle About capture: the view model, from an escaped-string ytInitialData", () => { + const [d] = run("yt-about-2024-handle.html", "https://www.youtube.com/@TeapotChannel/about", "20240101000000"); + assert.equal(d.itemId, `yt-about-${CID}-20240101000000`); + assert.equal(d.author, "@TeapotChannel"); + assert.equal(d.authorName, "Teapot Channel"); + assert.equal( + d.text, + "Teapot Channel\nTeapots, kettles and the occasional mug.\nSince 2010.\nWebsite: https://teapot-channel.example/\nJoined Jan 5, 2010\n80.1K subscribers\n3,456,789 views\nCountry: United Kingdom", + ); +}); + +test("two captures of one channel are two records; a page with nothing on it is noContent", () => { + const a = run("yt-about-2019-polymer.html", `https://www.youtube.com/channel/${CID}/about`, "20190101000000")[0]; + const b = run("yt-about-2024-handle.html", "https://www.youtube.com/@TeapotChannel/about", "20240101000000")[0]; + assert.notEqual(a.itemId, b.itemId); + const empty = extractYtAbout({ html: "<html><body></body></html>", capture: captureOf("https://www.youtube.com/@Gone/about", "20250101000000") }); + assert.deepEqual(empty, [ + { kind: "yt-about", itemId: "yt-about-@Gone-20250101000000", author: "@Gone", text: "This capture holds no channel description.", links: [], noContent: true }, + ]); +}); + +test("matches: channel pages only", () => { + assert.equal(ytAboutExtractor.matches(new URL("https://www.youtube.com/@TeapotChannel/about"), ""), true); + assert.equal(ytAboutExtractor.matches(new URL("https://www.youtube.com/watch?v=AbCdEfGhIjK"), ""), false); + assert.equal(ytAboutExtractor.name, "yt-about"); + assert.equal(ytAboutExtractor.version, 1); +}); diff --git a/common/lib/waybackPages/extractors/ytAbout.ts b/common/lib/waybackPages/extractors/ytAbout.ts @@ -0,0 +1,319 @@ +// 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>-<captureTs>"` (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/<name>/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<string, unknown>; +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]|&bull;|&middot;)+/, ""); + 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, +};