Add Reddit with its comment threads, and show quoted posts whole
CI / Typecheck, test, build (pull_request) Successful in 9s
CI / Typecheck, test, build (pull_request) Successful in 9s
Two changes. They share the `Segment` model, which is why they arrive
together.
## Reddit
A new adapter under /reddit, plus the thread beneath the post -- on Reddit the
conversation is usually the reason the link was shared, so a viewer that showed
only the post would be showing the wrong half.
The `.json` twin of a post URL is the post and the whole first page of comments
in one response, far better than anything the page gives up, so it is the only
layer that normally runs. Reddit refuses it to a browser it has never seen and
answers with a JavaScript challenge, which any ordinary navigation solves by
itself; the adapter navigates once and retries, and the cookie left behind
serves every later post. Below that, `shreddit-comment` elements are read from
the rendered page -- flat, each carrying its own `depth`, so `treeFromDepths`
rebuilds the nesting.
`Post.comments` is a tree rather than a flat list with depths, because folding
a comment has to take everything under it along and nesting is what makes that
free. Each comment renders as a `<details open>`, so collapsing works with the
stylesheet off and from the keyboard, and a collapsed one says how many replies
it is hiding. "Collapse all" is the only part that needs the script, so it
ships hidden and appears once the script has run. What sits behind a "load
more" is not fetched -- that is a second page and often a third -- but it is
counted and said out loud rather than quietly dropped.
Four things the payloads got wrong on the first try, each now with a fixture:
`fallback_url` is the video track alone whenever `has_audio` is true, so a post
with sound has to use `hls_url` and only a silent one gets the proxied MP4;
`scrubber_media_url` looks like a poster and is a second MP4 for the timeline
thumbnails, while the still is in `preview.images`; a gallery's pictures live
in `media_metadata` keyed and unordered, with their order only in
`gallery_data`; and `replies` is the string "" rather than an object when there
are none. Comment bodies are Markdown, rendered by a new render/markdown.ts
that escapes first and then puts back only the constructs we chose to support
-- never Reddit's own `body_html`, which would mean trusting markup a stranger
caused to be generated.
An app share link (/r/<sub>/s/<code>) is a plain 301, so one request told not
to follow it is enough. The permalink it resolves to is what the copy button
hands back, since an opaque share code is a tracking parameter by another name.
## Quoted posts
Both X and Bluesky lifted the quoted post's media out and showed it as the
quoter's own, dropping the quoted words and the quoted author entirely. A quote
of a photo post therefore rendered as somebody else's picture under the wrong
name with nothing to say so, and a quote that had a picture of its own dropped
the quoted one instead -- the two could never both appear. Half the quote posts
people share are someone answering a stranger and the other half are someone
continuing a thought from an earlier post; neither reads with only one side of
it on the page.
`Segment.quoted` now carries the whole thing -- author, words, pictures, time
and a link to it -- and renders as a post inside the post. Neither payload
carries a usable address for it: X has no permalink and it is rebuilt from the
handle and `id_str`, Bluesky has an `at://` URI nobody can open and it is
rebuilt from the handle and the record key. On Bluesky the record sits at
`embed.record` for a plain quote and at `embed.record.record` when the quoting
post has media of its own, and a quote can also point at a feed, a list or a
post since deleted, which arrive in the same slot under a different `$type` --
only `app.bsky.embed.record#viewRecord` is taken.
Two things about X's text, both visible on any post and not only a quote. It
arrives pre-escaped, so an ampersand someone typed was reaching the page as the
literal `&`; it is decoded in the adapter, where the encoding comes from,
leaving the escape-on-the-way-out rule alone. And every link is a `t.co`, which
tells the reader nothing and routes them through X's click tracker to find out
-- `entities.urls` carries the real address alongside, so it is put back. The
shortlink X staples onto the end of a quote post is dropped rather than
expanded, since the post it points at is already on the page;
`display_text_range` is where that boundary is and it keeps a link the author
put there deliberately. Its indices are UTF-16 units into the escaped text, so
the slice happens before decoding and before expanding, and splitting to
codepoints first overshoots past an emoji -- checked against a post carrying
one.
A quote is context, and context that fills the screen has stopped being
context, so a segment carrying one gives up the window-filling cap on its own
media.
## Along the way
setupMedia only ever wired `document.querySelector('.media')`, the first rail
on the page. That was already wrong for a Bluesky or Threads chain with media
in more than one post, and a quoted carousel would have hit it too. It now runs
per rail.
## Verified
108 tests, typecheck and build clean. Resolved end to end against the live
platforms: Reddit self, gallery, video, link and share-link posts; X quotes
with no media, with media on the quoted side, and with media on both; Bluesky
quotes in both embed shapes, including a ten-post chain where every post quotes
a different account and all nine quotes come back under the right name.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017nMQ2eDKnqALYhAibpTKTu
This commit is contained in:
+119
-17
@@ -1,5 +1,5 @@
|
||||
import { config } from '../config.ts';
|
||||
import { ResolveError, oneSegment, type Media, type Post } from '../types.ts';
|
||||
import { ResolveError, oneSegment, type Author, type Media, type Post, type Quoted } from '../types.ts';
|
||||
import { captureJson } from '../browser/capture.ts';
|
||||
import { hostMatcher } from './url.ts';
|
||||
import type { PlatformSpec, ResolveContext } from './types.ts';
|
||||
@@ -16,15 +16,89 @@ type MediaDetail = {
|
||||
video_info?: { duration_millis?: number; variants?: VideoVariant[] };
|
||||
};
|
||||
|
||||
type TweetUser = { screen_name?: string; name?: string; profile_image_url_https?: string };
|
||||
|
||||
type TweetResult = {
|
||||
id_str?: string;
|
||||
text?: string;
|
||||
/** Which slice of `text` X itself shows. UTF-16 indices. */
|
||||
display_text_range?: [number, number];
|
||||
entities?: { urls?: Array<{ url?: string; expanded_url?: string }> };
|
||||
created_at?: string;
|
||||
user?: { screen_name?: string; name?: string; profile_image_url_https?: string };
|
||||
user?: TweetUser;
|
||||
mediaDetails?: MediaDetail[];
|
||||
quoted_tweet?: TweetResult;
|
||||
tombstone?: unknown;
|
||||
};
|
||||
|
||||
/**
|
||||
* X hands back post text with the markup-significant characters already
|
||||
* escaped — an ampersand someone typed arrives as `&`. Everything
|
||||
* downstream escapes on the way out, so leaving them would put the entity
|
||||
* itself on screen.
|
||||
*/
|
||||
const ENTITIES: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
''': "'",
|
||||
};
|
||||
|
||||
function decodeEntities(text: string): string {
|
||||
// `&` last would double-decode `&lt;`; one pass over the lot cannot.
|
||||
return text.replace(/&(?:amp|lt|gt|quot|#39);/g, (entity) => ENTITIES[entity] ?? entity);
|
||||
}
|
||||
|
||||
const SHORTLINK = /https?:\/\/t\.co\/[A-Za-z0-9]+/g;
|
||||
|
||||
/**
|
||||
* Put back the addresses `t.co` stands in for.
|
||||
*
|
||||
* Every link in a post is rewritten to a shortlink before it is stored, so
|
||||
* left alone the page shows `t.co/QdJhOVu4En` — which says nothing about
|
||||
* where it goes, and routes the reader through X's click tracker to find
|
||||
* out. The payload carries the real address alongside, so there is no reason
|
||||
* to show the stand-in.
|
||||
*
|
||||
* Matched on the shortlink itself rather than by `indices`, which are offsets
|
||||
* into a string this function is in the middle of changing the length of.
|
||||
*/
|
||||
function expandShortlinks(text: string, result: TweetResult): string {
|
||||
const expansions = new Map<string, string>();
|
||||
for (const entity of result.entities?.urls ?? []) {
|
||||
if (!entity.url || !entity.expanded_url) continue;
|
||||
if (!/^https?:\/\//.test(entity.expanded_url)) continue;
|
||||
expansions.set(entity.url, entity.expanded_url);
|
||||
}
|
||||
if (expansions.size === 0) return text;
|
||||
return text.replace(SHORTLINK, (link) => expansions.get(link) ?? link);
|
||||
}
|
||||
|
||||
/**
|
||||
* The words of the post, as X itself would show them.
|
||||
*
|
||||
* A quote post gets a `t.co` link to the post it quotes stapled to the end of
|
||||
* its text, and X hides it — the quoted post is on the page, so a shortlink
|
||||
* to it is noise. `display_text_range` is where that boundary is, and it also
|
||||
* keeps a link the author put there on purpose, which is why the range is
|
||||
* used rather than stripping trailing URLs.
|
||||
*
|
||||
* Sliced before decoding: the indices are into the escaped text, where an
|
||||
* ampersand is five characters. They are UTF-16 units, so a plain `slice` is
|
||||
* right and splitting to codepoints first would overshoot past an emoji.
|
||||
*/
|
||||
function visibleText(result: TweetResult): string | undefined {
|
||||
const raw = result.text;
|
||||
if (!raw) return undefined;
|
||||
const range = result.display_text_range;
|
||||
const shown = Array.isArray(range) ? raw.slice(range[0], range[1]) : raw;
|
||||
// Expanded after the slice for the same reason: the range is measured
|
||||
// against the text as it arrived.
|
||||
const text = expandShortlinks(decodeEntities(shown), result).trimEnd();
|
||||
return text || undefined;
|
||||
}
|
||||
|
||||
/** Every X post URL ends in `/status/<id>`, whatever precedes it. */
|
||||
function tweetId(pathRest: string): string | undefined {
|
||||
return /\/status(?:es)?\/(\d+)/.exec(`/${pathRest}`)?.[1];
|
||||
@@ -75,29 +149,57 @@ export function mediaFromDetails(details: MediaDetail[] | undefined): Media[] {
|
||||
});
|
||||
}
|
||||
|
||||
function authorOf(user: TweetUser | undefined): Author {
|
||||
const avatar = user?.profile_image_url_https;
|
||||
return {
|
||||
handle: `@${user?.screen_name ?? 'unknown'}`,
|
||||
...(user?.name ? { displayName: user.name } : {}),
|
||||
// `_normal` is a 48px thumbnail; `_x96` is the same file at 96.
|
||||
...(avatar ? { avatar: { url: avatar.replace('_normal', '_x96') } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The post a quote post is talking about.
|
||||
*
|
||||
* Shown in full — whose it is, what it said and what it showed — rather than
|
||||
* having its picture lifted out and hung under the quoter's name. Half the
|
||||
* quote posts people share are someone answering a stranger, and the other
|
||||
* half are someone continuing their own thought from an earlier post; both
|
||||
* are unreadable with only one side of them on the page.
|
||||
*
|
||||
* The syndication payload carries no permalink for the quoted post, so its
|
||||
* URL is rebuilt from the handle and the id, the same shape every X post has.
|
||||
*/
|
||||
export function quotedFrom(quoted: TweetResult | undefined): Quoted | undefined {
|
||||
if (!quoted?.user) return undefined;
|
||||
const handle = quoted.user.screen_name;
|
||||
return {
|
||||
author: authorOf(quoted.user),
|
||||
...(visibleText(quoted) ? { text: visibleText(quoted) } : {}),
|
||||
media: mediaFromDetails(quoted.mediaDetails),
|
||||
...(quoted.created_at ? { postedAt: quoted.created_at } : {}),
|
||||
...(handle && quoted.id_str
|
||||
? { url: `https://x.com/${handle}/status/${quoted.id_str}` }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function toPost(result: TweetResult, originalUrl: string): Post {
|
||||
const handle = result.user?.screen_name ?? 'unknown';
|
||||
const avatar = result.user?.profile_image_url_https;
|
||||
const quoted = quotedFrom(result.quoted_tweet);
|
||||
return {
|
||||
platform: 'x',
|
||||
platformLabel: 'X',
|
||||
originalUrl,
|
||||
author: {
|
||||
handle: `@${handle}`,
|
||||
...(result.user?.name ? { displayName: result.user.name } : {}),
|
||||
// `_normal` is a 48px thumbnail; `_x96` is the same file at 96.
|
||||
...(avatar ? { avatar: { url: avatar.replace('_normal', '_x96') } } : {}),
|
||||
},
|
||||
author: authorOf(result.user),
|
||||
textPosition: 'above',
|
||||
segments: oneSegment({
|
||||
...(result.text ? { text: result.text } : {}),
|
||||
// A quote post usually carries no media of its own — the picture being
|
||||
// talked about belongs to the post it quotes, and that is the thing
|
||||
// worth showing.
|
||||
media: mediaFromDetails(
|
||||
result.mediaDetails?.length ? result.mediaDetails : result.quoted_tweet?.mediaDetails,
|
||||
),
|
||||
...(visibleText(result) ? { text: visibleText(result) } : {}),
|
||||
// Only its own. The quoted post's pictures are shown with the quoted
|
||||
// post, where it is clear whose they are.
|
||||
media: mediaFromDetails(result.mediaDetails),
|
||||
...(result.created_at ? { postedAt: result.created_at } : {}),
|
||||
...(quoted ? { quoted } : {}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user