2 Commits
Author SHA1 Message Date
thatguygriff 2ccc7bd618 Merge pull request 'Add Reddit with its comment threads, and show quoted posts whole' (#3) from reddit-and-quoted-posts into main
CI / Typecheck, test, build (push) Successful in 33s
Publish / Build and push (push) Successful in 2m3s
Reviewed-on: #3
2026-08-27 16:10:58 +00:00
thatguygriffandClaude Opus 5 6325f0ff32 Add Reddit with its comment threads, and show quoted posts whole
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 `&amp;`; 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
2026-08-27 11:45:40 -03:00
28 changed files with 3623 additions and 69 deletions
+46 -4
View File
@@ -1,9 +1,9 @@
# antisocial — working notes
A self-hosted page that shows a social post without the app. StopTheMadness rewrites
links to X, Threads, Instagram, TikTok and Bluesky into `/<prefix>/<original path>`;
this resolves the post by driving a real headless Chromium and renders the media, the
text, a platform badge and a copy-the-original button.
links to X, Threads, Instagram, TikTok, Bluesky and Reddit into
`/<prefix>/<original path>`; this resolves the post by driving a real headless Chromium
and renders the media, the text, a platform badge and a copy-the-original button.
Built for one person on a private network, with no authentication. `README.md` has the
rewrite rules and the user-facing description. This file is the working context.
@@ -35,6 +35,7 @@ different fixes:
| Right media, wrong count | The structured payload was missed and it fell through to the DOM, which only shows the first carousel item. |
| Poster image where a video belongs | Same fall-through, plus the `<video>` had not hydrated when the DOM was read. |
| Nothing at all | The platform refused this specific post logged out, or a key moved. |
| Reddit post fine, no comments | The `.json` was refused and it fell through to the page, where the comment tree loads late. |
**3. Look at what the page actually served.**
@@ -66,6 +67,17 @@ A `Post` is a list of `Segment`s, not a single body. Most platforms produce one
(`oneSegment` in `types.ts`); Bluesky and Threads produce the author's whole chain,
with `isAnchor` marking the post that was linked — which need not be the first.
`Segment.quoted` is a post inside a post — someone else's words and pictures, kept
under their own name. X and Bluesky fill it in. Both used to lift the quoted post's
media out and show it as the quoter's own, which is the bug to avoid reintroducing:
a quoted picture without the name attached to it is a false attribution.
`Post.comments` is a separate thing and a tree, not a chain. Only Reddit fills it in,
because only there is the conversation usually the point of the link. It 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 — the renderer emits a `<details>`
per comment and gets collapsing without a line of JavaScript.
Things worth knowing before editing:
- **One Chromium, one context, persistent.** Cookies and dismissed banners accumulate on
@@ -95,8 +107,24 @@ Things worth knowing before editing:
deliberately matches only V1. Threads are built by walking `parent` up and the
author's own `replies` down; `depth`/`parentHeight` are what make that possible, at
the cost of dragging the whole reply tree along (a few hundred KB on a busy post).
A quote fills in `Segment.quoted`. The record sits at `embed.record` for a plain quote
and at `embed.record.record` when the quoting post has media of its own
(`recordWithMedia`) — check both. 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`, so only
`app.bsky.embed.record#viewRecord` is accepted. The quoted post's address has to be
rebuilt: `uri` is an `at://` nobody can open.
- **X** — the `platform.twitter.com` embed calls the syndication endpoint; we catch that
response. A quote post carries no media of its own, so the quoted post's media is used.
response. A quote post keeps the post it quotes whole, in `Segment.quoted` — author,
words and pictures — rather than lifting its media out; doing that put someone else's
picture under the quoter's name, and dropped the quoted words entirely. There is no
permalink in the payload, so the quoted post's URL is rebuilt from the handle and
`id_str`. Two things about the text: it arrives pre-escaped (`&amp;`) and has to be
decoded, since everything downstream escapes again on the way out; and X staples a
`t.co` to the quoted post onto the end, which `display_text_range` trims — its indices
are UTF-16 units into the *escaped* text, so slice before decoding and do not split to
codepoints first. Every remaining link is a `t.co`, expanded from `entities.urls`
matched on the shortlink text rather than by `indices`, which are offsets into a string
the expansion is changing the length of.
- **Instagram** — the least reliable. It ships the structured payload only some of the
time, and refuses some posts from the embed entirely ("the link may be broken"). The
DOM is the floor and only ever shows the first carousel item. Reels hydrate their
@@ -106,6 +134,20 @@ Things worth knowing before editing:
carries an `itemStruct`; do not hardcode the key, photo posts use a different one.
Its CDN needs `Referer` *and* cookies. Short `vm.`/`vt.` links arrive as a bare path
segment and are rebuilt in `buildOriginalUrl`.
- **Reddit** — the `.json` twin of any post URL is the whole post plus the first page of
comments in one response, which is far better than anything the page gives up, so that
is the only layer that normally runs. A cold profile gets a JavaScript challenge
instead of JSON; an ordinary navigation solves it by itself, so the adapter navigates
once and retries, and the cookie serves every later post. The floor is
`shreddit-comment` elements, which are flat with a `depth` attribute — `treeFromDepths`
rebuilds the nesting. `replies` is `""` and not an object when there are none.
Video: `fallback_url` is the *video track alone* whenever `has_audio` is true, so a
post with sound has to use `hls_url`, direct and unproxied; a silent one gets the
proxied MP4. `scrubber_media_url` is not a poster — it is a second MP4 for the
timeline thumbnails, and the still is in `preview.images`. A gallery's pictures are in
`media_metadata`, keyed and unordered; their order is only in `gallery_data`. Comment
bodies are Markdown, rendered by `src/render/markdown.ts` — escape first, then put
back the constructs we chose to support, never `body_html`.
- **Threads** — same media schema as Instagram (`src/platforms/meta-media.ts`). Its
payloads are full of empty stub nodes, so the finder only accepts a node with actual
candidates in it. The page ships the linked post, the author's follow-ups, other
+41 -7
View File
@@ -2,9 +2,9 @@
Reads social posts back to you without the app.
Links to X, Threads, Instagram, TikTok and Bluesky get shared constantly, and opening
one means an app interstitial, a login wall, a feed you didn't ask for, and a pile of
tracking. antisocial is the other half of a StopTheMadness rewrite rule: the link gets
Links to X, Threads, Instagram, TikTok, Bluesky and Reddit get shared constantly, and
opening one means an app interstitial, a login wall, a feed you didn't ask for, and a
pile of tracking. antisocial is the other half of a StopTheMadness rewrite rule: the link gets
redirected here, and you get the post — the media and the words — plus a badge saying
where it came from and a button to copy the original URL if you do want to go there.
@@ -28,14 +28,19 @@ Replace `antisocial.example.com` with wherever you are running it.
| Instagram | `/^https:\/\/(?:www\.)?instagram\.com\/(.*)$/` | `https://antisocial.example.com/ig/$1` |
| TikTok | `/^https:\/\/(?:www\.\|vm\.\|vt\.)?tiktok\.com\/(.*)$/` | `https://antisocial.example.com/tiktok/$1` |
| Bluesky | `/^https:\/\/bsky\.app\/(.*)$/` | `https://antisocial.example.com/bsky/$1` |
| Reddit | `/^https:\/\/(?:www\.\|old\.\|new\.\|np\.\|m\.)?reddit\.com\/(.*)$/` | `https://antisocial.example.com/reddit/$1` |
| Reddit | `/^https:\/\/redd\.it\/(.*)$/` | `https://antisocial.example.com/reddit/$1` |
So `https://x.com/user/status/123` becomes
`https://antisocial.example.com/x/user/status/123`.
Tracking parameters (`igsh`, `utm_*`, `s`, `t`, and friends) are stripped on arrival, so
the URL the copy button gives back is the clean one. TikTok `vm.`/`vt.` share codes lose
their subdomain in the rewrite; a single opaque path segment is recognised as a share
code and rebuilt as `vm.tiktok.com/<code>/`.
Tracking parameters (`igsh`, `utm_*`, `share_id`, `s`, `t`, and friends) are stripped on
arrival, so the URL the copy button gives back is the clean one. TikTok `vm.`/`vt.`
share codes lose their subdomain in the rewrite; a single opaque path segment is
recognised as a share code and rebuilt as `vm.tiktok.com/<code>/`, or `redd.it/<code>`
where it came from Reddit. A Reddit `/r/<sub>/s/<code>` share link is followed to the
post it points at, and that permalink — not the opaque share code — is what the copy
button hands back.
`/` serves this table with the live hostnames, if you'd rather read it there.
@@ -61,6 +66,7 @@ Each adapter layers its extraction, most structured first:
| Instagram | `/embed/captioned/` | `shortcode_media`, then the rendered `<video>`/`<img>` |
| TikTok | the post page | `__UNIVERSAL_DATA_FOR_REHYDRATION__` |
| Threads | the post page | the Relay payloads in `<script type="application/json">` |
| Reddit | the post's own `.json` | the post and the first page of comments; falls back to the page |
On Bluesky and Threads people write in chains, so where the linked post is part
of one, the author's own follow-ups are shown with it, in the order they were
@@ -68,6 +74,29 @@ written, with the post you actually followed marked. Other people's replies are
left out — they are a conversation, not the thing that was shared, and on a busy
post there are hundreds of them.
A post that quotes another shows both, on X and on Bluesky. The quoted post gets its own
author, its own words and its own pictures, in a block inside the one quoting it —
because half the quote posts people share are someone answering a stranger and the other
half are someone continuing a thought from an earlier post, and neither reads with only
one side of it on the page. Showing the quoted picture on its own, which is what used to
happen, put it under the wrong person's name.
X links are un-shortened. Every link in a post is rewritten to a `t.co` before it is
stored, so left alone the page shows `t.co/QdJhOVu4En` and sends you through X's click
tracker to find out where it goes; the real address is in the payload alongside. 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 — a link the author put there on purpose
is kept.
On Reddit the thread under the post is usually the reason the link was shared, so
Reddit posts come with it: every comment the first page carried, nested the way it was
written. Each comment is a `<details>` element, so folding one takes its whole subtree
with it, works without JavaScript and works from the keyboard; a collapsed comment says
how many replies it is hiding. "Collapse all" is the one piece that needs the script,
which is why it only appears once the script has run. What was 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.
Media never gets linked straight at a CDN. Instagram and TikTok reject requests without
a matching `Referer` (and sometimes cookies), and proxying keeps your browser from
talking to the platform at all. Every asset is registered under an opaque `/m/<id>` and
@@ -110,6 +139,11 @@ Known rough edges:
carousel will come back as its first image only.
- **TikTok sometimes answers with a slider puzzle** instead of the post. You get handed
the puzzle rather than an error — see below.
- **Reddit refuses `.json` to a browser it has never seen.** The first request of a cold
profile gets a JavaScript challenge, which the page solves by itself on an ordinary
navigation; the adapter does that once and retries, and the cookie it leaves behind
serves every later post. If the JSON is still refused, the rendered page is read
instead — the same comments, without the scores Reddit is withholding.
## Verification puzzles
+226
View File
@@ -330,3 +330,229 @@ main { max-width: 680px; margin: 0 auto; }
min-height: 220px;
}
}
/* ---------- a post with a headline ---------- */
/* Reddit is the one platform where the post has a title and the body is
optional, so the headline has to carry on its own. */
.text__title {
margin: 0 0 8px;
font-size: 19px;
line-height: 1.3;
font-weight: 650;
}
.text__title:only-child { margin-bottom: 0; }
/* ---------- comments ---------- */
.thread {
margin-top: 12px;
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
}
.thread__head {
display: flex;
align-items: baseline;
gap: 10px;
padding: 12px 14px;
border-bottom: 1px solid var(--line);
}
.thread__title { margin: 0; font-size: 15px; font-weight: 650; }
.thread__count { font-size: 12px; color: var(--ink-dim); }
.thread__toggle {
appearance: none;
margin-left: auto;
border: 1px solid var(--line);
background: transparent;
color: var(--ink-dim);
font: inherit;
font-size: 12px;
padding: 4px 12px;
border-radius: 999px;
cursor: pointer;
}
.thread__list { padding: 6px 14px 14px; }
.c { margin-top: 10px; }
/* The whole byline is the hit target for folding, so it wants to look like
one thing rather than a row of separate labels. */
.c__head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 8px;
font-size: 12px;
color: var(--ink-dim);
cursor: pointer;
list-style: none;
padding: 2px 0;
user-select: none;
}
.c__head::-webkit-details-marker { display: none; }
.c__head::before {
content: "";
display: inline-grid;
place-items: center;
width: 15px;
height: 15px;
border: 1px solid var(--line);
border-radius: 4px;
font-size: 11px;
line-height: 1;
color: var(--ink-dim);
flex: none;
}
.c:not([open]) > .c__head::before { content: "+"; }
.c__author { font-weight: 600; color: var(--ink); }
.c__hidden { font-variant-numeric: tabular-nums; }
.c[open] > .c__head .c__hidden { display: none; }
.c__mark {
padding: 1px 5px;
border-radius: 4px;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
color: var(--accent-ink);
background: var(--ink-dim);
}
.c__mark--op { background: #ff4500; }
.c__mark--mod, .c__mark--admin { background: #1a7f4b; }
.c__body { font-size: 15px; overflow-wrap: anywhere; }
.c__body > :first-child { margin-top: 4px; }
.c__body > :last-child { margin-bottom: 0; }
.c__body p { margin: 0 0 8px; }
.c__body a { color: inherit; text-decoration-color: var(--ink-dim); text-underline-offset: 2px; }
.c__body ul, .c__body ol { margin: 0 0 8px; padding-left: 20px; }
.c__body blockquote {
margin: 0 0 8px;
padding-left: 10px;
border-left: 3px solid var(--line);
color: var(--ink-dim);
}
.c__body pre {
margin: 0 0 8px;
padding: 8px 10px;
border-radius: 8px;
background: color-mix(in srgb, var(--ink) 6%, transparent);
overflow-x: auto;
}
.c__body code { font-size: 13px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.c__body pre code { font-size: 12px; }
/* The rule down the left is what tells you where a subtree ends, which is
the thing a wall of replies otherwise makes you count indents for. */
.c__replies {
margin: 6px 0 0 7px;
padding-left: 11px;
border-left: 1px solid var(--line);
}
.c__more { margin: 8px 0 0; font-size: 12px; color: var(--ink-dim); }
.thread__more {
margin: 0;
padding: 12px 14px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--ink-dim);
}
@media (max-width: 520px) {
.c__replies { margin-left: 4px; padding-left: 7px; }
}
/* ---------- a quoted post ---------- */
/*
* A post inside a post. Bordered and inset rather than merely indented,
* because the whole job of this block is to be unmistakably someone else's
* — an indent alone reads as a continuation of the words above it.
*/
.quote {
margin: 0 14px 14px;
border: 1px solid var(--line);
border-radius: 10px;
overflow: hidden;
}
.text + .quote, .media + .quote { margin-top: 14px; }
.quote__who {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 2px 6px;
padding: 10px 12px 0;
font-size: 13px;
min-width: 0;
}
.quote__avatar {
width: 20px;
height: 20px;
border-radius: 50%;
flex: none;
align-self: center;
}
.quote__name { font-weight: 600; }
.quote__handle, .quote__who time { color: var(--ink-dim); font-size: 12px; }
.quote__text { padding: 6px 12px 10px; font-size: 15px; overflow-wrap: anywhere; }
.quote__text a { color: inherit; text-decoration-color: var(--ink-dim); text-underline-offset: 2px; }
/* Its own media sits flush in the block, the way the post's own does in the
card, so the two read as the same kind of thing at different sizes. */
.quote .media { border-bottom: 0; }
.quote__text + .media, .quote__who + .media { border-top: 1px solid var(--line); }
.quote__open {
display: block;
padding: 9px 12px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--ink-dim);
text-decoration: none;
}
/*
* Deliberately smaller than the post's own media, and after the window-fitting
* rule above so it wins on source order at equal specificity. A quote is
* context for the post, and context that fills the screen has stopped being
* context.
*/
.post .quote .item img,
.post .quote .item video {
max-height: 40vh;
max-height: 40dvh;
min-height: 0;
}
/*
* A post that quotes another has two things to show, so its own media gives
* up the window-filling cap above. Left at full height the quote starts below
* the fold, which is the same as not having it — the whole reason it is here
* is that neither half reads without the other.
*/
.segment[data-quoted] .item img,
.segment[data-quoted] .item video {
max-height: 45vh;
max-height: 45dvh;
min-height: 0;
}
+35 -5
View File
@@ -37,10 +37,9 @@ function setupCopy() {
}
}
function setupMedia() {
const media = document.querySelector('.media');
if (!media) return;
// One per rail: a post can carry several -- a thread of them, or a post and
// the post it quotes -- and wiring only the first leaves the rest inert.
function setupMedia(media) {
const rail = media.querySelector('.media__rail');
const items = [...media.querySelectorAll('.item')];
const at = media.querySelector('.media__at');
@@ -97,8 +96,39 @@ function setupMedia() {
}
}
// Every comment is a <details open>, so folding one already works with this
// file missing. All this adds is doing the whole page at once, which is why
// the button ships hidden and is only revealed here.
function setupComments() {
const toggle = document.querySelector('.thread__toggle');
if (!toggle) return;
const all = [...document.querySelectorAll('details.c')];
if (all.length === 0) return;
toggle.hidden = false;
toggle.addEventListener('click', () => {
const collapsing = toggle.dataset.collapsed !== 'true';
for (const comment of all) comment.open = !collapsing;
toggle.dataset.collapsed = String(collapsing);
toggle.textContent = collapsing ? 'Expand all' : 'Collapse all';
});
// Reopening one by hand means the page is no longer collapsed, so the
// button should offer the other thing.
for (const comment of all) {
comment.addEventListener('toggle', () => {
if (comment.open && toggle.dataset.collapsed === 'true') {
toggle.dataset.collapsed = 'false';
toggle.textContent = 'Collapse all';
}
});
}
}
setupCopy();
setupMedia();
for (const media of document.querySelectorAll('.media')) setupMedia(media);
setupComments();
// --- Verification puzzles -------------------------------------------------
//
+55 -8
View File
@@ -1,5 +1,5 @@
import { config } from '../config.ts';
import { ResolveError, type Media, type Post, type Segment } from '../types.ts';
import { ResolveError, type Media, type Post, type Quoted, type Segment } from '../types.ts';
import { captureJson } from '../browser/capture.ts';
import { hostMatcher } from './url.ts';
import type { PlatformSpec, ResolveContext } from './types.ts';
@@ -8,6 +8,18 @@ const API = 'https://public.api.bsky.app/xrpc';
type Aspect = { width: number; height: number };
type Actor = { handle?: string; displayName?: string; avatar?: string };
/** The quoted post as the API hands it over, when it is a post at all a
* quote can also point at a feed, a list, or something deleted. */
type ViewRecord = {
$type?: string;
uri?: string;
author?: Actor;
value?: { text?: string; createdAt?: string };
embeds?: Embed[];
};
type Embed = {
$type?: string;
images?: Array<{ thumb?: string; fullsize?: string; alt?: string; aspectRatio?: Aspect }>;
@@ -15,12 +27,14 @@ type Embed = {
thumbnail?: string;
aspectRatio?: Aspect;
media?: Embed;
record?: { embeds?: Embed[] };
/** A plain quote puts the record here; a quote with media of its own puts
* it one level further in. */
record?: ViewRecord & { record?: ViewRecord };
};
type BskyPost = {
uri?: string;
author?: { handle?: string; displayName?: string; avatar?: string };
author?: Actor;
record?: { text?: string; createdAt?: string };
embed?: Embed;
indexedAt?: string;
@@ -73,19 +87,52 @@ export function mediaFromEmbed(embed: Embed | undefined): Media[] {
}];
}
// A quote post carries the quoted post's media one level in. That is
// usually the thing being pointed at, so it is what to show.
const quoted = embed.record?.embeds?.[0];
if (quoted) return mediaFromEmbed(quoted);
// Nothing of its own. A quoted post's pictures belong to the quoted post
// and are shown with it, under the name of whoever actually posted them.
return [];
}
/** `at://<did>/app.bsky.feed.post/<rkey>` is not a link anyone can open, so
* the web address is rebuilt from the handle and the record key. */
function webUrlFor(uri: string | undefined, handle: string | undefined): string | undefined {
const rkey = uri?.split('/').pop();
return rkey && handle ? `https://bsky.app/profile/${handle}/post/${rkey}` : undefined;
}
/**
* The post being quoted.
*
* A quote can also point at a feed, a list or a post that has since been
* deleted or blocked, and those arrive under different `$type`s in the same
* slot. Only a real post is taken; anything else is left out rather than
* rendered as a nameless empty box.
*/
export function quotedFrom(embed: Embed | undefined): Quoted | undefined {
// A quote carrying media of its own nests the record one level deeper.
const record = embed?.record?.record ?? embed?.record;
if (record?.$type !== 'app.bsky.embed.record#viewRecord' || !record.author) return undefined;
const url = webUrlFor(record.uri, record.author.handle);
return {
author: {
handle: `@${record.author.handle ?? 'unknown'}`,
...(record.author.displayName ? { displayName: record.author.displayName } : {}),
...(record.author.avatar ? { avatar: { url: record.author.avatar } } : {}),
},
...(record.value?.text ? { text: record.value.text } : {}),
media: mediaFromEmbed(record.embeds?.[0]),
...(record.value?.createdAt ? { postedAt: record.value.createdAt } : {}),
...(url ? { url } : {}),
};
}
function segmentOf(post: BskyPost, isAnchor: boolean): Segment {
const quoted = quotedFrom(post.embed);
return {
...(post.record?.text ? { text: post.record.text } : {}),
media: mediaFromEmbed(post.embed),
...(post.record?.createdAt ? { postedAt: post.record.createdAt } : {}),
...(quoted ? { quoted } : {}),
...(isAnchor ? { isAnchor: true } : {}),
};
}
+2 -1
View File
@@ -5,8 +5,9 @@ import { threads } from './threads.ts';
import { instagram } from './instagram.ts';
import { tiktok } from './tiktok.ts';
import { bluesky } from './bluesky.ts';
import { reddit } from './reddit.ts';
export const platforms: readonly PlatformSpec[] = [x, threads, instagram, tiktok, bluesky];
export const platforms: readonly PlatformSpec[] = [x, threads, instagram, tiktok, bluesky, reddit];
const byPrefix = new Map(platforms.map((p) => [p.prefix, p]));
+466
View File
@@ -0,0 +1,466 @@
import type { Page } from 'playwright';
import { ResolveError, oneSegment, type Comment, type Media, type Post } from '../types.ts';
import { readOpenGraph } from '../browser/capture.ts';
import { stripTracking } from './url.ts';
import type { PlatformSpec, ResolveContext } from './types.ts';
const HOST = 'https://www.reddit.com';
/** Path roots that are really Reddit paths, so anything else that arrives as
* a single opaque segment is a `redd.it` share code. */
const KNOWN_ROOTS = new Set(['r', 'u', 'user', 'comments', 'gallery', 'media', 'wiki']);
type Listing<T> = { kind?: string; data?: { children?: Array<Thing<T>> } };
type Thing<T> = { kind?: string; data?: T };
type RedditVideo = {
fallback_url?: string;
hls_url?: string;
has_audio?: boolean;
width?: number;
height?: number;
duration?: number;
};
type MediaMeta = {
status?: string;
e?: string;
m?: string;
s?: { u?: string; gif?: string; mp4?: string; x?: number; y?: number };
};
type Link = {
title?: string;
author?: string;
subreddit_name_prefixed?: string;
created_utc?: number;
selftext?: string;
permalink?: string;
url?: string;
url_overridden_by_dest?: string;
domain?: string;
post_hint?: string;
is_self?: boolean;
is_video?: boolean;
is_gallery?: boolean;
over_18?: boolean;
spoiler?: boolean;
link_flair_text?: string | null;
num_comments?: number;
score?: number;
gallery_data?: { items?: Array<{ media_id?: string }> };
media_metadata?: Record<string, MediaMeta>;
secure_media?: { reddit_video?: RedditVideo } | null;
media?: { reddit_video?: RedditVideo } | null;
preview?: {
images?: Array<{ source?: { url?: string; width?: number; height?: number } }>;
reddit_video_preview?: RedditVideo;
};
crosspost_parent_list?: Link[];
};
type CommentData = {
author?: string;
body?: string;
created_utc?: number;
score?: number;
score_hidden?: boolean;
is_submitter?: boolean;
distinguished?: string | null;
replies?: Listing<CommentData> | '';
};
type MoreData = { count?: number };
/** `[deleted]` and `[removed]` are the platform's own words, kept as they are. */
function authorName(author: string | undefined): string {
if (!author || author.startsWith('[')) return author ?? '[unknown]';
return `u/${author}`;
}
function isoFrom(seconds: number | undefined): string | undefined {
return seconds ? new Date(seconds * 1000).toISOString() : undefined;
}
function sized(width: number | undefined, height: number | undefined) {
return {
...(width ? { width } : {}),
...(height ? { height } : {}),
};
}
/**
* Reddit's own video, which arrives in three forms at once.
*
* `fallback_url` is a plain MP4 and the nicer thing to serve it proxies,
* so the viewer never talks to Reddit, and the native scrubber can seek it.
* But when a post has sound that MP4 is the video track alone: the audio is
* a separate file the DASH manifest stitches back on. So a silent post gets
* the MP4 and one with audio gets the HLS playlist, linked directly because
* proxying it would mean rewriting the manifest and every segment.
*/
function fromRedditVideo(video: RedditVideo, poster: string | undefined): Media[] {
const common = {
...sized(video.width, video.height),
...(video.duration ? { durationSec: video.duration } : {}),
};
if (video.has_audio !== false && video.hls_url) {
return [{ kind: 'video', url: video.hls_url, hls: true, direct: true, ...common }];
}
const url = video.fallback_url ?? video.hls_url;
if (!url) return [];
if (url === video.hls_url) {
return [{ kind: 'video', url, hls: true, direct: true, ...common }];
}
return [{
kind: 'video',
url,
...(poster ? { poster: { url: poster } } : {}),
...common,
}];
}
/** One entry of a gallery post. Reddit keeps the pictures somewhere other
* than the order it wants them shown in, so the two have to be joined. */
function fromGalleryItem(meta: MediaMeta | undefined): Media[] {
if (!meta || meta.status !== 'valid') return [];
const size = sized(meta.s?.x, meta.s?.y);
// An animated entry ships as a video as well; that is smaller and seekable.
if (meta.s?.mp4) return [{ kind: 'video', url: meta.s.mp4, ...size }];
const url = meta.s?.gif ?? meta.s?.u;
return url ? [{ kind: 'image', url, ...size }] : [];
}
export function mediaFromLink(link: Link): Media[] {
// A crosspost is a wrapper with nothing of its own in it.
const crossposted = link.crosspost_parent_list?.[0];
if (crossposted && !link.is_self) {
const inner = mediaFromLink(crossposted);
if (inner.length) return inner;
}
// `scrubber_media_url` looks like a poster and is not one: it is a second,
// tiny MP4 for the timeline thumbnails. The still is in the preview.
const still = link.preview?.images?.[0]?.source?.url;
const video = link.secure_media?.reddit_video ?? link.media?.reddit_video;
if (video) return fromRedditVideo(video, still);
if (link.is_gallery) {
const items = link.gallery_data?.items ?? [];
const gallery = items.flatMap((item) =>
fromGalleryItem(item.media_id ? link.media_metadata?.[item.media_id] : undefined));
if (gallery.length) return gallery;
}
// A GIF link is served as a video by the preview, which is the version
// worth having: the original is often tens of megabytes.
const asVideo = link.preview?.reddit_video_preview;
if (asVideo) return fromRedditVideo(asVideo, still);
const direct = link.url_overridden_by_dest ?? link.url;
if (direct && /\.(jpe?g|png|webp|gif)(\?|$)/i.test(direct)) {
const source = link.preview?.images?.[0]?.source;
return [{ kind: 'image', url: direct, ...sized(source?.width, source?.height) }];
}
// A link to somewhere else: the preview is all Reddit has, and it is still
// worth showing above the link itself.
const preview = link.preview?.images?.[0]?.source;
if (preview?.url) {
return [{ kind: 'image', url: preview.url, ...sized(preview.width, preview.height) }];
}
return [];
}
/**
* The words of the post: the self text, or for a link post the
* destination, which is the whole content of the post and needs to be
* tappable.
*/
function bodyOf(link: Link): string | undefined {
if (link.selftext?.trim()) return link.selftext;
const dest = link.url_overridden_by_dest;
if (dest && !dest.includes('redd.it') && !dest.startsWith(`${HOST}/gallery/`)) return dest;
return undefined;
}
export function commentsFrom(listing: Listing<CommentData> | undefined): {
comments: Comment[];
more: number;
} {
const comments: Comment[] = [];
let more = 0;
for (const child of listing?.data?.children ?? []) {
if (child.kind === 'more') {
more += (child.data as MoreData | undefined)?.count ?? 0;
continue;
}
const data = child.data;
if (!data || data.body === undefined) continue;
const replies = data.replies && typeof data.replies === 'object'
? commentsFrom(data.replies)
: { comments: [], more: 0 };
comments.push({
author: authorName(data.author),
...(data.body ? { text: data.body } : {}),
...(isoFrom(data.created_utc) ? { postedAt: isoFrom(data.created_utc) } : {}),
// Reddit hides the score on a new comment so an early downvote cannot
// steer the rest. Showing a placeholder 1 would be a lie.
...(data.score_hidden !== true && typeof data.score === 'number' ? { score: data.score } : {}),
...(data.is_submitter ? { isAuthor: true } : {}),
...(data.distinguished ? { distinguished: data.distinguished } : {}),
replies: replies.comments,
...(replies.more ? { moreReplies: replies.more } : {}),
});
}
return { comments, more };
}
export function toPost(body: [Listing<Link>, Listing<CommentData>], originalUrl: string): Post {
const link = body[0]?.data?.children?.[0]?.data;
if (!link) throw new ResolveError('Reddit returned no post', 'reddit', originalUrl);
const { comments, more } = commentsFrom(body[1]);
const flags = [
link.link_flair_text?.trim(),
link.over_18 ? 'NSFW' : undefined,
link.spoiler ? 'Spoiler' : undefined,
].filter(Boolean);
return {
platform: 'reddit',
platformLabel: 'Reddit',
originalUrl,
author: {
// The subreddit is the identity a Reddit link carries — the poster is
// a detail underneath it, so it goes in the display name.
handle: link.subreddit_name_prefixed ?? 'reddit',
displayName: [authorName(link.author), ...flags].join(' · '),
},
textPosition: 'above',
segments: oneSegment({
...(link.title ? { title: link.title } : {}),
...(bodyOf(link) ? { text: bodyOf(link) } : {}),
media: mediaFromLink(link),
...(isoFrom(link.created_utc) ? { postedAt: isoFrom(link.created_utc) } : {}),
}),
comments,
...(more ? { moreComments: more } : {}),
...(typeof link.num_comments === 'number' ? { commentCount: link.num_comments } : {}),
};
}
export type FlatComment = {
depth: number;
author: string;
score: number;
created: string;
text: string;
};
/**
* Rebuild the nesting from a flat list of comments that each know only their
* own depth, which is how the rendered page presents them.
*/
export function treeFromDepths(flat: FlatComment[]): Comment[] {
const roots: Comment[] = [];
// The comment last seen at each depth, so a reply can be attached to
// whatever it appeared underneath.
const openAt: Comment[] = [];
for (const row of flat) {
if (!row.text) continue;
const comment: Comment = {
author: authorName(row.author),
text: row.text,
...(row.created && !Number.isNaN(Date.parse(row.created))
? { postedAt: new Date(row.created).toISOString() }
: {}),
...(Number.isFinite(row.score) ? { score: row.score } : {}),
replies: [],
};
const parent = openAt[row.depth - 1];
if (row.depth > 0 && parent) parent.replies.push(comment);
else roots.push(comment);
// Anything deeper belonged to the comment this one just replaced.
openAt.length = row.depth + 1;
openAt[row.depth] = comment;
}
return roots;
}
/**
* Reads the comment tree back out of the rendered page.
*
* The floor, for when the JSON is refused. Reddit renders every comment as a
* `<shreddit-comment>` carrying its own depth, flat in document order.
*/
async function commentsFromDom(page: Page): Promise<Comment[]> {
const flat = await page
.evaluate(() =>
[...document.querySelectorAll('shreddit-comment')].map((el) => ({
depth: Number(el.getAttribute('depth') ?? 0),
author: el.getAttribute('author') ?? '',
score: Number(el.getAttribute('score') ?? Number.NaN),
created: el.getAttribute('created') ?? '',
text: el.querySelector('[slot="comment"]')?.textContent?.trim() ?? '',
})))
.catch((): FlatComment[] => []);
return treeFromDepths(flat);
}
/** Whatever the page will admit to, when the JSON will not come. */
async function fromPage(page: Page, originalUrl: string): Promise<Post> {
const attrs = await page
.evaluate(() => {
const post = document.querySelector('shreddit-post');
if (!post) return null;
const get = (name: string): string | undefined => post.getAttribute(name) ?? undefined;
return {
title: get('post-title'),
author: get('author'),
subreddit: get('subreddit-prefixed-name'),
created: get('created-timestamp'),
score: get('score'),
comments: get('comment-count'),
image: get('content-href'),
};
})
.catch(() => null);
const og = await readOpenGraph(page);
const title = attrs?.title ?? og['og:title'];
if (!title) throw new ResolveError('Reddit served neither the post nor its data', 'reddit', originalUrl);
const image = attrs?.image ?? og['og:image'];
const media: Media[] =
image && /\.(jpe?g|png|webp|gif)(\?|$)/i.test(image) ? [{ kind: 'image', url: image }] : [];
const count = Number(attrs?.comments);
return {
platform: 'reddit',
platformLabel: 'Reddit',
originalUrl,
author: {
handle: attrs?.subreddit ?? 'reddit',
displayName: authorName(attrs?.author),
},
textPosition: 'above',
segments: oneSegment({
title,
media,
...(attrs?.created && !Number.isNaN(Date.parse(attrs.created))
? { postedAt: new Date(attrs.created).toISOString() }
: {}),
}),
comments: await commentsFromDom(page),
...(Number.isFinite(count) ? { commentCount: count } : {}),
};
}
/** The `.json` twin of a post URL, asked for at the size of one page. */
function jsonUrlFor(postUrl: string): string {
const url = new URL(postUrl);
url.pathname = `${url.pathname.replace(/\/+$/, '')}/.json`;
url.search = '';
url.searchParams.set('raw_json', '1');
url.searchParams.set('limit', '100');
url.searchParams.set('sort', 'confidence');
return url.href;
}
function isShareLink(url: URL): boolean {
return url.hostname === 'redd.it' || /^\/r\/[^/]+\/s\/[^/]+/.test(url.pathname);
}
/**
* Share links from the app are opaque, and the post id is only on the other
* side of a redirect. One request that is told not to follow it is enough
* far cheaper than loading the page to find out where it went.
*/
async function followShareLink(page: Page, originalUrl: string): Promise<string> {
const response = await page.request
.get(originalUrl, { maxRedirects: 0 })
.catch(() => undefined);
const location = response?.headers()['location'];
if (!location) return originalUrl;
try {
return stripTracking(new URL(location, originalUrl)).href;
} catch {
return originalUrl;
}
}
async function fetchJson(page: Page, url: string): Promise<[Listing<Link>, Listing<CommentData>] | undefined> {
const response = await page.request
.get(url, { headers: { Accept: 'application/json' } })
.catch(() => undefined);
if (!response?.ok()) return undefined;
if (!response.headers()['content-type']?.includes('json')) return undefined;
const body = (await response.json().catch(() => undefined)) as unknown;
return Array.isArray(body) && body.length >= 2 ? (body as [Listing<Link>, Listing<CommentData>]) : undefined;
}
async function resolve({ page, originalUrl }: ResolveContext): Promise<Post> {
let postUrl = originalUrl;
try {
if (isShareLink(new URL(originalUrl))) postUrl = await followShareLink(page, originalUrl);
} catch {
// Not a URL we can take apart; the request below will say so.
}
// Reddit's JSON is the whole post and the whole first page of comments in
// one response, which no amount of reading the page can match.
let body = await fetchJson(page, jsonUrlFor(postUrl));
if (!body) {
// A cold context gets a JavaScript challenge instead, which the page
// solves by itself on any ordinary navigation. Doing that once leaves the
// cookie behind and the JSON answers from then on, including for every
// later post.
await page.goto(postUrl, { waitUntil: 'domcontentloaded' }).catch(() => undefined);
await page.waitForTimeout(1500);
body = await fetchJson(page, jsonUrlFor(page.url() || postUrl));
if (!body) {
// Still refused. The page in front of us is the post, so read that.
await page.waitForSelector('shreddit-comment', { timeout: 5_000 }).catch(() => undefined);
return fromPage(page, originalUrl);
}
}
// The resolved permalink, not the share code we came in with: an opaque
// `/s/` link says nothing about what it points at, and handing it back is
// the same as handing back a tracking parameter.
return toPost(body, postUrl);
}
export const reddit: PlatformSpec = {
id: 'reddit',
label: 'Reddit',
prefix: 'reddit',
canonicalHost: 'www.reddit.com',
textPosition: 'above',
matchesHost: (host) => host === 'reddit.com' || host.endsWith('.reddit.com') || host === 'redd.it',
/** A single opaque segment is a `redd.it` share code the rewrite rule
* drops the host, so `redd.it/abc123` arrives as just `abc123`. */
buildOriginalUrl: (pathRest, search) => {
const first = pathRest.split('/')[0] ?? '';
if (first && !pathRest.includes('/') && !KNOWN_ROOTS.has(first)) {
return `https://redd.it/${first}${search}`;
}
return `${HOST}/${pathRest}${search}`;
},
resolve,
};
+1
View File
@@ -9,6 +9,7 @@ const TRACKING_PARAMS = new Set([
's', 't', 'si', 'xmt', '_r', '_t', '_d',
'is_from_webapp', 'sender_device', 'sender_web_id', 'web_id',
'share_app_id', 'share_link_id', 'share_item_id', 'tt_from',
'share_id', 'rdt', 'correlation_id', 'post_fullname', 'ref_campaign',
]);
export function stripTracking(url: URL): URL {
+119 -17
View File
@@ -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 `&amp;`. Everything
* downstream escapes on the way out, so leaving them would put the entity
* itself on screen.
*/
const ENTITIES: Record<string, string> = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
};
function decodeEntities(text: string): string {
// `&amp;` last would double-decode `&amp;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 } : {}),
}),
};
}
+1
View File
@@ -31,6 +31,7 @@ const ACCENT: Record<string, { color: string; monogram: string }> = {
instagram: { color: '#c13584', monogram: 'IG' },
tiktok: { color: '#fe2c55', monogram: '♪' },
bluesky: { color: '#0085ff', monogram: 'B' },
reddit: { color: '#ff4500', monogram: 'r' },
};
export function badge(platform: string, label: string): Raw {
+167
View File
@@ -0,0 +1,167 @@
import { escapeHtml, raw, type Raw } from './html.ts';
/**
* The small subset of Markdown people actually write in a Reddit comment.
*
* Not a Markdown implementation, and not trying to be one. Reddit hands us
* `body_html` too, but taking that would mean trusting markup a stranger
* caused to be generated; the rule here is the same as everywhere else in
* this project escape first, then put back only the constructs we chose to
* support. Anything unrecognised stays as the literal characters the
* commenter typed, which is the safe way to be wrong.
*/
const REDDIT = 'https://www.reddit.com';
/** Absolute http(s) only. `javascript:` and friends never become links. */
function safeHref(url: string): string | undefined {
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : undefined;
} catch {
return undefined;
}
}
function anchor(href: string, label: string): string {
return `<a href="${escapeHtml(href)}" rel="noopener noreferrer nofollow" target="_blank">${escapeHtml(label)}</a>`;
}
/**
* Trailing punctuation is far more often the end of the sentence than part
* of the address, and an unmatched closing bracket cannot belong to a URL
* that has no opening one.
*/
function trimUrlTail(url: string): string {
let out = url;
for (;;) {
const last = out.at(-1) ?? '';
if (',.;:!?'.includes(last)) out = out.slice(0, -1);
else if (last === ')' && (out.match(/\(/g)?.length ?? 0) < (out.match(/\)/g)?.length ?? 0)) {
out = out.slice(0, -1);
} else return out;
}
}
const INLINE = new RegExp(
[
'`([^`\\n]+)`', // 1 code
'\\[([^\\]\\n]+)\\]\\(([^)\\s]+)\\)', // 2 label, 3 href
'\\*\\*([^*\\n]+)\\*\\*', // 4 strong
'~~([^~\\n]+)~~', // 5 strike
'(?<![\\w*])\\*([^*\\n]+)\\*(?![\\w*])', // 6 em with asterisks
'(?<![\\w_])_([^_\\n]+)_(?![\\w_])', // 7 em with underscores
'(https?://[^\\s<>]+)', // 8 bare url
'(?<![\\w/])(/?[ru]/[A-Za-z0-9_][A-Za-z0-9_-]{1,30})', // 9 r/sub and u/name
].join('|'),
'g',
);
/** One line of body text: escaped, with the inline constructs put back. */
function inline(text: string): string {
let out = '';
let cursor = 0;
for (const match of text.matchAll(INLINE)) {
const [whole, code, label, href, strong, strike, emStar, emScore, url, subOrUser] = match;
out += escapeHtml(text.slice(cursor, match.index));
cursor = match.index + whole.length;
if (code !== undefined) {
out += `<code>${escapeHtml(code)}</code>`;
} else if (label !== undefined && href !== undefined) {
const safe = safeHref(href);
out += safe ? anchor(safe, label) : escapeHtml(whole);
} else if (strong !== undefined) {
out += `<strong>${inline(strong)}</strong>`;
} else if (strike !== undefined) {
out += `<del>${inline(strike)}</del>`;
} else if (emStar !== undefined || emScore !== undefined) {
out += `<em>${inline(emStar ?? emScore ?? '')}</em>`;
} else if (url !== undefined) {
const trimmed = trimUrlTail(url);
const safe = safeHref(trimmed);
out += safe
? anchor(safe, trimmed.replace(/^https?:\/\/(www\.)?/, '')) + escapeHtml(url.slice(trimmed.length))
: escapeHtml(whole);
} else if (subOrUser !== undefined) {
const path = subOrUser.startsWith('/') ? subOrUser : `/${subOrUser}`;
out += anchor(`${REDDIT}${path}`, subOrUser);
}
}
return out + escapeHtml(text.slice(cursor));
}
const BULLET = /^\s{0,3}[-*+]\s+/;
const NUMBERED = /^\s{0,3}\d+[.)]\s+/;
/**
* Group lines into blocks and render each. Blocks are what separate a quote
* from the reply to it, and a comment that loses that separation reads as
* though the commenter said both halves.
*/
function blocks(lines: string[]): string {
let out = '';
let at = 0;
const takeWhile = (keep: (line: string) => boolean): string[] => {
const run: string[] = [];
while (at < lines.length && keep(lines[at] ?? '')) {
run.push(lines[at] ?? '');
at += 1;
}
return run;
};
while (at < lines.length) {
const line = lines[at] ?? '';
if (line.trim() === '') {
at += 1;
continue;
}
if (/^\s*```/.test(line)) {
at += 1;
const body = takeWhile((l) => !/^\s*```/.test(l));
if (at < lines.length) at += 1; // the closing fence
out += `<pre><code>${escapeHtml(body.join('\n'))}</code></pre>`;
continue;
}
if (/^ {4}\S/.test(line)) {
const body = takeWhile((l) => /^ {4}/.test(l) || l.trim() === '');
out += `<pre><code>${escapeHtml(body.map((l) => l.slice(4)).join('\n').trimEnd())}</code></pre>`;
continue;
}
if (/^\s*>/.test(line)) {
const body = takeWhile((l) => /^\s*>/.test(l));
// Nested, so a quote of a quote keeps its shape.
out += `<blockquote>${blocks(body.map((l) => l.replace(/^\s*>\s?/, '')))}</blockquote>`;
continue;
}
if (BULLET.test(line) || NUMBERED.test(line)) {
const ordered = !BULLET.test(line);
const pattern = ordered ? NUMBERED : BULLET;
const items = takeWhile((l) => pattern.test(l));
const tag = ordered ? 'ol' : 'ul';
out += `<${tag}>${items.map((l) => `<li>${inline(l.replace(pattern, ''))}</li>`).join('')}</${tag}>`;
continue;
}
const paragraph = takeWhile(
(l) => l.trim() !== '' && !/^\s*>/.test(l) && !BULLET.test(l) && !NUMBERED.test(l) && !/^\s*```/.test(l),
);
out += `<p>${paragraph.map((l) => inline(l)).join('<br>')}</p>`;
}
return out;
}
/** Comment text, as safe markup. */
export function renderMarkdown(text: string): Raw {
return raw(blocks(text.replace(/\r\n?/g, '\n').split('\n')));
}
+136 -5
View File
@@ -1,7 +1,8 @@
import { proxyUrlFor } from '../media/registry.ts';
import { anchorOf, type Media, type Post, type Segment } from '../types.ts';
import { anchorOf, type Comment, type Media, type Post, type Quoted, type Segment } from '../types.ts';
import { html, raw, type Raw } from './html.ts';
import { badge, layout, originalUrlBlock } from './layout.ts';
import { renderMarkdown } from './markdown.ts';
import { linkify } from './text.ts';
/**
@@ -62,8 +63,11 @@ function renderMedia(media: Media[]): Raw {
}
function renderText(segment: Segment, post: Post): Raw {
if (!segment.text) return html``;
return html`<div class="text">${linkify(segment.text, post.platform)}</div>`;
if (!segment.text && !segment.title) return html``;
return html`<div class="text">
${segment.title ? html`<h1 class="text__title">${segment.title}</h1>` : ''}
${segment.text ? linkify(segment.text, post.platform) : ''}
</div>`;
}
function renderWhen(postedAt: string | undefined): Raw {
@@ -76,6 +80,36 @@ function renderWhen(postedAt: string | undefined): Raw {
})}</time>`;
}
/**
* The post being quoted, drawn as a post of its own inside the one quoting
* it: its author, its words, its pictures, and a way to open it.
*
* The author line is the point. Lifting only the media out which is what
* this used to do put someone else's picture under the quoter's name with
* nothing to say so.
*/
function renderQuoted(quoted: Quoted, post: Post): Raw {
const avatar = quoted.author.avatar ? proxyUrlFor(quoted.author.avatar) : undefined;
return html`<blockquote class="quote">
<header class="quote__who">
${avatar ? html`<img class="quote__avatar" src="${avatar}" alt="" loading="lazy">` : ''}
${quoted.author.displayName
? html`<span class="quote__name">${quoted.author.displayName}</span>`
: ''}
<span class="quote__handle">${quoted.author.handle}</span>
${renderWhen(quoted.postedAt)}
</header>
${quoted.text ? html`<div class="quote__text">${linkify(quoted.text, post.platform)}</div>` : ''}
${renderMedia(quoted.media)}
${quoted.url
? html`<a class="quote__open" href="${quoted.url}" rel="noopener noreferrer nofollow" target="_blank">
Open the quoted post on ${post.platformLabel}
</a>`
: ''}
</blockquote>`;
}
/**
* One post in the chain. When there is only one, the wrapper is invisible;
* when there are several, each is separated and the one that was actually
@@ -83,13 +117,109 @@ function renderWhen(postedAt: string | undefined): Raw {
*/
function renderSegment(segment: Segment, post: Post, threaded: boolean): Raw {
const above = post.textPosition === 'above';
return html`<section class="segment" ${threaded && segment.isAnchor ? raw('data-anchor="true"') : ''}>
return html`<section class="segment" ${threaded && segment.isAnchor ? raw('data-anchor="true"') : ''} ${
segment.quoted ? raw('data-quoted="true"') : ''
}>
${threaded && segment.isAnchor
? html`<p class="segment__mark">the post you followed</p>`
: ''}
${above ? renderText(segment, post) : ''}
${renderMedia(segment.media)}
${above ? '' : renderText(segment, post)}
${segment.quoted ? renderQuoted(segment.quoted, post) : ''}
</section>`;
}
/** Short enough to sit on a comment's byline without wrapping. Absolute
* rather than "3 hours ago", because the page is cached for an hour and a
* relative time would quietly become wrong while it sat there. */
function shortWhen(postedAt: string | undefined): Raw {
if (!postedAt) return html``;
const date = new Date(postedAt);
if (Number.isNaN(date.getTime())) return html``;
return html`<time datetime="${date.toISOString()}">${date.toLocaleString('en-CA', {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
})}</time>`;
}
/** Everything hanging off a comment, however deep. Shown only while it is
* collapsed, so what a fold is hiding is never a mystery. */
function descendantsOf(comment: Comment): number {
return comment.replies.reduce((total, reply) => total + 1 + descendantsOf(reply), 0);
}
/**
* One comment and everything under it.
*
* A `<details>` per comment, so collapsing works with the stylesheet turned
* off and the keyboard alone, and takes the whole subtree with it because
* the replies are nested inside rather than listed alongside.
*/
function renderComment(comment: Comment, depth: number): Raw {
const marks = [
comment.isAuthor ? 'OP' : undefined,
comment.distinguished === 'moderator' ? 'MOD' : undefined,
comment.distinguished === 'admin' ? 'ADMIN' : undefined,
].filter((mark) => mark !== undefined);
return html`<details class="c" open data-depth="${depth}">
<summary class="c__head">
<span class="c__author">${comment.author}</span>
${marks.map((mark) => html`<span class="c__mark c__mark--${mark.toLowerCase()}">${mark}</span>`)}
${typeof comment.score === 'number'
? html`<span class="c__score">${comment.score} ${Math.abs(comment.score) === 1 ? 'point' : 'points'}</span>`
: ''}
${shortWhen(comment.postedAt)}
${descendantsOf(comment) > 0
? html`<span class="c__hidden">+${descendantsOf(comment)} ${
descendantsOf(comment) === 1 ? 'reply' : 'replies'
}</span>`
: ''}
</summary>
${comment.text ? html`<div class="c__body">${renderMarkdown(comment.text)}</div>` : ''}
${comment.replies.length || comment.moreReplies
? html`<div class="c__replies">
${comment.replies.map((reply) => renderComment(reply, depth + 1))}
${comment.moreReplies
? html`<p class="c__more">${comment.moreReplies} more ${
comment.moreReplies === 1 ? 'reply' : 'replies'
}, on Reddit</p>`
: ''}
</div>`
: ''}
</details>`;
}
/**
* The conversation under the post, where the platform has one.
*
* Everything the first page carried, in the order it was ranked. What is
* missing is what was behind a "load more" following those means going to
* the platform, so they are counted rather than pretended away.
*/
function renderComments(post: Post): Raw {
const comments = post.comments;
if (!comments?.length) return html``;
const threads = comments.length;
const shown = comments.reduce((total, comment) => total + 1 + descendantsOf(comment), 0);
const total = post.commentCount;
return html`<section class="thread" data-platform="${post.platform}">
<header class="thread__head">
<h2 class="thread__title">Comments</h2>
<span class="thread__count">${
total !== undefined && total > shown ? html`${shown} of ${total}` : html`${shown}`
}, in ${threads} ${threads === 1 ? 'thread' : 'threads'}</span>
<button type="button" class="thread__toggle" data-collapsed="false" hidden>Collapse all</button>
</header>
<div class="thread__list">${comments.map((comment) => renderComment(comment, 0))}</div>
${post.moreComments
? html`<p class="thread__more">${post.moreComments} more, behind “load more” on Reddit.</p>`
: ''}
</section>`;
}
@@ -118,7 +248,8 @@ export function renderPost(post: Post): string {
${renderWhen(anchor?.postedAt)}
${originalUrlBlock(post.originalUrl, post.platformLabel)}
</footer>
</article>`;
</article>
${renderComments(post)}`;
const who = post.author.displayName ?? post.author.handle;
return layout(`${who} on ${post.platformLabel}`, body);
+1
View File
@@ -8,6 +8,7 @@ const PROFILE_BASE: Record<PlatformId, string> = {
instagram: 'https://www.instagram.com/',
tiktok: 'https://www.tiktok.com/@',
bluesky: 'https://bsky.app/profile/',
reddit: 'https://www.reddit.com/user/',
};
const TAG_BASE: Partial<Record<PlatformId, string>> = {
+61 -2
View File
@@ -1,5 +1,5 @@
/** The five platforms v1 understands. */
export type PlatformId = 'x' | 'threads' | 'instagram' | 'tiktok' | 'bluesky';
/** The platforms antisocial understands. */
export type PlatformId = 'x' | 'threads' | 'instagram' | 'tiktok' | 'bluesky' | 'reddit';
/**
* Something fetchable that lives on someone else's CDN.
@@ -40,6 +40,24 @@ export type Author = {
avatar?: Asset;
};
/**
* A post that the post being shown is talking about.
*
* Held apart from the segment quoting it rather than folded into it. The
* words and the pictures belong to someone else, and showing them under the
* quoter's name which is what folding them in amounts to tells the
* reader something untrue about who said what.
*/
export type Quoted = {
author: Author;
text?: string;
media: Media[];
/** ISO 8601. */
postedAt?: string;
/** The quoted post's own URL, so it can be opened on its own. */
url?: string;
};
/**
* One post. Usually a whole `Post` is a single segment, but on the platforms
* where people write in chains Bluesky and Threads the author's own
@@ -47,15 +65,44 @@ export type Author = {
* do not.
*/
export type Segment = {
/** Only Reddit gives a post a headline of its own. Everywhere else the
* first words of the body do that job, so this is left unset. */
title?: string;
text?: string;
media: Media[];
/** ISO 8601. */
postedAt?: string;
/** The post this one quotes, where there is one. */
quoted?: Quoted;
/** The post the link actually pointed at. Only meaningful when a thread
* has more than one segment. */
isAnchor?: boolean;
};
/**
* One comment, with the replies that hang off it.
*
* A tree rather than a flat list with depths: collapsing a comment has to
* take everything under it along, and nesting is what makes that free.
*/
export type Comment = {
/** Already prefixed, e.g. `u/someone`. `[deleted]` is left as it came. */
author: string;
text?: string;
/** ISO 8601. */
postedAt?: string;
/** Absent when the platform is still hiding it on a new comment. */
score?: number;
/** The author of the post, replying under it. */
isAuthor?: boolean;
/** Marked by the platform as a moderator or admin comment. */
distinguished?: string;
replies: Comment[];
/** Replies that exist upstream but were not on the page we were given.
* Shown as a count, since following them means going to the platform. */
moreReplies?: number;
};
/**
* The single shape every adapter produces and the renderer consumes. Adding
* a platform means producing one of these; nothing downstream changes.
@@ -73,6 +120,18 @@ export type Post = {
textPosition: 'above' | 'below';
/** In the order they were written. Never empty. */
segments: Segment[];
/**
* The conversation under the post, where the platform has one worth
* showing. Only Reddit fills this in: elsewhere the replies are strangers
* arguing beneath something that was shared for its own sake, but on
* Reddit the thread is usually the point of the link.
*/
comments?: Comment[];
/** Top-level comments the first page did not carry. */
moreComments?: number;
/** What the platform says the total is, which is larger than what we
* show whenever `moreComments` is set. */
commentCount?: number;
};
/** Most platforms have no notion of a chain, so their adapters use this. */
+44 -9
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mediaFromEmbed, selfThread, toPost } from '../src/platforms/bluesky.ts';
import { mediaFromEmbed, quotedFrom, selfThread, toPost } from '../src/platforms/bluesky.ts';
import { fixture } from './helpers.ts';
const URL_ = 'https://bsky.app/profile/example/post/abc';
@@ -45,14 +45,49 @@ test('a quote post with media reaches through the nested embed', () => {
assert.deepEqual(media, [{ kind: 'image', url: 'https://example/i.jpg' }]);
});
test('a quote post shows the media of the post it quotes', () => {
const media = mediaFromEmbed({
$type: 'app.bsky.embed.record#view',
record: {
embeds: [{ $type: 'app.bsky.embed.images#view', images: [{ fullsize: 'https://cdn/q.jpg' }] }],
},
});
assert.deepEqual(media, [{ kind: 'image', url: 'https://cdn/q.jpg' }]);
test('a quote post carries the post it quotes, whose it is included', () => {
const segment = toPost(fixture('bluesky/quote.json'), URL_).segments[0];
const quoted = segment?.quoted;
assert.ok(quoted, 'the quoted post must survive');
assert.equal(quoted?.author.handle, '@cpsc.gov');
assert.equal(quoted?.author.displayName, 'U.S. Consumer Product Safety Commission');
assert.match(quoted?.text ?? '', /Longer videos is great/);
assert.ok(quoted?.postedAt);
// `at://` is not an address anyone can open, so the web one is rebuilt.
assert.equal(quoted?.url, 'https://bsky.app/profile/cpsc.gov/post/3mtzkm3hmo222');
});
test('the quoted post keeps its own media instead of lending it to the quoter', () => {
const segment = toPost(fixture('bluesky/quote.json'), URL_).segments[0];
assert.deepEqual(segment?.media, [], 'the quoter attached nothing');
assert.equal(segment?.quoted?.media.length, 1);
assert.equal(segment?.quoted?.media[0]?.kind, 'video');
});
test('a quote with media of its own nests the quoted record one level deeper', () => {
// `recordWithMedia` puts it at `embed.record.record`; a plain quote puts it
// at `embed.record`. Reading only the first shape finds nothing here.
const quoted = toPost(fixture('bluesky/quote-with-media.json'), URL_).segments[0]?.quoted;
assert.equal(quoted?.author.handle, '@quillmatiq.com');
assert.match(quoted?.text ?? '', /huge value add/);
});
test('a quote pointing at something that is not a post is left out', () => {
// A quote can point at a feed, a list, or a post since deleted or blocked.
// They arrive in the same slot under a different type, carrying none of
// what a post has.
for (const $type of [
'app.bsky.embed.record#viewNotFound',
'app.bsky.embed.record#viewBlocked',
'app.bsky.embed.record#viewDetached',
'app.bsky.feed.defs#generatorView',
]) {
assert.equal(quotedFrom({ $type: 'app.bsky.embed.record#view', record: { $type } }), undefined);
}
assert.equal(quotedFrom(undefined), undefined);
assert.equal(quotedFrom({ $type: 'app.bsky.embed.images#view' }), undefined);
});
// The chain fixture is a real thread. Other people's replies were trimmed to
+35
View File
@@ -0,0 +1,35 @@
{
"post": {
"uri": "at://did:plc:4hodhjl2kposuchzvpiviwps/app.bsky.feed.post/3mrvmbtqn2c24",
"author": {
"handle": "brittanyellich.com",
"displayName": "Brittany Ellich",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:4hodhjl2kposuchzvpiviwps/bafkreidaibgqtw5rstbp6vmjvyv3zata5whjmhw2qerrbeqaq3gy7cfyzq"
},
"record": {
"text": "Thanks to this suggestion, you can now schedule updates to @attie.ai pages to build your own personal newsletter about whatever it is you care about ❤️\n\nattie.ai/@brittanyell...",
"createdAt": "2026-07-30T23:37:54.005Z"
},
"embed": {
"$type": "app.bsky.embed.recordWithMedia#view",
"media": {
"$type": "app.bsky.embed.external#view"
},
"record": {
"record": {
"$type": "app.bsky.embed.record#viewRecord",
"uri": "at://did:plc:xgvzy7ni6ig6ievcbls5jaxe/app.bsky.feed.post/3mrdeskslm222",
"author": {
"handle": "quillmatiq.com",
"displayName": "Anuj Ahooja",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:xgvzy7ni6ig6ievcbls5jaxe/bafkreiaumjzoigdvnldguuxu3ytpzwglqgy3dckzg5cxwqcp5yjychrf4e"
},
"value": {
"text": "I think a huge value add here would be to have these pages periodically query for new info and create new versions of the pages, along with a notification (maybe on Bluesky or over email for visibility). A manual refresh button would be a good start!\n\ncc @jay.bsky.team @pfrazee.com",
"createdAt": "2026-07-23T17:36:09.832Z"
}
}
}
}
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"post": {
"uri": "at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.post/3mtzvbrnbds2q",
"author": {
"handle": "bsky.app",
"displayName": "Bluesky",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:z72i7hdynmk6r22z27h6tvur/bafkreihwihm6kpd6zuwhhlro75p5qks5qtrcu55jp3gddbfjsieiv7wuka"
},
"record": {
"text": "NOW PLAYING: \"Beats To Relax / Be Safe To,\" by @cpsc.gov",
"createdAt": "2026-08-27T03:19:57.683Z"
},
"embed": {
"$type": "app.bsky.embed.record#view",
"record": {
"$type": "app.bsky.embed.record#viewRecord",
"uri": "at://did:plc:wbmw5r5a2j7txv72ggne2uoe/app.bsky.feed.post/3mtzkm3hmo222",
"author": {
"handle": "cpsc.gov",
"displayName": "U.S. Consumer Product Safety Commission",
"avatar": "https://cdn.bsky.app/img/avatar/plain/did:plc:wbmw5r5a2j7txv72ggne2uoe/bafkreic44z27sfbvclf2h2xjmsfbglhyqiobn2kigoayodampyvbiml3m4"
},
"value": {
"text": "Longer videos is great.",
"createdAt": "2026-08-27T00:08:52.368Z"
},
"embeds": [
{
"$type": "app.bsky.embed.video#view",
"playlist": "https://video.bsky.app/watch/did%3Aplc%3Awbmw5r5a2j7txv72ggne2uoe/bafkreia7e6rm7lq6k74ttdlbyx25g37eng3llqm7pex4fheah5voznais4/playlist.m3u8",
"thumbnail": "https://video.bsky.app/watch/did%3Aplc%3Awbmw5r5a2j7txv72ggne2uoe/bafkreia7e6rm7lq6k74ttdlbyx25g37eng3llqm7pex4fheah5voznais4/thumbnail.jpg",
"aspectRatio": {
"height": 1080,
"width": 1920
}
}
]
}
}
}
}
+541
View File
@@ -0,0 +1,541 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "Spay day kinda nervy",
"author": "Background_Round_853",
"subreddit_name_prefixed": "r/aww",
"created_utc": 1786959785,
"selftext": "",
"permalink": "/r/aww/comments/1vqnp2e/spay_day_kinda_nervy/",
"url": "https://www.reddit.com/gallery/1vqnp2e",
"url_overridden_by_dest": "https://www.reddit.com/gallery/1vqnp2e",
"domain": "reddit.com",
"is_self": false,
"is_video": false,
"is_gallery": true,
"over_18": false,
"spoiler": false,
"num_comments": 443,
"score": 40774,
"gallery_data": {
"items": [
{
"is_deleted": false,
"media_id": "6xfm6s4wowjh1",
"id": 1020169008
},
{
"is_deleted": false,
"media_id": "x1o3cr4wowjh1",
"id": 1020169009
},
{
"is_deleted": false,
"media_id": "kury9t4wowjh1",
"id": 1020169010
},
{
"is_deleted": false,
"media_id": "v07ubs4wowjh1",
"id": 1020169011
}
]
},
"media_metadata": {
"v07ubs4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 155,
"x": 108,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=108&crop=smart&auto=webp&s=aa2a1ab3c453178f9ba6b8a06800c0fa923ad570"
},
{
"y": 311,
"x": 216,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=216&crop=smart&auto=webp&s=ec1e4d46b41511ffb3c27e2e331d23469c6be827"
},
{
"y": 461,
"x": 320,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=320&crop=smart&auto=webp&s=22812e3829549a461bdbcb81232a8edf752cac10"
},
{
"y": 922,
"x": 640,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=640&crop=smart&auto=webp&s=56315dc4cf19d12e6f19401792a059f70314ef04"
},
{
"y": 1383,
"x": 960,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=960&crop=smart&auto=webp&s=b706a7d2164462251f869651679c3635e15b6d25"
},
{
"y": 1555,
"x": 1080,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=e5af0cc235a7b2583d8e8a87f7799607e41f1f23"
}
],
"s": {
"y": 1736,
"x": 1205,
"u": "https://preview.redd.it/v07ubs4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=d5f2f69da610bf9a9b5b7cb99f94c21d21d4e75e"
},
"id": "v07ubs4wowjh1"
},
"6xfm6s4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 140,
"x": 108,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=108&crop=smart&auto=webp&s=231c0253d9ffcadcfa085c55264f968e1be7cd38"
},
{
"y": 281,
"x": 216,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=216&crop=smart&auto=webp&s=efb67b41fa2afbde45b4fbf3ff389cb7c98cbe62"
},
{
"y": 417,
"x": 320,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=320&crop=smart&auto=webp&s=4709db023af013805c8a0e4d64fdde867900df2c"
},
{
"y": 834,
"x": 640,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=640&crop=smart&auto=webp&s=2a43ebc507dc45cf578f7e74b62b6d37861d4f18"
},
{
"y": 1252,
"x": 960,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=960&crop=smart&auto=webp&s=f8f82d7392e30f1fb0d449489972ee2cd2e77d1f"
},
{
"y": 1408,
"x": 1080,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=d438c9c25573da6b99ec89d26b373cf676d0a727"
}
],
"s": {
"y": 1572,
"x": 1205,
"u": "https://preview.redd.it/6xfm6s4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=ce8cff5c5c1d347a25c3c4431290fa76637f85b1"
},
"id": "6xfm6s4wowjh1"
},
"kury9t4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 141,
"x": 108,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=108&crop=smart&auto=webp&s=cca8d53fa39835bc14cfcb0b70f2409d2c0b41fd"
},
{
"y": 283,
"x": 216,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=216&crop=smart&auto=webp&s=5c196d8c1c5395b4388548729d779a74d011a6a7"
},
{
"y": 420,
"x": 320,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=320&crop=smart&auto=webp&s=6760b50b63edbf681e13739bbccc17551dbcacba"
},
{
"y": 840,
"x": 640,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=640&crop=smart&auto=webp&s=4cf3bb5bd6c53e6d9a8fff6560258da7fb9de4e1"
},
{
"y": 1261,
"x": 960,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=960&crop=smart&auto=webp&s=7c214c8d1a7a951b891b08d43cf445c28cb6ac20"
},
{
"y": 1418,
"x": 1080,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=4eca14b69a68d05f78a5c6319867b4102fa3abfb"
}
],
"s": {
"y": 1583,
"x": 1205,
"u": "https://preview.redd.it/kury9t4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=24c97654ddd1d3bee61788a965223a9e40d92d6e"
},
"id": "kury9t4wowjh1"
},
"x1o3cr4wowjh1": {
"status": "valid",
"e": "Image",
"m": "image/jpg",
"p": [
{
"y": 80,
"x": 108,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=108&crop=smart&auto=webp&s=8a3211796cdf827ccdc39d76ff9aab299c4cbe2f"
},
{
"y": 160,
"x": 216,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=216&crop=smart&auto=webp&s=52c19a8c35965fccd08e4aaa7bb22f9aae22549e"
},
{
"y": 237,
"x": 320,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=320&crop=smart&auto=webp&s=c54e14e1989b0c1a67708fda3fe611da15f52414"
},
{
"y": 474,
"x": 640,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=640&crop=smart&auto=webp&s=4b7d4b60bb388c485024efe867466f6e5aba6fad"
},
{
"y": 711,
"x": 960,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=960&crop=smart&auto=webp&s=b0e46c04be74d31c5b00c0a704638888a4ca6781"
},
{
"y": 800,
"x": 1080,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=1080&crop=smart&auto=webp&s=c9bb5e091d769c8ec1360a83b6164117406641c8"
}
],
"s": {
"y": 893,
"x": 1205,
"u": "https://preview.redd.it/x1o3cr4wowjh1.jpg?width=1205&format=pjpg&auto=webp&s=20fbd865e429feb527bddb0b7f4bed3fc3281075"
},
"id": "x1o3cr4wowjh1"
}
}
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Background_Round_853",
"body": "https://preview.redd.it/d1m4kf45pwjh1.jpeg?width=1206&format=pjpg&auto=webp&s=6ccd095185d203c6569514e4b0bf93ed9de3ed2c\n\nDone ✅✅ she looks DEVASTATED",
"created_utc": 1786959888,
"score": 6583,
"score_hidden": false,
"is_submitter": true,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Fritzkreig",
"body": "Ah, may your lady and you share mutual joy for the years to come!",
"created_utc": 1786960145,
"score": 943,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "malk600",
"body": "She's coming off anaesthesia, idk what the SOC is in your country, but kitteh would typically get dexmedetomidine + opioid + something like ketamine. Vets will typically revert dexmedetomidine w/ atipamezol, which is about as mild and pleasant as being woken up by a swift kick in the nuts. The cat is just tired, confused, restless (it's possible she's going to be woozy and tired as hell but won't be able to sleep) and overall feels like a person would feel after doing a heavy night of things that are supposed to stay in Vegas.\n\nTake good care of her!",
"created_utc": 1786961915,
"score": 1298,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "teadazed",
"body": "Yes, I showed up to collect my two (brother and sister cats) and commented on their weirdass pupils. The nurse said fondly \"yeah... that's from all the drugs we've given them\".\nThey were both batting invisible butterflies the rest of the evening.",
"created_utc": 1786966670,
"score": 449,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "rocket_randall",
"body": "It's been a while since we had ours fixed, but we opted for a slow release pain killer that would keep them comfy for ~3 days after surgery while they healed. Of course our lunatics decided that once they were home and feeling no pain that it was time to lose their minds and nothing on earth could stop them running around and crashing into things. There was a bit of a scare after our little guy crashed into something and our daughter saw what looked like an eye injury, so off we went to the emergency vet just to be told that there was no injury, it was just the lubricant that was put on his eyes before surgery breaking up and he was fine. As a small consolation the vet said he was a huge endorphin hit for the staff at that time of night.",
"created_utc": 1786983276,
"score": 28,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "teadazed",
"body": "Oh of course they must have eye drops during surgery, their eyes stay open don't they? It's the right way round to take them in for something that turns out to be nothing.\n\nIt's funny, I also have a collie who unlike the cats did not enjoy the aftermath of her neutering drugs At All, she was a haunted-looking cuddlebug until she could move properly again.",
"created_utc": 1786984556,
"score": 18,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "more",
"data": {
"count": 1,
"id": "p4dtjha"
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Ashkir",
"body": "Some of the funniest things my dog has ever done was after they were waking up form anesthesia. She decided on a new place to potty that day too and to this day, years later, I cant train that spot out of her too 👀😭😂",
"created_utc": 1786975001,
"score": 112,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Winter_Fall_7066",
"body": "My dog was given a small sedative so the vet could witness a limp (he was excited and all over the place despite being in pain). Got home, ex asked “is the dog fucked up?” Dog immediately walks over to Christmas tree and pees on it. ",
"created_utc": 1786986392,
"score": 73,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Constant_Function238",
"body": "In his brain”thanks family for bringing my potty inside.”",
"created_utc": 1786990338,
"score": 28,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Pr0digy_",
"body": "My friend years ago dropped off his mastiff to get neutered and I was the one to pick him up because my friend was working late, he was dopey and groggy but really happy to see me. I took him home and watched him until my friend came home as soon as my friend entered the house the dog growled (nothing crazy) and went and hid behind me it was hilarious. Everything was forgiven with some treats and pets. ",
"created_utc": 1787001797,
"score": 19,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "werewooferer",
"body": "the dog knew who took him, and knew who saved him 🤣",
"created_utc": 1787167461,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 1,
"id": "p4c9qw2"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "chickens_for_laughs",
"body": "I remember that vet telling me to not let her jump onto furniture. Like I could get her to stop. She healed fine and lived to 20!",
"created_utc": 1786979935,
"score": 22,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "cAt_S0fa",
"body": "Lol yes the vet said the same thing to my mother when she got my childhood cat spayed. That night the cat was climbing the curtains...\n",
"created_utc": 1787000485,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 21,
"id": "p49jamx"
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 24,
"id": "p4cqjj6"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Shailo",
"body": "What a precious baby 🥺 those eyes omg. Wishing her a speedy recovery and lots of cuddles and treats in the meantime 💖",
"created_utc": 1786960262,
"score": 667,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "Trenzane",
"body": "I misread it as Spa day and was like ❤️ \n\nThen my brain worked and went ☹️",
"created_utc": 1786962348,
"score": 875,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "klgall1",
"body": "Glad I'm not the only one! I was reading the comments and saw the discussions about all the drugs and was very confused.\n\nI am not awake yet haha.",
"created_utc": 1786969784,
"score": 89,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "Cyber_Mermaid",
"body": "I still thought this said \"spa day\" until I read this comment lol",
"created_utc": 1786985184,
"score": 23,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "more",
"data": {
"count": 8,
"id": "p48kfhn"
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 195,
"id": "p4c6cph"
}
}
]
}
}
]
+102
View File
@@ -0,0 +1,102 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "Ratko Mladic, Murderous Butcher of Bosnia, Dies at 83",
"author": "Knightro829",
"subreddit_name_prefixed": "r/news",
"created_utc": 1787836039,
"selftext": "",
"permalink": "/r/news/comments/1vzthbh/ratko_mladic_murderous_butcher_of_bosnia_dies_at/",
"url": "https://www.nytimes.com/2026/08/27/world/europe/ratko-mladic-dead.html?unlocked_article_code=1.8lA.Wgnd.qCJl7Bw9IdHl&smid=nytcore-ios-share",
"url_overridden_by_dest": "https://www.nytimes.com/2026/08/27/world/europe/ratko-mladic-dead.html?unlocked_article_code=1.8lA.Wgnd.qCJl7Bw9IdHl&smid=nytcore-ios-share",
"domain": "nytimes.com",
"is_self": false,
"is_video": false,
"over_18": false,
"spoiler": false,
"num_comments": 32,
"score": 187
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Knightro829",
"body": "Well, at least Death is getting closer to the mark after the past couple of days…. \n \nEdit: If you have several hours on your hands, go watch a.) The Death of Yugoslavia, a six-part documentary that aired on BBC in 1995-1996 (all episodes available on YouTube), and b.) PBS Frontlines “The Trial of Ratko Mladic”, also available on YouTube.",
"created_utc": 1787836109,
"score": 1,
"score_hidden": true,
"is_submitter": true,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "HungryCurrency8481",
"body": "Dolly Parton, Tim Curry, Ratko Mladic - what a trio ",
"created_utc": 1787836074,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "kataiga",
"body": "Unfortunately death also got Yayoi Kusama last night…",
"created_utc": 1787836540,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "RhoOfFeh",
"body": "He wasn't 80. I am holding out for completion of this deal.",
"created_utc": 1787836843,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "SheikhMahdeek",
"body": "See? Bad people live to ripe old age too",
"created_utc": 1787836434,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
]
+351
View File
@@ -0,0 +1,351 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "What's a healthy food that pleases the taste buds too?",
"author": "Weary_Discipline_178",
"subreddit_name_prefixed": "r/AskReddit",
"created_utc": 1787833594,
"selftext": "",
"permalink": "/r/AskReddit/comments/1vzsjee/whats_a_healthy_food_that_pleases_the_taste_buds/",
"url": "https://www.reddit.com/r/AskReddit/comments/1vzsjee/whats_a_healthy_food_that_pleases_the_taste_buds/",
"domain": "self.AskReddit",
"is_self": true,
"is_video": false,
"over_18": false,
"spoiler": false,
"num_comments": 127,
"score": 94
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "manny221122",
"body": "greek yogurt with berries, honey and a little granola 😭 it tastes suspiciously close to dessert and somehow i get to pretend i have my life together while eating it",
"created_utc": 1787835955,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "more",
"data": {
"count": 1,
"id": "p67it4u"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "CoconutxKitten",
"body": "The vast majority of fruit ",
"created_utc": 1787833703,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Technical_Buy_8198",
"body": "Currently cant get enough of a crunchy green grape. Almost ate an entire pack but had to stop myself. So good",
"created_utc": 1787833833,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "CoconutxKitten",
"body": "I love when theyre crunchy & slightly tart ",
"created_utc": 1787834158,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Ok_Reference_4860",
"body": "Yeppp and so delicious ",
"created_utc": 1787835229,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "deerhuntingdude",
"body": "Grapes are pretty low in fiber but high in sugar. They're good for you, but definitely only in moderation ",
"created_utc": 1787834561,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "random314",
"body": "Mangoes specifically.\n\nAlso watermelon.",
"created_utc": 1787834693,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "CoconutxKitten",
"body": "Watermelon is unhealthy specifically for me because Im allergic 😂",
"created_utc": 1787834743,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "more",
"data": {
"count": 2,
"id": "p67dyiw"
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "AngryBarista",
"body": "Chili",
"created_utc": 1787833749,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "VillagePlayful416",
"body": "good chili is basically a cheat code, you can dump a ton of veg in there and it still tastes like a proper meal\n\n \ni slow cook mine with black beans, capsicum, shredded carrot and sometimes a bit of sweet potato, the smoked paprika does all the heavy lifting\n\n \nmake a huge batch sunday and you're set for the week",
"created_utc": 1787833937,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "NOT_Frank_or_Joe",
"body": "A winter staple for me. I also add beets, cut them up small and cook fully on the side then in to simmer with the rest. \n\nEdit: forgot to add, replace the beef with ground turkey as well.",
"created_utc": 1787834097,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "AngryBarista",
"body": "Every time I make it, i look at my wife and say \"this has no business being as good as it is for how healthy it is. Just packed with protein and fiber and can have minimal fat if you use a lean protein",
"created_utc": 1787834149,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Klutzy-Client",
"body": "But triple the amount of beans in it and we are talking",
"created_utc": 1787836492,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "kitty_swankiss",
"body": "Everything Nuts in moderation 🥜🌰",
"created_utc": 1787833760,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "jefe_gonna_jefe",
"body": "Not me.",
"created_utc": 1787833889,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "BlueEyedMalachi",
"body": "Nice",
"created_utc": 1787833961,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "t1",
"data": {
"author": "Lettuce_Milk",
"body": "Either you got all the nut or none at all 😎",
"created_utc": 1787836058,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
},
{
"kind": "more",
"data": {
"count": 2,
"id": "p67a17t"
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Chicken-picante",
"body": "What about odyssey?\n\nOdyssey deez nutz",
"created_utc": 1787834927,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Perfectenschlag_",
"body": "Boooooo",
"created_utc": 1787836540,
"score": 1,
"score_hidden": true,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 10,
"id": "p677sc7"
}
}
]
}
}
]
+451
View File
@@ -0,0 +1,451 @@
[
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t3",
"data": {
"title": "1957 Ford Fairlane",
"author": "icleanjaxfl",
"subreddit_name_prefixed": "r/oddlysatisfying",
"created_utc": 1787830536,
"selftext": "",
"permalink": "/r/oddlysatisfying/comments/1vzrfkw/1957_ford_fairlane/",
"url": "https://v.redd.it/74hudhx2mwlh1",
"url_overridden_by_dest": "https://v.redd.it/74hudhx2mwlh1",
"domain": "v.redd.it",
"post_hint": "hosted:video",
"is_self": false,
"is_video": true,
"over_18": false,
"spoiler": false,
"num_comments": 109,
"score": 3477,
"secure_media": {
"reddit_video": {
"bitrate_kbps": 2400,
"fallback_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_720.mp4?source=fallback",
"has_audio": false,
"height": 1280,
"width": 720,
"scrubber_media_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_96.mp4",
"dash_url": "https://v.redd.it/74hudhx2mwlh1/DASHPlaylist.mpd?a=1790429193%2CNjQwMTBmMDMxODhjMGViOGUyMjU2ZDE2NGFkNmI2MDU2ZDQ2NmVjNmEzNzg0MTQzNGVkMTU5OGI2ZTgyYTU3ZQ%3D%3D&v=1&f=sd",
"duration": 25,
"hls_url": "https://v.redd.it/74hudhx2mwlh1/HLSPlaylist.m3u8?a=1790429193%2CZjkwZmQwODJiYmRhNGY2NDkyYTMxMDZlYmVhMzQwYWVkYTg0MzMwOWEwYjAyMGZhMzY0MWJmYTIyMmE0OTQ3Zg%3D%3D&v=1&f=sd",
"is_gif": false,
"transcoding_status": "completed"
}
},
"media": {
"reddit_video": {
"bitrate_kbps": 2400,
"fallback_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_720.mp4?source=fallback",
"has_audio": false,
"height": 1280,
"width": 720,
"scrubber_media_url": "https://v.redd.it/74hudhx2mwlh1/CMAF_96.mp4",
"dash_url": "https://v.redd.it/74hudhx2mwlh1/DASHPlaylist.mpd?a=1790429193%2CNjQwMTBmMDMxODhjMGViOGUyMjU2ZDE2NGFkNmI2MDU2ZDQ2NmVjNmEzNzg0MTQzNGVkMTU5OGI2ZTgyYTU3ZQ%3D%3D&v=1&f=sd",
"duration": 25,
"hls_url": "https://v.redd.it/74hudhx2mwlh1/HLSPlaylist.m3u8?a=1790429193%2CZjkwZmQwODJiYmRhNGY2NDkyYTMxMDZlYmVhMzQwYWVkYTg0MzMwOWEwYjAyMGZhMzY0MWJmYTIyMmE0OTQ3Zg%3D%3D&v=1&f=sd",
"is_gif": false,
"transcoding_status": "completed"
}
},
"preview": {
"images": [
{
"source": {
"url": "https://external-preview.redd.it/N245aGFidjJtd2xoMRGGAvg1khFB1AQL8vVunwC_Mb5qnXHCQGxm0j4C5bdR.png?format=pjpg&auto=webp&s=cd60e451633a907b172389c0cd1c09e174ac9f16",
"width": 405,
"height": 720
}
}
]
}
}
}
]
}
},
{
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Head-State-",
"body": "That retractable hardtop transformer mechanism is pure engineering wizardry.",
"created_utc": 1787830965,
"score": 328,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Pretend-Internet-625",
"body": "ya until you have to go and fix it and make it work properly. ",
"created_utc": 1787832356,
"score": 150,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "bigalindahouse",
"body": "Would much rather work on this than today's vehicles",
"created_utc": 1787833724,
"score": 63,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Pretend-Internet-625",
"body": "Well ya I get that but these were a real pain in the ",
"created_utc": 1787833961,
"score": 6,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Brasticus",
"body": "r/redditsniper claims another",
"created_utc": 1787834765,
"score": 21,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Andy_B_Goode",
"body": "Yeah, it's neat, but it also totally looks like one of those things that would break in the first two or three years and most people wouldn't bother fixing",
"created_utc": 1787835341,
"score": 6,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "utukore",
"body": "Same setup was used for the e93 roof. Other than the squeeks and rattles or the slow open/ close time they worked well.",
"created_utc": 1787836411,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "kss1089",
"body": "Everything is a 4 bar mechanism. if it's super complicated, it's multiple 4 bar mechanisms. ",
"created_utc": 1787833936,
"score": 12,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "Tony_Penny",
"body": "Ford Fairlane, rock and roll detective. ",
"created_utc": 1787831095,
"score": 29,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "perflubon",
"body": "One of the best \"worst\" movies ever.",
"created_utc": 1787832767,
"score": 7,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Tony_Penny",
"body": "I absolutely loved that movie as a kid. ",
"created_utc": 1787833553,
"score": 3,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "imamakebaddecisions",
"body": "Booty time, booty time, across the USA, booty time, booty time, hey hey hey!",
"created_utc": 1787833566,
"score": 5,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "[deleted]",
"body": "[removed]",
"created_utc": 1787833134,
"score": 145,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "And covering it for the winter... then uncovering it in the Spring. Getting that \"unwrapping a new gift\" endorphin rush all over again every year.",
"created_utc": 1787834518,
"score": 8,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "zytukin",
"body": "You'd leave it outside over winter???",
"created_utc": 1787834574,
"score": 4,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "I live in Seattle, so snow isnt a factor. Streets are dotted with covered cars in the winter. I guess it depends on location!",
"created_utc": 1787834801,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Flyingdutchman2305",
"body": "?? Isnt there lots of snow in seattle",
"created_utc": 1787835019,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "No. It doesn't snow in Seattle. We don't even have a snow removal budget in the city.\n\nWinter bottoms out at like 40-45 fahrenheit. It just mists, drizzles, gets overcast and grey for six months.",
"created_utc": 1787835128,
"score": 2,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Flyingdutchman2305",
"body": "Huh, my american Geography when it comes to latitude is apparently off\n\n![gif](giphy|QfzMP70zmNQiDf5sGP)",
"created_utc": 1787835286,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Bongressman",
"body": "It snows in Washington state, just not Seattle. We are surrounded by the Cascades and Olympic Mountains. Kind of boxed in and protected.\n\nOur weather closely mirrors London's, but with even less snowfall.",
"created_utc": 1787835622,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": {
"kind": "Listing",
"data": {
"children": [
{
"kind": "t1",
"data": {
"author": "Flyingdutchman2305",
"body": "Never knew, always thought it was one of those typical snowy winter cities",
"created_utc": 1787835875,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "zytukin",
"body": "It's not due to latitude, Seattle is more north than Wyoming, Kansas, etc which get a lot of snow.\n\nI think it has to do with being near the west coast so it gets hit with warm air coming up from the tropics.",
"created_utc": 1787835832,
"score": 1,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
}
]
}
}
}
},
{
"kind": "t1",
"data": {
"author": "its_Raze_7",
"body": "bot",
"created_utc": 1787836203,
"score": 2,
"score_hidden": false,
"is_submitter": false,
"replies": ""
}
}
]
}
}
}
},
{
"kind": "more",
"data": {
"count": 1,
"id": "p676rzl"
}
}
]
}
}
]
+128
View File
@@ -0,0 +1,128 @@
{
"id_str": "2086902906171605466",
"text": "NEW: Joey McGuire tells @Brett_McMurphy Texas Tech can't find future games, with Texas A&amp;M, USC, NC State and Mississippi State saying no or canceling series❌\n\n\"Were talking to everybody and anybody. So far, everybodys told us no.\"\n\nhttps://t.co/rEGx9JN5pJ https://t.co/QdJhOVu4En",
"display_text_range": [
0,
262
],
"entities": {
"urls": [
{
"url": "https://t.co/rEGx9JN5pJ",
"expanded_url": "https://www.on3.com/news/joey-mcguire-on-texas-techs-villain-era-were-the-most-hated-team-in-college-football/"
}
]
},
"created_at": "2026-08-10T19:50:00.000Z",
"user": {
"screen_name": "On3",
"name": "On3",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1414989749203390470/D2B25n0r_normal.jpg"
},
"mediaDetails": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/HPYnDNPW0AAJd6h.jpg",
"original_info": {
"focus_rects": [
{
"h": 605,
"w": 1080,
"x": 0,
"y": 609
},
{
"h": 1080,
"w": 1080,
"x": 0,
"y": 270
},
{
"h": 1231,
"w": 1080,
"x": 0,
"y": 119
},
{
"h": 1350,
"w": 675,
"x": 169,
"y": 0
},
{
"h": 1350,
"w": 1080,
"x": 0,
"y": 0
}
],
"height": 1350,
"width": 1080
}
}
],
"quoted_tweet": {
"id_str": "2086832880676716740",
"text": "NEW: Texas Tech's Joey McGuire tells @Brett_McMurphy the Red Raiders are embracing the villain role🔥\n\n\"Were the most hated team in college football. And I absolutely love it,\" McGuire told his team in a meeting.\n\nStory: https://t.co/rEGx9JN5pJ https://t.co/q7m39MOMNo",
"display_text_range": [
0,
245
],
"entities": {
"urls": [
{
"url": "https://t.co/rEGx9JN5pJ",
"expanded_url": "https://www.on3.com/news/joey-mcguire-on-texas-techs-villain-era-were-the-most-hated-team-in-college-football/"
}
]
},
"created_at": "2026-08-10T15:11:44.000Z",
"user": {
"screen_name": "On3",
"name": "On3",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1414989749203390470/D2B25n0r_normal.jpg"
},
"mediaDetails": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/HPXqebKWkAA5gvA.jpg",
"original_info": {
"focus_rects": [
{
"h": 630,
"w": 1125,
"x": 0,
"y": 0
},
{
"h": 630,
"w": 630,
"x": 75,
"y": 0
},
{
"h": 630,
"w": 553,
"x": 114,
"y": 0
},
{
"h": 630,
"w": 315,
"x": 233,
"y": 0
},
{
"h": 630,
"w": 1200,
"x": 0,
"y": 0
}
],
"height": 630,
"width": 1200
}
}
]
}
}
+70
View File
@@ -0,0 +1,70 @@
{
"id_str": "2092384141488620017",
"text": "The SEC, as expected, adopts a ban on professional players returning to college, which also includes basketball.",
"display_text_range": [
0,
112
],
"created_at": "2026-08-25T22:50:28.000Z",
"user": {
"screen_name": "RossDellenger",
"name": "Ross Dellenger",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1174672001958649861/m2N_Dbim_normal.jpg"
},
"quoted_tweet": {
"id_str": "2092383884872765473",
"text": "Following meetings with the Presidents, Chancellors, and Athletics Directors of the Southeastern Conference, the SEC will enforce the following policy: https://t.co/LohWnb7G1J",
"display_text_range": [
0,
151
],
"created_at": "2026-08-25T22:49:27.000Z",
"user": {
"screen_name": "SEC",
"name": "Southeastern Conference",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1807664314687299584/qhj7cnXy_normal.jpg"
},
"mediaDetails": [
{
"type": "photo",
"media_url_https": "https://pbs.twimg.com/media/HQmj_lxW8AAlFmc.jpg",
"original_info": {
"focus_rects": [
{
"h": 605,
"w": 1080,
"x": 0,
"y": 742
},
{
"h": 1080,
"w": 1080,
"x": 0,
"y": 360
},
{
"h": 1231,
"w": 1080,
"x": 0,
"y": 209
},
{
"h": 1440,
"w": 720,
"x": 0,
"y": 0
},
{
"h": 1440,
"w": 1080,
"x": 0,
"y": 0
}
],
"height": 1440,
"width": 1080
}
}
]
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"id_str": "2092435281869738141",
"text": "Deacon Kevin Barron of the Catholic Community of Buffalo North led the prayer service on Tuesday for Mayich. In an interview with @azcentral, Barron said that Maywich suffered a “cardiac event” and is currently in a coma.",
"display_text_range": [
0,
221
],
"created_at": "2026-08-26T02:13:41.000Z",
"user": {
"screen_name": "MikeMcMahonCHN",
"name": "Mike McMahon",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2068376149747449856/oqDq3qs4_normal.jpg"
},
"quoted_tweet": {
"id_str": "2092384930034548928",
"text": "Matthew Mayich, a sophomore defenseman, is the player hospitalized. There was a virtual prayer service held today, shared on social media, in which Mayichs cousin spoke. I didnt want to share the players name before we were sure the players family was OK with it being shared.",
"display_text_range": [
0,
280
],
"created_at": "2026-08-25T22:53:36.000Z",
"user": {
"screen_name": "MikeMcMahonCHN",
"name": "Mike McMahon",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/2068376149747449856/oqDq3qs4_normal.jpg"
}
}
}
+66
View File
@@ -0,0 +1,66 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { renderMarkdown } from '../src/render/markdown.ts';
const md = (text: string): string => String(renderMarkdown(text));
test('markup a commenter typed is text, not markup', () => {
const out = md('<script>alert(1)</script> & "quoted"');
assert.ok(!out.includes('<script>'));
assert.match(out, /&lt;script&gt;/);
assert.match(out, /&amp;/);
});
test('only http and https become links', () => {
assert.match(md('[go](https://example.com/a)'), /<a href="https:\/\/example\.com\/a"/);
// The label is still shown; it is only the link that is refused.
const dangerous = md('[go](javascript:alert(1))');
assert.ok(!dangerous.includes('<a '));
assert.match(dangerous, /\[go\]/);
});
test('a bare URL is linked without swallowing the sentence it ends', () => {
const out = md('see https://example.com/x.');
assert.match(out, /href="https:\/\/example\.com\/x"/);
assert.ok(out.endsWith('.</p>'), `trailing full stop should stay outside the link: ${out}`);
});
test('an ampersand in a link target survives as one', () => {
const out = md('[x](https://example.com/?a=1&b=2)');
assert.match(out, /href="https:\/\/example\.com\/\?a=1&amp;b=2"/);
});
test('a quote is a block of its own, so the reply is not read as part of it', () => {
const out = md('> they said this\n\nand I disagree');
assert.match(out, /<blockquote><p>they said this<\/p><\/blockquote><p>and I disagree<\/p>/);
});
test('quoting a quote keeps both levels', () => {
assert.match(md('> > deep\n> shallow'), /<blockquote><blockquote>/);
});
test('emphasis does not fire inside a word', () => {
// `snake_case_names` are ordinary in the subreddits this will be pointed at.
assert.equal(md('some_variable_name'), '<p>some_variable_name</p>');
assert.match(md('_yes_'), /<em>yes<\/em>/);
});
test('code is left exactly as typed', () => {
assert.match(md('`a < b && c`'), /<code>a &lt; b &amp;&amp; c<\/code>/);
assert.match(md('```\n<b>not bold</b>\n```'), /<pre><code>&lt;b&gt;not bold&lt;\/b&gt;<\/code><\/pre>/);
});
test('subreddit and user references link back to reddit', () => {
assert.match(md('over in r/aww'), /href="https:\/\/www\.reddit\.com\/r\/aww"/);
assert.match(md('ask u/someone'), /href="https:\/\/www\.reddit\.com\/u\/someone"/);
});
test('lists survive, both kinds', () => {
assert.match(md('- one\n- two'), /<ul><li>one<\/li><li>two<\/li><\/ul>/);
assert.match(md('1. one\n2. two'), /<ol><li>one<\/li><li>two<\/li><\/ol>/);
});
test('a single newline inside a paragraph is a line break, a blank line is a new one', () => {
assert.equal(md('one\ntwo'), '<p>one<br>two</p>');
assert.equal(md('one\n\ntwo'), '<p>one</p><p>two</p>');
});
+170
View File
@@ -0,0 +1,170 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { commentsFrom, mediaFromLink, toPost, treeFromDepths } from '../src/platforms/reddit.ts';
import { reddit } from '../src/platforms/reddit.ts';
import { originalUrlFor } from '../src/platforms/index.ts';
import { fixture } from './helpers.ts';
const URL_ = 'https://www.reddit.com/r/aww/comments/abc123/a_post/';
test('a text post is its title, and carries no media', () => {
const post = toPost(fixture('reddit/self.json'), URL_);
assert.equal(post.platform, 'reddit');
assert.equal(post.author.handle, 'r/AskReddit');
assert.match(post.author.displayName ?? '', /^u\//);
assert.equal(post.segments[0]?.title, "What's a healthy food that pleases the taste buds too?");
assert.deepEqual(post.segments[0]?.media, []);
assert.ok(post.segments[0]?.postedAt);
});
test('a gallery keeps every picture, in the order the post arranged them', () => {
const link = fixture<[{ data: { children: Array<{ data: Record<string, unknown> }> } }]>(
'reddit/gallery.json',
)[0].data.children[0]?.data as Parameters<typeof mediaFromLink>[0];
const media = mediaFromLink(link);
const ids = (link.gallery_data?.items ?? []).map((item) => item.media_id);
assert.equal(media.length, ids.length);
assert.ok(media.every((m) => m.kind === 'image'));
// The pictures live in `media_metadata`, keyed and unordered; the order is
// only in `gallery_data`, so joining the two is the whole job.
media.forEach((item, index) => assert.ok(item.url.includes(String(ids[index]))));
assert.ok(media.every((m) => m.width && m.height));
});
test('a silent video is served as the plain MP4, with a real image for a poster', () => {
const media = toPost(fixture('reddit/video.json'), URL_).segments[0]?.media ?? [];
assert.equal(media.length, 1);
const video = media[0];
assert.equal(video?.kind, 'video');
assert.match(video?.url ?? '', /\.mp4/);
assert.ok(video?.kind === 'video' && video.poster);
// Not the scrubber file, which is itself an MP4 and would render nothing.
assert.ok(video?.kind === 'video' && !video.poster?.url.endsWith('.mp4'));
assert.equal(video?.kind === 'video' ? video.hls : undefined, undefined);
});
test('a video with sound is the HLS playlist, because the MP4 has no audio track', () => {
const media = mediaFromLink({
secure_media: {
reddit_video: {
fallback_url: 'https://v.redd.it/abc/CMAF_720.mp4?source=fallback',
hls_url: 'https://v.redd.it/abc/HLSPlaylist.m3u8',
has_audio: true,
width: 1920,
height: 1080,
duration: 42,
},
},
});
assert.deepEqual(media, [
{
kind: 'video',
url: 'https://v.redd.it/abc/HLSPlaylist.m3u8',
hls: true,
direct: true,
width: 1920,
height: 1080,
durationSec: 42,
},
]);
});
test('a link post keeps the destination, since it is the whole content of the post', () => {
const post = toPost(fixture('reddit/link.json'), URL_);
assert.match(post.segments[0]?.text ?? '', /^https:\/\/www\.nytimes\.com\//);
});
test('a crosspost shows what it is crossposting', () => {
const media = mediaFromLink({
is_self: false,
crosspost_parent_list: [
{ url_overridden_by_dest: 'https://i.redd.it/inner.jpg', post_hint: 'image' },
],
});
assert.deepEqual(media, [{ kind: 'image', url: 'https://i.redd.it/inner.jpg' }]);
});
test('comments come back as a tree, with the counts of what is missing', () => {
const post = toPost(fixture('reddit/gallery.json'), URL_);
assert.equal(post.comments?.length, 3);
assert.ok((post.moreComments ?? 0) > 0, 'the "more comments" node should be counted, not dropped');
assert.equal(post.commentCount, 443);
const first = post.comments?.[0];
assert.equal(first?.author, 'u/Background_Round_853');
assert.equal(first?.isAuthor, true, 'the poster replying under their own post');
assert.equal(first?.score, 6583);
assert.ok((first?.replies.length ?? 0) > 0);
assert.ok(first?.replies.every((reply) => Array.isArray(reply.replies)));
});
test('a score the platform is still hiding is left off rather than guessed at', () => {
const { comments } = commentsFrom({
data: {
children: [
{ kind: 't1', data: { author: 'a', body: 'new', score: 1, score_hidden: true, replies: '' } },
{ kind: 't1', data: { author: 'b', body: 'older', score: 42, score_hidden: false, replies: '' } },
],
},
});
assert.equal(comments[0]?.score, undefined);
assert.equal(comments[1]?.score, 42);
});
test('a deleted commenter keeps the platform\'s own word for it', () => {
const { comments } = commentsFrom({
data: { children: [{ kind: 't1', data: { author: '[deleted]', body: '[removed]', replies: '' } }] },
});
assert.equal(comments[0]?.author, '[deleted]');
});
test('an empty reply listing is the string "", not an object', () => {
// Reddit says "no replies" with an empty string, which is the shape most
// likely to be read as a listing and crash the walk.
const { comments } = commentsFrom({
data: { children: [{ kind: 't1', data: { author: 'a', body: 'x', replies: '' } }] },
});
assert.deepEqual(comments[0]?.replies, []);
});
test('a redd.it share code is rebuilt, since the rewrite drops the host', () => {
assert.equal(originalUrlFor(reddit, 'abc123', ''), 'https://redd.it/abc123');
assert.equal(
originalUrlFor(reddit, 'r/aww/comments/abc123/a_post/', '?share_id=xyz&utm_source=share'),
'https://www.reddit.com/r/aww/comments/abc123/a_post/',
);
});
test('reddit links route to the adapter, and its media hosts do not', () => {
assert.ok(reddit.matchesHost('www.reddit.com'));
assert.ok(reddit.matchesHost('old.reddit.com'));
assert.ok(reddit.matchesHost('redd.it'));
assert.ok(!reddit.matchesHost('bsky.app'));
});
test('the page fallback rebuilds nesting from the depth on each comment', () => {
// Reddit renders the tree flat, so depth is the only thing saying what
// replies to what.
const tree = treeFromDepths([
{ depth: 0, author: 'a', score: 5, created: '', text: 'first' },
{ depth: 1, author: 'b', score: 4, created: '', text: 'under first' },
{ depth: 2, author: 'c', score: 3, created: '', text: 'under b' },
// Back up two levels: this belongs to `first`, not to `c`.
{ depth: 1, author: 'd', score: 2, created: '', text: 'also under first' },
{ depth: 0, author: 'e', score: 1, created: '', text: 'second' },
]);
assert.equal(tree.length, 2);
assert.equal(tree[0]?.replies.length, 2);
assert.equal(tree[0]?.replies[0]?.replies[0]?.text, 'under b');
assert.equal(tree[0]?.replies[1]?.text, 'also under first');
assert.deepEqual(tree[1]?.replies, []);
});
test('a comment the page gave no text for is dropped rather than shown empty', () => {
assert.deepEqual(treeFromDepths([{ depth: 0, author: 'a', score: 1, created: '', text: '' }]), []);
});
+129
View File
@@ -108,3 +108,132 @@ test('a failure still hands the link back', () => {
assert.ok(page.includes('Open on TikTok'));
assert.ok(page.includes('verification puzzle'));
});
function redditPost(overrides: Partial<Post> = {}): Post {
return post({
platform: 'reddit',
platformLabel: 'Reddit',
originalUrl: 'https://www.reddit.com/r/aww/comments/abc/a/',
author: { handle: 'r/aww' },
textPosition: 'above',
segments: oneSegment({ title: 'A headline', media: [] }),
...overrides,
});
}
test('a post with no comments renders no comment section at all', () => {
assert.ok(!renderPost(redditPost()).includes('class="thread"'));
assert.ok(!renderPost(post()).includes('class="thread"'));
});
test('comments nest, so collapsing one takes its replies with it', () => {
const page = renderPost(redditPost({
comments: [
{
author: 'u/a',
text: 'top',
replies: [{ author: 'u/b', text: 'nested', replies: [] }],
},
],
}));
// The reply is inside the parent's <details>, not a sibling of it.
const parent = page.slice(page.indexOf('<details class="c"'));
const closing = parent.indexOf('</details>');
assert.ok(parent.slice(0, closing).includes('nested'), 'a reply must live inside its parent');
assert.ok(page.includes('<details class="c" open'), 'threads start expanded');
});
test('a comment says how much a fold would hide', () => {
const page = renderPost(redditPost({
comments: [
{
author: 'u/a',
text: 'top',
replies: [
{ author: 'u/b', text: 'one', replies: [{ author: 'u/c', text: 'two', replies: [] }] },
],
},
],
}));
assert.ok(page.includes('+2 replies'), 'the whole subtree is counted, not just direct replies');
});
test('comment text is escaped, and its markdown is rendered', () => {
const page = renderPost(redditPost({
comments: [{ author: 'u/a', text: '**bold** <img src=x onerror=alert(1)>', replies: [] }],
}));
assert.ok(!page.includes('<img src=x'), 'markup in a comment must not survive');
assert.ok(page.includes('<strong>bold</strong>'));
});
test('what the first page did not carry is counted rather than pretended away', () => {
const page = renderPost(redditPost({
comments: [{ author: 'u/a', text: 'x', replies: [], moreReplies: 3 }],
moreComments: 40,
commentCount: 443,
}));
assert.ok(page.includes('3 more replies, on Reddit'));
assert.ok(page.includes('40 more, behind'));
assert.ok(page.includes('1 of 443'));
});
function quoting(quoted: Post['segments'][number]['quoted']): Post {
return post({
platform: 'x',
platformLabel: 'X',
textPosition: 'above',
segments: oneSegment({ text: 'look at this', media: [], quoted }),
});
}
test('a quoted post is drawn with its own author, not folded under the quoter', () => {
const page = quoting({
author: { handle: '@other', displayName: 'Someone Else' },
text: 'the original words',
media: [],
url: 'https://x.com/other/status/9',
});
const html_ = renderPost(page);
assert.ok(html_.includes('class="quote"'));
assert.ok(html_.includes('@other'), 'the quoted handle must be on the page');
assert.ok(html_.includes('Someone Else'));
assert.ok(html_.includes('the original words'));
assert.ok(html_.includes('href="https://x.com/other/status/9"'));
});
test('a quoted post with no quote renders no block', () => {
assert.ok(!renderPost(quoting(undefined)).includes('class="quote"'));
});
test("the quoted post's media is proxied like any other", () => {
const html_ = renderPost(quoting({
author: { handle: '@other' },
media: [{ kind: 'image', url: 'https://pbs.twimg.com/q.jpg' }],
}));
assert.ok(!html_.includes('https://pbs.twimg.com/q.jpg'), 'upstream URLs must not reach the page');
assert.ok(html_.includes('src="/m/'));
});
test('a quoted post is separated from the words that quote it', () => {
const html_ = renderPost(quoting({
author: { handle: '@other' },
text: 'quoted words',
media: [],
}));
// The quoter's text closes before the block opens, so the two can never
// read as one paragraph by the same person.
assert.ok(html_.indexOf('look at this') < html_.indexOf('class="quote"'));
assert.ok(html_.indexOf('class="quote"') < html_.indexOf('quoted words'));
});
test('markup in a quoted post is escaped like any other stranger\'s text', () => {
const html_ = renderPost(quoting({
author: { handle: '<img src=x onerror=alert(1)>' },
text: '<script>alert(1)</script>',
media: [],
}));
assert.ok(!html_.includes('<script>alert(1)</script>'));
assert.ok(!html_.includes('<img src=x'));
});
+110 -11
View File
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { mediaFromDetails, toPost } from '../src/platforms/x.ts';
import { mediaFromDetails, quotedFrom, toPost } from '../src/platforms/x.ts';
import { fixture } from './helpers.ts';
const URL_ = 'https://x.com/example/status/1';
@@ -50,20 +50,119 @@ test('a video picks the highest-bitrate mp4 and ignores the streaming variants',
]);
});
test('a quote post shows the media of the post it quotes', () => {
// The quote itself carries none; without this the page is text and nothing
// else, which is exactly the thing the reader wanted to see.
test('a quote post carries the post it quotes, whose it is included', () => {
// Someone continuing their own thought from an earlier post. Without the
// quoted half on the page the remaining half says nothing.
const post = toPost(fixture('x/quote-text.json'), URL_);
const quoted = post.segments[0]?.quoted;
assert.ok(quoted, 'the quoted post must survive');
assert.equal(quoted?.author.handle, '@MikeMcMahonCHN');
assert.ok(quoted?.author.displayName);
assert.match(quoted?.text ?? '', /Matthew Mayich/);
assert.ok(quoted?.postedAt);
// No permalink in the payload, so it is rebuilt from the handle and the id.
assert.equal(quoted?.url, 'https://x.com/MikeMcMahonCHN/status/2092384930034548928');
});
test('the quoted post keeps its own pictures instead of lending them to the quoter', () => {
const post = toPost(fixture('x/quote-photo.json'), URL_);
assert.deepEqual(post.segments[0]?.media, [], 'the quoter attached nothing');
assert.equal(post.segments[0]?.quoted?.media.length, 1);
assert.equal(post.segments[0]?.quoted?.media[0]?.kind, 'image');
});
test('media on both sides stays on the side it came from', () => {
// This is the case the old either-or could not represent at all: it showed
// the quoter's picture and silently dropped the one being talked about.
const segment = toPost(fixture('x/quote-both.json'), URL_).segments[0];
assert.equal(segment?.media.length, 1);
assert.equal(segment?.quoted?.media.length, 1);
assert.notEqual(segment?.media[0]?.url, segment?.quoted?.media[0]?.url);
});
test('a post quoting nothing has no quoted post', () => {
assert.equal(toPost(fixture('x/photo.json'), URL_).segments[0]?.quoted, undefined);
assert.equal(quotedFrom(undefined), undefined);
// A quoted post X will not describe is nothing to show.
assert.equal(quotedFrom({ text: 'orphaned' }), undefined);
});
test('the shortlink X staples to a quote post is not shown', () => {
// The quoted post is right there on the page; a t.co pointing at it is
// noise, which is why X hides it too. `display_text_range` says where it
// starts, and keeps a link the author put there deliberately.
const both = toPost(fixture('x/quote-both.json'), URL_).segments[0];
// Two links arrive: one the author wrote, one X appended pointing at the
// quoted post. Exactly the second goes.
assert.equal((both?.text?.match(/https?:\/\//g) ?? []).length, 1, "the author's own link stays");
assert.match(both?.text ?? '', /on3\.com/);
assert.ok(!both?.text?.includes('QdJhOVu4En'));
const photo = toPost(fixture('x/quote-photo.json'), URL_).segments[0];
assert.ok(!photo?.quoted?.text?.includes('t.co'), 'and the same on the quoted post');
});
test('a t.co stands aside for the address it stands in for', () => {
// Left alone the page says `t.co/rEGx9JN5pJ`, which tells the reader
// nothing and sends them through X's click tracker to find out.
const segment = toPost(fixture('x/quote-both.json'), URL_).segments[0];
assert.ok(!segment?.text?.includes('t.co/'), `still shortened: ${segment?.text}`);
assert.match(segment?.text ?? '', /on3\.com/);
assert.match(segment?.quoted?.text ?? '', /on3\.com/);
});
test('a shortlink the payload does not explain is left as it is', () => {
const post = toPost(
{
text: 'look at this',
text: 'see https://t.co/unknown1 and https://t.co/known123',
user: { screen_name: 'someone' },
mediaDetails: [],
quoted_tweet: {
mediaDetails: [{ type: 'photo', media_url_https: 'https://pbs.twimg.com/q.jpg' }],
},
entities: { urls: [{ url: 'https://t.co/known123', expanded_url: 'https://example.com/real' }] },
},
URL_,
);
assert.equal(post.segments[0]?.media.length, 1);
assert.equal(post.segments[0]?.media[0]?.url, 'https://pbs.twimg.com/q.jpg?name=orig');
assert.equal(post.segments[0]?.text, 'see https://t.co/unknown1 and https://example.com/real');
});
test('an expansion that is not an http address is refused', () => {
const post = toPost(
{
text: 'https://t.co/abc',
user: { screen_name: 'someone' },
entities: { urls: [{ url: 'https://t.co/abc', expanded_url: 'javascript:alert(1)' }] },
},
URL_,
);
assert.equal(post.segments[0]?.text, 'https://t.co/abc');
});
test('the visible range is applied before the entities are decoded', () => {
// The indices are into the escaped text, where `&amp;` is five characters.
// Decoding first shifts everything after it and truncates the tail.
const post = toPost(
{
text: 'Tom &amp; Jerry https://t.co/xxx',
display_text_range: [0, 15],
user: { screen_name: 'someone' },
},
URL_,
);
assert.equal(post.segments[0]?.text, 'Tom & Jerry');
});
test('escaped characters X hands back are decoded, not shown as entities', () => {
// The syndication payload arrives pre-escaped; everything downstream
// escapes again on the way out, so leaving these puts `&amp;` on screen.
const post = toPost(
{
text: 'Tom &amp; Jerry &lt;3 &quot;quoted&quot;',
user: { screen_name: 'someone' },
quoted_tweet: { text: 'me &amp; you', user: { screen_name: 'other' }, id_str: '9' },
},
URL_,
);
assert.equal(post.segments[0]?.text, 'Tom & Jerry <3 "quoted"');
assert.equal(post.segments[0]?.quoted?.text, 'me & you');
});