NGU-Web/server/src/feeds.js
Aidan Dona f1a0b06ac2 Page management, step 3: section types with their own settings; the front page as sections
Migration 083 gives the section types that need more than blocks their
own tables (hero, slides, countdown, stats, paths, featured cards, the
Community blog's slots, pinned posts and feeds) and turns the front page
into Home's sections: the hero, then its bands in order. Any section can
be hidden. The Front page editor, its tables and the Community page's
are gone; /api/front-page and /api/community-blog fold into the page's
sections (sectionData.js). The admin engine reads and writes a child
collection's own side tables and gated nested collections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:34:56 -05:00

188 lines
7.2 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (section_feeds, 083), for its "newest community posts".
A Substack's feed is https://<name>.substack.com/feed.
Each feed is fetched through linkPreview.js's safeGet, so it gets
the same public-address checks, timeout and size cap as a link
preview. Results are kept in memory for CACHE_MS. A feed that
fails keeps serving what it last returned, and one that has never
worked contributes nothing: the section shows the pinned posts
and whatever the other feeds have, rather than an error.
Items come back as plain data: title, url, excerpt, image,
published (ISO), source. Only http(s) links and https images are
kept, so a feed can't put a javascript: link or a mixed-content
image on the page.
═══════════════════════════════════════════════════════════════ */
import { decodeEntities, elements, innerOf, openTags, safeGet } from "./linkPreview.js";
const CACHE_MS = 30 * 60 * 1000;
const MAX_FEED_BYTES = 3 * 1024 * 1024;
const MAX_ITEMS_PER_FEED = 20;
const EXCERPT_CHARS = 300;
const cache = new Map(); // url → { at, feed }
/* ── Parsing ───────────────────────────────────────────────── */
function unwrap(text) {
return text.replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1");
}
/* The text inside the first <tag>…</tag>, CDATA unwrapped. Tag
names may carry a namespace prefix (content:encoded). Scanned with
indexOf, not a regex: the feed is someone else's (see "Scanning
markup" in linkPreview.js). */
function inner(xml, tag) {
const text = innerOf(xml, tag);
return text == null ? null : unwrap(text);
}
function attrOf(xml, tag, name, where = () => true) {
for (const el of openTags(xml, tag, 50)) {
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
if (value && where(el)) return value[2] ?? value[3];
}
return null;
}
// Enough of a body or summary to make an excerpt from, so the tag
// strip and entity decoding never see more than this.
const PLAIN_SCAN = 20_000;
function plain(html) {
if (!html) return null;
// Tags stripped both before and after decoding: a description is
// often HTML written as entities (&lt;p&gt;).
const strip = (s) => s.replace(/<[^>]*>/g, " ");
const text = decodeEntities(strip(decodeEntities(strip(html.slice(0, PLAIN_SCAN)))));
if (!text) return null;
return text.length > EXCERPT_CHARS ? `${text.slice(0, EXCERPT_CHARS).trimEnd()}…` : text;
}
function safeUrl(raw, base, { httpsOnly = false } = {}) {
if (!raw) return null;
try {
const url = new URL(decodeEntities(raw), base);
if (url.protocol === "https:" || (!httpsOnly && url.protocol === "http:")) return url.toString();
} catch {
/* not a URL */
}
return null;
}
function isoDate(raw) {
if (!raw) return null;
const date = new Date(raw.trim());
return Number.isNaN(date.getTime()) ? null : date.toISOString();
}
function firstImage(html) {
if (!html) return null;
for (const tag of openTags(html, "img", 20)) {
const src = tag.match(/\bsrc\s*=\s*["']([^"']+)["']/i)?.[1];
if (src) return src;
}
return null;
}
function parseFeed(xml, feedUrl) {
// The root element is near the top; nothing needs the rest for this.
const top = xml.slice(0, 8192);
const root = openTags(top, "feed", 1)[0] ?? "";
const isAtom = /xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(root) && openTags(top, "rss", 1).length === 0;
const tag = isAtom ? "entry" : "item";
// The channel's own title is the one before the first item.
const firstItem = xml.toLowerCase().indexOf(`<${tag}`);
const channelTitle = decodeEntities(
inner(firstItem === -1 ? xml : xml.slice(0, firstItem), "title")?.slice(0, 1000) ?? "",
);
const blocks = elements(xml, tag, MAX_ITEMS_PER_FEED);
const items = [];
for (const block of blocks) {
const link = isAtom
? attrOf(block, "link", "href", (el) => !/rel\s*=\s*["'](?!alternate)/i.test(el))
: inner(block, "link");
const url = safeUrl(link?.trim(), feedUrl);
const title = decodeEntities(inner(block, "title")?.slice(0, 1000) ?? "");
if (!url || !title) continue;
const body = inner(block, "content:encoded") ?? inner(block, "content");
const summary = inner(block, "description") ?? inner(block, "summary");
const image =
attrOf(block, "enclosure", "url", (el) => /type\s*=\s*["']image\//i.test(el)) ??
attrOf(block, "media:content", "url") ??
attrOf(block, "media:thumbnail", "url") ??
firstImage(body) ??
firstImage(summary);
items.push({
title,
url,
excerpt: plain(summary) ?? plain(body),
image: safeUrl(image, feedUrl, { httpsOnly: true }),
published: isoDate(inner(block, "pubDate") ?? inner(block, "published") ?? inner(block, "updated")),
});
}
return { title: channelTitle || null, items };
}
/* ── Fetching ──────────────────────────────────────────────── */
async function fetchFeed(url) {
const result = await safeGet(url, {
maxBytes: MAX_FEED_BYTES,
accept: "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.1",
});
return parseFeed(result.body.toString("utf8"), result.url.toString());
}
/* One fetch at a time per feed, shared by everyone who asks while it
runs. A failure keeps the last good copy and waits 5 minutes before
trying again, rather than retrying on every request. */
function refresh(url) {
const hit = cache.get(url);
if (hit?.pending) return hit.pending;
const pending = fetchFeed(url)
.then((feed) => {
cache.set(url, { at: Date.now(), feed });
return feed;
})
.catch((err) => {
console.warn(`feed ${url}: ${err.message}`);
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
});
cache.set(url, { ...hit, pending });
return pending;
}
/* A fresh copy as it is; a stale one straight away while a refresh
runs behind it, so no visitor waits on someone else's server once
the feed has been read once. Only the very first read waits. */
async function readFeed(url) {
const hit = cache.get(url);
if (hit?.feed) {
if (Date.now() - hit.at >= CACHE_MS) refresh(url);
return hit.feed;
}
return refresh(url);
}
/* Every listed feed's items, newest first, each tagged with its
source: the row's label, else the feed's own title. */
export async function readFeeds(rows) {
const feeds = await Promise.all(rows.map((row) => readFeed(row.url)));
const items = feeds.flatMap((feed, i) =>
feed.items.map((item) => ({ ...item, source: rows[i].label || feed.title })),
);
return items.sort((a, b) => (b.published ?? "").localeCompare(a.published ?? ""));
}