/* ═══════════════════════════════════════════════════════════════ 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://.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*\s*$/, "$1"); } /* The text inside the first …, 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]*?)`, "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(/]*\bsrc\s*=\s*["']([^"']+)["']/i)?.[1] ?? null; } function parseFeed(xml, feedUrl) { const isAtom = /]*xmlns=["']http:\/\/www\.w3\.org\/2005\/Atom/i.test(xml) && !//gi : //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 ?? "")); }