Add CLI entry point, RSS content extraction, and image support

Features:
- Add CLI with commands: start, add, remove, list, fetch, status, items
- Auto-detect RSS format when adding feeds
- Auto-run database migrations on startup
- Extract full HTML content from RSS description field (NOS-style feeds)
- Extract image URLs from RSS enclosure tags
- Display images in terminal output with emoji
- Include imageUrl in JSON formatter output

Database:
- Add image_url column to feed_items table
- Update storage layer to persist imageUrl field

Tests:
- Add 10 CLI integration tests
- Add 3 RSS parser tests for image/content extraction
- Add 2 storage tests for imageUrl persistence

Dependencies:
- Add commander for CLI framework

All 144 tests passing
This commit is contained in:
Edo Limburg
2026-05-05 23:05:30 +02:00
parent 78a2b27f6d
commit c79eb6d76d
14 changed files with 825 additions and 4 deletions
+3 -1
View File
@@ -8,6 +8,7 @@ interface JsonFeedItem {
publishedAt: string;
content?: string;
summary?: string;
imageUrl?: string;
}
export class JsonFormatter {
@@ -19,7 +20,8 @@ export class JsonFormatter {
url: item.url,
publishedAt: item.publishedAt.toISOString(),
...(item.content !== undefined && { content: item.content }),
...(item.summary !== undefined && { summary: item.summary })
...(item.summary !== undefined && { summary: item.summary }),
...(item.imageUrl !== undefined && { imageUrl: item.imageUrl })
}));
return JSON.stringify(jsonItems, null, 2);
+4
View File
@@ -23,6 +23,10 @@ export class TerminalFormatter {
lines.push(` ${this.dim(truncated)}`);
}
if (item.imageUrl) {
lines.push(` ${this.dim('📷')} ${this.dim(this.truncate(item.imageUrl, 70))}`);
}
lines.push('');
});
+133
View File
@@ -169,6 +169,139 @@ describe('RssParser', () => {
expect(items1[0].id).toBe(items2[0].id);
});
it('uses description as content when no content:encoded and description contains HTML', async () => {
// Simulates feeds like NOS that put full HTML content in description
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<item>
<title><![CDATA[Iran ontkent aanvallen VAE]]></title>
<link>https://nos.nl/l/2613264</link>
<description><![CDATA[
<p>Iran ontkent aanvallen te hebben uitgevoerd op de Verenigde Arabische Emiraten.</p>
<p>Gisteren werden er ook al aanvallen gemeld door de VAE.</p>
<h2>Onderhandelingen onmogelijk</h2>
<p>Iraanse staatsmedia melden dat de Iraanse president Pezeshkian heeft gezegd dat de VS aan de ene kant de druk op Iran opvoert.</p>
]]></description>
<pubDate>Tue, 5 May 2026 21:44:46 +0200</pubDate>
</item>
</channel>
</rss>`;
const items = await parser.parse(xml, 'https://feeds.nos.nl/nosnieuwsalgemeen');
expect(items).toHaveLength(1);
expect(items[0].title).toBe('Iran ontkent aanvallen VAE');
// Content should contain the full HTML
expect(items[0].content).toContain('<p>Iran ontkent aanvallen');
expect(items[0].content).toContain('<h2>Onderhandelingen onmogelijk</h2>');
// Summary should be extracted from content
expect(items[0].summary).toBeDefined();
expect(items[0].summary).toContain('Iran ontkent aanvallen');
expect(items[0].summary?.length).toBeLessThanOrEqual(210); // 200 + "..."
});
it('uses description as summary when it looks like plain text summary', async () => {
const xml = `<?xml version="1.0"?>
<rss version="2.0">
<channel>
<item>
<title>Short Summary Article</title>
<link>https://example.com/article</link>
<description>This is just a brief summary without HTML tags</description>
<pubDate>Mon, 06 Sep 2024 09:00:00 GMT</pubDate>
</item>
</channel>
</rss>`;
const items = await parser.parse(xml, 'https://example.com/feed.xml');
expect(items).toHaveLength(1);
expect(items[0].summary).toBe('This is just a brief summary without HTML tags');
expect(items[0].content).toBeUndefined();
});
it('strips CDATA wrappers from description and content', async () => {
const xml = `<?xml version="1.0"?>
<rss version="2.0">
<channel>
<item>
<title><![CDATA[CDATA Title]]></title>
<link>https://example.com/article</link>
<description><![CDATA[<p>This is a very long content with <strong>formatting</strong> and lots of text to ensure it exceeds the 500 character threshold for being considered full content. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>]]></description>
<pubDate>Mon, 06 Sep 2024 09:00:00 GMT</pubDate>
</item>
</channel>
</rss>`;
const items = await parser.parse(xml, 'https://example.com/feed.xml');
expect(items[0].title).toBe('CDATA Title');
expect(items[0].content).toContain('<p>This is a very long content');
expect(items[0].content).toContain('<strong>formatting</strong>');
});
it('extracts image URL from enclosure', async () => {
const xml = `<?xml version="1.0"?>
<rss version="2.0">
<channel>
<item>
<title>Article with Image</title>
<link>https://example.com/article</link>
<description>Article summary</description>
<enclosure url="https://example.com/image.jpg" type="image/jpeg" length="12345"/>
<pubDate>Mon, 06 Sep 2024 09:00:00 GMT</pubDate>
</item>
</channel>
</rss>`;
const items = await parser.parse(xml, 'https://example.com/feed.xml');
expect(items).toHaveLength(1);
expect(items[0].imageUrl).toBe('https://example.com/image.jpg');
});
it('extracts first image from multiple enclosures', async () => {
const xml = `<?xml version="1.0"?>
<rss version="2.0">
<channel>
<item>
<title>Article with Multiple Enclosures</title>
<link>https://example.com/article</link>
<description>Article summary</description>
<enclosure url="https://example.com/audio.mp3" type="audio/mpeg" length="12345"/>
<enclosure url="https://example.com/image.webp" type="image/webp" length="67890"/>
<enclosure url="https://example.com/video.mp4" type="video/mp4" length="99999"/>
<pubDate>Mon, 06 Sep 2024 09:00:00 GMT</pubDate>
</item>
</channel>
</rss>`;
const items = await parser.parse(xml, 'https://example.com/feed.xml');
expect(items).toHaveLength(1);
expect(items[0].imageUrl).toBe('https://example.com/image.webp');
});
it('handles items without enclosure', async () => {
const xml = `<?xml version="1.0"?>
<rss version="2.0">
<channel>
<item>
<title>Article without Image</title>
<link>https://example.com/article</link>
<description>Article summary</description>
<pubDate>Mon, 06 Sep 2024 09:00:00 GMT</pubDate>
</item>
</channel>
</rss>`;
const items = await parser.parse(xml, 'https://example.com/feed.xml');
expect(items).toHaveLength(1);
expect(items[0].imageUrl).toBeUndefined();
});
});
describe('supports', () => {
+103 -2
View File
@@ -9,6 +9,12 @@ interface RssChannel {
description?: string;
}
interface RssEnclosure {
'@_url'?: string;
'@_type'?: string;
'@_length'?: string;
}
interface RssItem {
title?: string;
link?: string;
@@ -16,6 +22,7 @@ interface RssItem {
'content:encoded'?: string;
pubDate?: string;
guid?: string;
enclosure?: RssEnclosure | RssEnclosure[];
}
interface RssFeed {
@@ -84,17 +91,111 @@ export class RssParser implements IParser {
const publishedAt = item.pubDate ? parseDate(item.pubDate) : new Date();
const url = item.link;
// Handle content extraction
// Some feeds use content:encoded for full content
// Others put full content in description (like NOS)
const hasContentEncoded = !!item['content:encoded'];
const description = item.description ? this.cleanText(item.description) : undefined;
const contentEncoded = item['content:encoded'] ? this.cleanText(item['content:encoded']) : undefined;
// If there's content:encoded, use it as content and description as summary
// If no content:encoded but description looks like full content (contains HTML), use it as content
// Otherwise description is just a summary
const descriptionLooksLikeContent = description && this.looksLikeFullContent(description);
let content: string | undefined;
let summary: string | undefined;
if (contentEncoded) {
// Standard case: content:encoded has full content, description has summary
content = contentEncoded;
summary = description;
} else if (descriptionLooksLikeContent) {
// No content:encoded but description contains full HTML content
content = description;
// Extract first paragraph or truncate for summary
summary = this.extractSummary(description);
} else {
// Description is just a plain text summary
summary = description;
content = undefined;
}
// Extract image URL from enclosure
const imageUrl = this.extractImageUrl(item.enclosure);
return {
id: generateId(url, publishedAt),
source,
title: this.cleanText(item.title),
url,
publishedAt,
summary: item.description ? this.cleanText(item.description) : undefined,
content: item['content:encoded'] ? this.cleanText(item['content:encoded']) : undefined,
summary,
content,
imageUrl,
};
}
private extractImageUrl(enclosure: RssEnclosure | RssEnclosure[] | undefined): string | undefined {
if (!enclosure) {
return undefined;
}
// Handle single enclosure or array of enclosures
const enclosures = Array.isArray(enclosure) ? enclosure : [enclosure];
// Find first image enclosure
for (const enc of enclosures) {
const url = enc['@_url'];
const type = enc['@_type'];
if (url) {
// Check if it's an image type (image/*)
if (!type || type.startsWith('image/')) {
return url;
}
}
}
return undefined;
}
private looksLikeFullContent(text: string): boolean {
// Check if text looks like full HTML content rather than a brief summary
// Indicators: contains HTML tags, is quite long, has multiple paragraphs
if (!text) return false;
// Check for common HTML tags that indicate full content
const hasHtmlTags = /<(p|div|br|h[1-6]|ul|ol|li|img|a|strong|em|blockquote)[\s>]/i.test(text);
// Check for substantial length (more than 500 chars suggests full content)
const isLong = text.length > 500;
// Check for multiple paragraphs or line breaks
const hasMultipleParagraphs = (text.match(/<p[\s>]/gi) || []).length >= 2 ||
text.split(/\n\n|<br\s*\/?>/i).length >= 3;
return hasHtmlTags && (isLong || hasMultipleParagraphs);
}
private extractSummary(content: string): string {
// Extract a summary from full HTML content
// Try to get the first paragraph or first 200 chars
if (!content) return '';
// Remove HTML tags
const textOnly = content.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
// Get first 200 characters, ending at a word boundary
if (textOnly.length <= 200) {
return textOnly;
}
const truncated = textOnly.substring(0, 200);
const lastSpace = truncated.lastIndexOf(' ');
return truncated.substring(0, lastSpace) + '...';
}
private cleanText(text: string): string {
if (!text) return '';
// Remove CDATA wrappers if present
+42
View File
@@ -136,6 +136,48 @@ describe('SqlStorage', () => {
expect(recent[0].url).toBe('https://example.com/article'); // unchanged
expect(recent[0].publishedAt).toEqual(new Date('2024-09-06T09:00:00Z')); // unchanged
});
it('saves and retrieves imageUrl', async () => {
const item: FeedItem = {
id: 'image-test',
source: 'https://example.com/feed.xml',
title: 'Article with Image',
url: 'https://example.com/article',
publishedAt: new Date('2024-09-06T09:00:00Z'),
summary: 'Summary',
imageUrl: 'https://example.com/image.jpg',
};
await storage.save([item]);
const recent = await storage.getRecent(1);
expect(recent).toHaveLength(1);
expect(recent[0].imageUrl).toBe('https://example.com/image.jpg');
});
it('updates imageUrl on upsert', async () => {
const item: FeedItem = {
id: 'image-update-test',
source: 'https://example.com/feed.xml',
title: 'Article',
url: 'https://example.com/article',
publishedAt: new Date('2024-09-06T09:00:00Z'),
imageUrl: 'https://example.com/old-image.jpg',
};
await storage.save([item]);
// Update with new image URL
const updatedItem: FeedItem = {
...item,
imageUrl: 'https://example.com/new-image.jpg',
};
await storage.save([updatedItem]);
const recent = await storage.getRecent(1);
expect(recent[0].imageUrl).toBe('https://example.com/new-image.jpg');
});
});
describe('getRecent', () => {
+3
View File
@@ -28,6 +28,7 @@ export class SqlStorage implements IStorage {
published_at: item.publishedAt.toISOString(),
content: item.content ?? null,
summary: item.summary ?? null,
image_url: item.imageUrl ?? null,
created_at: new Date().toISOString(),
}));
@@ -40,6 +41,7 @@ export class SqlStorage implements IStorage {
title: (eb) => eb.ref('excluded.title'),
content: (eb) => eb.ref('excluded.content'),
summary: (eb) => eb.ref('excluded.summary'),
image_url: (eb) => eb.ref('excluded.image_url'),
})
)
.execute();
@@ -96,6 +98,7 @@ export class SqlStorage implements IStorage {
publishedAt: new Date(row.published_at),
content: row.content ?? undefined,
summary: row.summary ?? undefined,
imageUrl: row.image_url ?? undefined,
};
}