Add a blog: posts at /blog/:id and a Community page section

Admin → Blog → Posts (migration 031): our own posts with a
content-block body, cover image, excerpt, date, tags, and authors
shown as person tiles, either People records or a guest name and
photo. A post is a draft until published; Listed works as it does
elsewhere. Posts are on the QR page too.

Admin → Blog → Community section: the first section of the
Community page, with its heading and blurb from the admin, in two
halves, each pinned first and then newest up to its slots. Our posts
come from blog_posts; community posts are pinned link or video cards
(reusing featured cards and Fetch preview), then the newest items
from a list of RSS or Atom feeds. Feeds are read through the link
preview's guarded fetch and cached for 30 minutes, and a failing feed
keeps its last good items.

content_blocks and featured_cards are rebuilt to accept the new owner
kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 16:27:00 -05:00
parent d4f65d93b4
commit d374f9ac17
21 changed files with 1275 additions and 15 deletions

150
server/src/feeds.js Normal file
View file

@ -0,0 +1,150 @@
/* ═══════════════════════════════════════════════════════════════
FEEDS
Reads the RSS and Atom feeds the Community page's blog section
lists (community_page_feeds), 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, 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). */
function inner(xml, tag) {
const match = xml.match(new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, "i"));
return match ? unwrap(match[1]) : null;
}
function attrOf(xml, tag, name, where = () => true) {
for (const match of xml.matchAll(new RegExp(`<${tag}\\b[^>]*>`, "gi"))) {
const el = match[0];
const value = el.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)')`, "i"));
if (value && where(el)) return value[2] ?? value[3];
}
return null;
}
function plain(html) {
if (!html) return null;
const text = decodeEntities(html.replace(/<[^>]+>/g, " "));
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) {
return html?.match(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null;
}
function parseFeed(xml, feedUrl) {
const isAtom = /<feed\b[^>]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !/<rss\b/i.test(xml);
const channelTitle = decodeEntities(inner(xml.replace(/<(item|entry)\b[\s\S]*$/i, ""), "title") ?? "");
const blocks = xml.match(isAtom ? /<entry\b[\s\S]*?<\/entry>/gi : /<item\b[\s\S]*?<\/item>/gi) ?? [];
const items = [];
for (const block of blocks.slice(0, MAX_ITEMS_PER_FEED)) {
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") ?? "");
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());
}
async function readFeed(url) {
const hit = cache.get(url);
if (hit && Date.now() - hit.at < CACHE_MS) return hit.feed;
try {
const feed = await fetchFeed(url);
cache.set(url, { at: Date.now(), feed });
return feed;
} catch (err) {
console.warn(`feed ${url}: ${err.message}`);
// Serve the last good copy, and don't retry on every request.
const stale = hit?.feed ?? { title: null, items: [] };
cache.set(url, { at: Date.now() - CACHE_MS + 5 * 60 * 1000, feed: stale });
return stale;
}
}
/* 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 ?? ""));
}