Skip to content

Real-time dashboard for monitoring global news, markets, and geopolitical events

TypeScript

Replace rss2json with Cloudflare Worker RSS parsing

Sean Thielen-Esparzabff86b692e03
diff --git a/js/data.js b/js/data.js
index 4f96237..8526909 100644
--- a/js/data.js
+++ b/js/data.js
@@ -8,14 +8,20 @@ export async function fetchWithProxy(url) {
return serviceClient.fetchWithProxy(url);
}
-// Fetch RSS feed using rss2json API as primary method - now with caching
+// Worker URL for RSS parsing
+const WORKER_URL = 'https://situation-monitor-proxy.seanthielen-e.workers.dev';
+
+// Fetch RSS feed using Cloudflare Worker with built-in RSS-to-JSON parsing
export async function fetchFeedViaJson(source) {
try {
- const result = await serviceClient.request('RSS2JSON', '/v1/api.json', {
- params: { rss_url: source.url }
- });
+ const proxyUrl = `${WORKER_URL}/?url=${encodeURIComponent(source.url)}&format=json`;
+ const response = await fetch(proxyUrl);
- const data = result.data;
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+
+ const data = await response.json();
if (data.status !== 'ok' || !data.items) return [];
return data.items.slice(0, 5).map(item => ({
@@ -24,10 +30,10 @@ export async function fetchFeedViaJson(source) {
link: item.link || '',
pubDate: item.pubDate || '',
isAlert: hasAlertKeyword(item.title || ''),
- _cached: result.fromCache || false
+ _cached: response.headers.get('X-Cache') === 'HIT'
}));
} catch (e) {
- console.log(`rss2json failed for ${source.name}, trying XML proxy...`);
+ console.log(`Worker failed for ${source.name}, trying XML fallback...`);
return null; // Signal to try XML fallback
}
}
@@ -38,9 +44,9 @@ export function hasAlertKeyword(title) {
return ALERT_KEYWORDS.some(kw => lower.includes(kw));
}
-// Parse RSS feed - tries rss2json API first, then falls back to XML proxy
+// Parse RSS feed - tries Cloudflare Worker JSON first, then falls back to XML
export async function fetchFeed(source) {
- // Try rss2json API first (more reliable)
+ // Try Worker RSS-to-JSON first
const jsonResult = await fetchFeedViaJson(source);
if (jsonResult !== null && jsonResult.length > 0) {
return jsonResult;
@@ -274,11 +280,13 @@ export async function fetchCongressTrades() {
// Note: The House Stock Watcher S3 bucket is no longer publicly accessible.
// This now fetches congressional trading-related news instead.
try {
- const result = await serviceClient.request('RSS2JSON', '/v1/api.json', {
- params: { rss_url: 'https://news.google.com/rss/search?q=congress+stock+trading+disclosure&hl=en-US&gl=US&ceid=US:en' }
- });
+ const feedUrl = 'https://news.google.com/rss/search?q=congress+stock+trading+disclosure&hl=en-US&gl=US&ceid=US:en';
+ const proxyUrl = `${WORKER_URL}/?url=${encodeURIComponent(feedUrl)}&format=json`;
+ const response = await fetch(proxyUrl);
- const data = result.data;
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+
+ const data = await response.json();
if (data.status === 'ok' && data.items) {
return data.items.slice(0, 10).map(item => ({
name: item.title.substring(0, 50) + (item.title.length > 50 ? '...' : ''),
@@ -320,16 +328,17 @@ export async function fetchGovContracts() {
}
}
-// Fetch AI news from major AI companies - now with ServiceClient
+// Fetch AI news from major AI companies - using Cloudflare Worker
export async function fetchAINews() {
const results = await Promise.all(AI_FEEDS.map(async (source) => {
- // Try rss2json API first with ServiceClient
+ // Use Cloudflare Worker with RSS-to-JSON parsing
try {
- const result = await serviceClient.request('RSS2JSON', '/v1/api.json', {
- params: { rss_url: source.url }
- });
+ const proxyUrl = `${WORKER_URL}/?url=${encodeURIComponent(source.url)}&format=json`;
+ const response = await fetch(proxyUrl);
+
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
- const data = result.data;
+ const data = await response.json();
if (data.status === 'ok' && data.items) {
return data.items.slice(0, 3).map(item => ({
source: source.name,
@@ -338,32 +347,6 @@ export async function fetchAINews() {
date: item.pubDate || ''
}));
}
- } catch (e) {
- // Fall through to XML proxy
- }
-
- // Fallback to XML proxy
- try {
- const text = await fetchWithProxy(source.url);
- const parser = new DOMParser();
- const xml = parser.parseFromString(text, 'text/xml');
-
- let items = xml.querySelectorAll('item');
- if (items.length === 0) items = xml.querySelectorAll('entry');
-
- return Array.from(items).slice(0, 3).map(item => {
- let link = '';
- const linkEl = item.querySelector('link');
- if (linkEl) link = linkEl.getAttribute('href') || linkEl.textContent || '';
-
- return {
- source: source.name,
- title: item.querySelector('title')?.textContent?.trim() || 'No title',
- link: link.trim(),
- date: item.querySelector('pubDate')?.textContent ||
- item.querySelector('published')?.textContent || ''
- };
- });
} catch (e) {
console.log(`Failed to fetch ${source.name}`);
return [];
diff --git a/workers/proxy/index.js b/workers/proxy/index.js
index e8c9872..70e5b0b 100644
--- a/workers/proxy/index.js
+++ b/workers/proxy/index.js
@@ -1,4 +1,4 @@
-// Cloudflare Worker - CORS Proxy with caching
+// Cloudflare Worker - CORS Proxy with RSS parsing and caching
// Deploy: wrangler deploy
const ALLOWED_ORIGINS = [
@@ -13,7 +13,7 @@ const ALLOWED_ORIGINS = [
'rss.nytimes.com',
'rss.cnn.com',
'www.theguardian.com',
- 'apnews.com',
+ 'news.google.com',
// Tech feeds
'news.ycombinator.com',
'hnrss.org',
@@ -71,6 +71,120 @@ function getCacheTtl(contentType, host) {
return 120;
}
+// Parse RSS/Atom XML to JSON
+function parseRssToJson(xml, feedUrl) {
+ const result = {
+ status: 'ok',
+ feed: {
+ url: feedUrl,
+ title: '',
+ link: '',
+ description: ''
+ },
+ items: []
+ };
+
+ // Extract feed metadata
+ result.feed.title = extractTag(xml, 'title') || '';
+ result.feed.link = extractTag(xml, 'link') || feedUrl;
+ result.feed.description = extractTag(xml, 'description') || extractTag(xml, 'subtitle') || '';
+
+ // Check if it's Atom format
+ const isAtom = xml.includes('<feed') && xml.includes('xmlns="http://www.w3.org/2005/Atom"');
+
+ if (isAtom) {
+ // Parse Atom format
+ const entries = xml.match(/<entry[\s\S]*?<\/entry>/gi) || [];
+ for (const entry of entries.slice(0, 20)) {
+ const item = {
+ title: extractTag(entry, 'title') || '',
+ pubDate: extractTag(entry, 'published') || extractTag(entry, 'updated') || '',
+ link: extractAtomLink(entry) || '',
+ description: extractTag(entry, 'summary') || extractTag(entry, 'content') || '',
+ content: extractTag(entry, 'content') || ''
+ };
+ if (item.title || item.link) {
+ result.items.push(item);
+ }
+ }
+ } else {
+ // Parse RSS format
+ const items = xml.match(/<item[\s\S]*?<\/item>/gi) || [];
+ for (const item of items.slice(0, 20)) {
+ const parsed = {
+ title: extractTag(item, 'title') || '',
+ pubDate: extractTag(item, 'pubDate') || extractTag(item, 'dc:date') || '',
+ link: extractTag(item, 'link') || extractTag(item, 'guid') || '',
+ description: extractTag(item, 'description') || '',
+ content: extractTag(item, 'content:encoded') || extractTag(item, 'content') || ''
+ };
+ if (parsed.title || parsed.link) {
+ result.items.push(parsed);
+ }
+ }
+ }
+
+ return result;
+}
+
+// Extract content from XML tag
+function extractTag(xml, tagName) {
+ // Handle namespaced tags (e.g., content:encoded)
+ const escapedTag = tagName.replace(':', '\\:');
+
+ // Try CDATA first
+ const cdataRegex = new RegExp(`<${escapedTag}[^>]*><!\\[CDATA\\[([\\s\\S]*?)\\]\\]><\\/${escapedTag}>`, 'i');
+ const cdataMatch = xml.match(cdataRegex);
+ if (cdataMatch) {
+ return decodeHtmlEntities(cdataMatch[1].trim());
+ }
+
+ // Try regular content
+ const regex = new RegExp(`<${escapedTag}[^>]*>([\\s\\S]*?)<\\/${escapedTag}>`, 'i');
+ const match = xml.match(regex);
+ if (match) {
+ return decodeHtmlEntities(match[1].trim());
+ }
+
+ return null;
+}
+
+// Extract link from Atom entry (handles href attribute)
+function extractAtomLink(entry) {
+ // Look for link with rel="alternate" or no rel (default)
+ const linkMatch = entry.match(/<link[^>]*href=["']([^"']+)["'][^>]*>/i);
+ if (linkMatch) {
+ return linkMatch[1];
+ }
+ return extractTag(entry, 'link');
+}
+
+// Decode common HTML entities
+function decodeHtmlEntities(text) {
+ if (!text) return text;
+ return text
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&')
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;/g, "'")
+ .replace(/&apos;/g, "'")
+ .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
+ .replace(/&#(\d+);/g, (_, dec) => String.fromCharCode(parseInt(dec, 10)));
+}
+
+// Check if content is RSS/Atom XML
+function isRssFeed(contentType, body) {
+ if (contentType.includes('xml') || contentType.includes('rss') || contentType.includes('atom')) {
+ return true;
+ }
+ // Check body for RSS/Atom markers
+ if (body && (body.includes('<rss') || body.includes('<feed') || body.includes('<channel'))) {
+ return true;
+ }
+ return false;
+}
+
// Add CORS headers to response
function addCorsHeaders(response, origin) {
const headers = new Headers(response.headers);
@@ -117,12 +231,14 @@ export default {
return new Response('Method not allowed', { status: 405 });
}
- // Get target URL from query param
+ // Get target URL and format preference from query params
const targetUrl = url.searchParams.get('url');
+ const wantJson = url.searchParams.get('format') === 'json';
+
if (!targetUrl) {
return new Response(JSON.stringify({
error: 'Missing url parameter',
- usage: 'Add ?url=<encoded-url> to proxy requests'
+ usage: 'Add ?url=<encoded-url>&format=json to fetch and parse RSS feeds'
}), {
status: 400,
headers: { 'Content-Type': 'application/json' }
@@ -140,30 +256,29 @@ export default {
});
}
- // Check cache first
- const cacheKey = new Request(targetUrl, request);
+ // Create cache key (include format param for JSON-parsed versions)
+ const cacheKeyUrl = wantJson ? `${targetUrl}__json` : targetUrl;
+ const cacheKey = new Request(cacheKeyUrl, request);
const cache = caches.default;
- let response = await cache.match(cacheKey);
-
- if (response) {
- // Return cached response
- const cachedResponse = addCorsHeaders(response, origin);
- cachedResponse.headers.set('X-Cache', 'HIT');
- cachedResponse.headers.set('X-Cache-Time', response.headers.get('X-Cache-Time') || 'unknown');
- return cachedResponse;
+ let cachedResponse = await cache.match(cacheKey);
+
+ if (cachedResponse) {
+ const response = addCorsHeaders(cachedResponse, origin);
+ response.headers.set('X-Cache', 'HIT');
+ response.headers.set('X-Cache-Time', cachedResponse.headers.get('X-Cache-Time') || 'unknown');
+ return response;
}
// Fetch from origin
try {
const targetUrlObj = new URL(targetUrl);
- response = await fetch(targetUrl, {
+ const response = await fetch(targetUrl, {
headers: {
'User-Agent': 'SituationMonitor/1.0 (https://github.com/situation-monitor)',
- 'Accept': request.headers.get('Accept') || '*/*'
+ 'Accept': 'application/rss+xml, application/xml, text/xml, application/atom+xml, */*'
},
cf: {
- // Cloudflare cache settings
cacheTtl: getCacheTtl('', targetUrlObj.hostname),
cacheEverything: true
}
@@ -179,31 +294,57 @@ export default {
}), origin);
}
- // Clone for caching
- const responseToCache = response.clone();
const contentType = response.headers.get('content-type') || '';
+ const body = await response.text();
const cacheTtl = getCacheTtl(contentType, targetUrlObj.hostname);
- // Store in cache with TTL
+ let finalBody = body;
+ let finalContentType = contentType;
+
+ // Parse RSS to JSON if requested and content is RSS/Atom
+ if (wantJson && isRssFeed(contentType, body)) {
+ try {
+ const parsed = parseRssToJson(body, targetUrl);
+ finalBody = JSON.stringify(parsed);
+ finalContentType = 'application/json';
+ } catch (parseError) {
+ // If parsing fails, return error
+ return addCorsHeaders(new Response(JSON.stringify({
+ status: 'error',
+ error: 'Failed to parse RSS feed',
+ message: parseError.message
+ }), {
+ status: 500,
+ headers: { 'Content-Type': 'application/json' }
+ }), origin);
+ }
+ }
+
+ // Create response
+ const finalResponse = new Response(finalBody, {
+ status: 200,
+ headers: {
+ 'Content-Type': finalContentType,
+ 'X-Cache': 'MISS',
+ 'X-Cache-TTL': String(cacheTtl)
+ }
+ });
+
+ // Store in cache
if (cacheTtl > 0) {
- const cacheHeaders = new Headers(responseToCache.headers);
+ const cacheHeaders = new Headers(finalResponse.headers);
cacheHeaders.set('Cache-Control', `public, max-age=${cacheTtl}`);
cacheHeaders.set('X-Cache-Time', new Date().toISOString());
ctx.waitUntil(
- cache.put(cacheKey, new Response(responseToCache.body, {
- status: responseToCache.status,
- statusText: responseToCache.statusText,
+ cache.put(cacheKey, new Response(finalBody, {
+ status: 200,
headers: cacheHeaders
}))
);
}
- // Return response with CORS headers
- const finalResponse = addCorsHeaders(response, origin);
- finalResponse.headers.set('X-Cache', 'MISS');
- finalResponse.headers.set('X-Cache-TTL', String(cacheTtl));
- return finalResponse;
+ return addCorsHeaders(finalResponse, origin);
} catch (error) {
return addCorsHeaders(new Response(JSON.stringify({