feedkeeper 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feedkeeper",
3
- "version": "0.40.0",
3
+ "version": "0.42.0",
4
4
  "description": "A lightweight, self-hosted RSS reader and remote MCP server for your news, blogs, and AI workflows.",
5
5
  "keywords": [
6
6
  "rss",
@@ -0,0 +1,33 @@
1
+ ALTER TABLE push_devices RENAME TO push_devices_web;
2
+ DROP INDEX idx_push_devices_user;
3
+
4
+ CREATE TABLE push_devices (
5
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
6
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
7
+ endpoint TEXT UNIQUE,
8
+ p256dh TEXT,
9
+ auth TEXT,
10
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
11
+ native_device_id INTEGER UNIQUE REFERENCES personal_access_tokens(id) ON DELETE CASCADE,
12
+ native_token TEXT,
13
+ native_environment TEXT CHECK(native_environment IN ('development', 'production')),
14
+ native_language TEXT,
15
+ native_feeds INTEGER NOT NULL DEFAULT 0,
16
+ native_editions INTEGER NOT NULL DEFAULT 0,
17
+ CHECK (
18
+ (endpoint IS NOT NULL AND p256dh IS NOT NULL AND auth IS NOT NULL AND native_device_id IS NULL) OR
19
+ (endpoint IS NULL AND native_device_id IS NOT NULL AND native_token IS NOT NULL AND native_environment IS NOT NULL AND native_language IS NOT NULL)
20
+ )
21
+ );
22
+
23
+ INSERT INTO push_devices (id, user_id, endpoint, p256dh, auth, created_at)
24
+ SELECT id, user_id, endpoint, p256dh, auth, created_at FROM push_devices_web;
25
+
26
+ -- Delivery cursors in the existing outbox refer to the original ID sequence.
27
+ UPDATE sqlite_sequence SET seq = MAX(seq, (SELECT seq FROM sqlite_sequence WHERE name = 'push_devices_web'))
28
+ WHERE name = 'push_devices';
29
+ INSERT INTO sqlite_sequence (name, seq)
30
+ SELECT 'push_devices', seq FROM sqlite_sequence WHERE name = 'push_devices_web'
31
+ AND NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = 'push_devices');
32
+ DROP TABLE push_devices_web;
33
+ CREATE INDEX idx_push_devices_user ON push_devices(user_id);
@@ -1,20 +1,24 @@
1
- import Parser from "rss-parser";
2
1
  import { fetchFeed } from "./fetcher.js";
3
2
  import { assertPublicFeedUrl } from "./blockedHosts.js";
4
- import { decodeEntities, plainTitle } from "./text.js";
5
- import { applePodcastId, feedUrlFromAppleLookup, platformFeedCandidates } from "./platformFeeds.js";
6
- const rssParser = new Parser();
3
+ import { decodeEntities } from "./text.js";
4
+ import { applePodcastId, fediverseFeedCandidate, feedUrlFromAppleLookup, platformFeedCandidates, youtubeChannelFeedFromHtml } from "./platformFeeds.js";
5
+ import { parseFeedBody } from "./feedParser.js";
7
6
  // Common alternate feed types found in HTML <head>
8
7
  const FEED_MIME_TYPES = [
9
8
  "application/rss+xml",
10
9
  "application/atom+xml",
10
+ "application/feed+json",
11
+ "application/json",
11
12
  "text/xml",
12
13
  "application/xml",
13
14
  ];
14
15
  const MAX_PROBES = 15;
15
- const COMMON_PATHS = ["/feed/", "/feed", "/rss.xml", "/atom.xml", "/feed.xml", "/index.xml", "/rss/", "/rss", "/rss.php?feed=RSS2.0", "/rss.php?feed=ATOM1.0"];
16
+ const COMMON_PATHS = [
17
+ "/feed/", "/feed", "/rss.xml", "/atom.xml", "/feed.xml", "/feed.json",
18
+ "/index.xml", "/index.json", "/rss/", "/rss", "/rss.php?feed=RSS2.0", "/rss.php?feed=ATOM1.0",
19
+ ];
16
20
  // Feed-looking URLs anywhere in a page, including JSON embedded in attributes.
17
- const FEED_URL_IN_TEXT = /https?:\/\/[^\s"'<>\\]+?(?:\.rss|\.atom|\/feed\/?|\/(?:rss|atom|feed)\.xml)(?=["'\s<>\\]|$)/gi;
21
+ const FEED_URL_IN_TEXT = /https?:\/\/[^\s"'<>\\]+?(?:\.rss|\.atom|\/feed\/?|\/(?:rss|atom|feed)\.xml|\/feed\.json)(?=["'\s<>\\]|$)/gi;
18
22
  function sameUrl(a, b) {
19
23
  const normalize = (value) => {
20
24
  try {
@@ -33,9 +37,9 @@ async function parseFeedAt(url) {
33
37
  const fetched = await fetchFeed(url, { priority: "interactive" });
34
38
  const finalUrl = fetched.finalUrl || url;
35
39
  try {
36
- const parsed = await rssParser.parseString(fetched.body);
37
- if (parsed.items && (parsed.title || parsed.description || parsed.items.length > 0)) {
38
- return { feed: { url: finalUrl, title: plainTitle(parsed.title) ?? null, type: "application/rss+xml" }, html: null, finalUrl };
40
+ const parsed = await parseFeedBody(fetched.body);
41
+ if (parsed.title || parsed.description || parsed.items.length > 0) {
42
+ return { feed: { url: finalUrl, title: parsed.title ?? null, type: parsed.mimeType }, html: null, finalUrl };
39
43
  }
40
44
  }
41
45
  catch {
@@ -118,6 +122,19 @@ export async function discoverFeeds(inputUrl) {
118
122
  const fromPage = await keepRealFeeds(extractFeedsFromHtml(page.html, page.finalUrl), page.finalUrl);
119
123
  if (fromPage.length > 0)
120
124
  return fromPage;
125
+ const ytChannelFeed = youtubeChannelFeedFromHtml(page.html, validated);
126
+ if (ytChannelFeed) {
127
+ const candidate = await parseFeedAt(ytChannelFeed);
128
+ if (candidate.feed)
129
+ return [candidate.feed];
130
+ }
131
+ }
132
+ // 2b. Fediverse / Mastodon profile handles (`/@user` -> `/@user.rss`).
133
+ const fediverse = fediverseFeedCandidate(validated);
134
+ if (fediverse && !sameUrl(fediverse, targetUrl)) {
135
+ const candidate = await parseFeedAt(fediverse);
136
+ if (candidate.feed)
137
+ return [candidate.feed];
121
138
  }
122
139
  // 3. Common feed paths; some lead to an overview page that lists the site's feeds.
123
140
  const probeBase = page.finalUrl || targetUrl;
@@ -176,6 +193,9 @@ export function extractFeedsFromHtml(html, baseUrl) {
176
193
  if (href.endsWith("/feed") || href.endsWith(".rss") || href.endsWith(".xml") || href.includes("/rss/")) {
177
194
  add(href, decodeEntities(stripHtmlTags(match[3]).trim()) || null, "application/rss+xml");
178
195
  }
196
+ else if (href.endsWith("/feed.json") || href.endsWith("/index.json")) {
197
+ add(href, decodeEntities(stripHtmlTags(match[3]).trim()) || null, "application/feed+json");
198
+ }
179
199
  }
180
200
  for (const match of decodeEntities(html).matchAll(FEED_URL_IN_TEXT)) {
181
201
  add(match[0], null, "application/rss+xml");
@@ -0,0 +1,240 @@
1
+ import Parser from "rss-parser";
2
+ import { normalizePublishedAt } from "./dates.js";
3
+ import { authorLine } from "./author.js";
4
+ import { unwrapRedirectLink } from "./redirectLinks.js";
5
+ import { decodeEntities, plainTitle } from "./text.js";
6
+ const xmlParser = new Parser({
7
+ customFields: {
8
+ feed: ["icon"],
9
+ item: [
10
+ ["media:content", "mediaContent", { keepArray: false }],
11
+ ["media:thumbnail", "mediaThumbnail", { keepArray: false }],
12
+ ["content:encoded", "contentEncoded", { keepArray: false }],
13
+ ],
14
+ },
15
+ });
16
+ function isRecord(value) {
17
+ return typeof value === "object" && value !== null && !Array.isArray(value);
18
+ }
19
+ function asNonEmptyString(value) {
20
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
21
+ }
22
+ function mediaAttribute(value, key) {
23
+ if (!isRecord(value))
24
+ return undefined;
25
+ if (isRecord(value.$) && value.$[key] !== undefined)
26
+ return value.$[key];
27
+ return value[key];
28
+ }
29
+ function cleanImageUrl(url) {
30
+ return url.trim().replace(/&(?:#038|amp);/g, "&");
31
+ }
32
+ function isValidImageUrl(url) {
33
+ if (typeof url !== "string")
34
+ return false;
35
+ let parsed;
36
+ try {
37
+ parsed = new URL(url.trim());
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
43
+ return false;
44
+ const host = parsed.hostname.toLowerCase();
45
+ if (host === "pixel.wp.com" || host.endsWith(".pixel.wp.com"))
46
+ return false;
47
+ const pathAndQuery = (parsed.pathname + parsed.search).toLowerCase();
48
+ if (pathAndQuery.includes("/1x1") || pathAndQuery.includes("pixel") || pathAndQuery.includes("tracking") || pathAndQuery.includes("beacon")) {
49
+ return false;
50
+ }
51
+ return true;
52
+ }
53
+ function firstHtmlImageUrl(html) {
54
+ if (typeof html !== "string" || !html.includes("<img"))
55
+ return null;
56
+ const match = html.match(/<img[^>]+src=["'](https?:\/\/[^"'\s>]+)["']/i);
57
+ return match && isValidImageUrl(match[1]) ? cleanImageUrl(match[1]) : null;
58
+ }
59
+ function extractXmlImageUrl(item) {
60
+ // 1. media:content (Media RSS)
61
+ const mediaContent = item.mediaContent ?? item["media:content"];
62
+ if (mediaContent) {
63
+ if (isValidImageUrl(mediaContent))
64
+ return cleanImageUrl(mediaContent);
65
+ const url = mediaAttribute(mediaContent, "url");
66
+ const medium = mediaAttribute(mediaContent, "medium");
67
+ const type = mediaAttribute(mediaContent, "type");
68
+ if (isValidImageUrl(url) && (medium === "image" || !medium || (typeof type === "string" && type.startsWith("image/")))) {
69
+ return cleanImageUrl(url);
70
+ }
71
+ }
72
+ // 2. media:thumbnail
73
+ const mediaThumbnail = item.mediaThumbnail ?? item["media:thumbnail"];
74
+ if (mediaThumbnail) {
75
+ if (isValidImageUrl(mediaThumbnail))
76
+ return cleanImageUrl(mediaThumbnail);
77
+ const url = mediaAttribute(mediaThumbnail, "url");
78
+ if (isValidImageUrl(url))
79
+ return cleanImageUrl(url);
80
+ }
81
+ // 3. enclosure
82
+ if (item.enclosure?.url) {
83
+ const url = item.enclosure.url;
84
+ const type = item.enclosure.type ?? "";
85
+ if (type.startsWith("image/") || /\.(jpe?g|png|webp|gif|avif|svg)(\?.*)?$/i.test(url)) {
86
+ if (isValidImageUrl(url))
87
+ return cleanImageUrl(url);
88
+ }
89
+ }
90
+ // 4. First <img> tag in HTML content or summary
91
+ return firstHtmlImageUrl(item.contentEncoded ?? item["content:encoded"] ?? item.content ?? item.summary ?? "");
92
+ }
93
+ function extractJsonFeedImageUrl(item, contentHtml) {
94
+ if (isValidImageUrl(item.image))
95
+ return cleanImageUrl(item.image);
96
+ if (isValidImageUrl(item.banner_image))
97
+ return cleanImageUrl(item.banner_image);
98
+ if (Array.isArray(item.attachments)) {
99
+ for (const attachment of item.attachments) {
100
+ if (!isRecord(attachment))
101
+ continue;
102
+ const mimeType = typeof attachment.mime_type === "string" ? attachment.mime_type.toLowerCase() : "";
103
+ if (mimeType.startsWith("image/") && isValidImageUrl(attachment.url)) {
104
+ return cleanImageUrl(attachment.url);
105
+ }
106
+ }
107
+ }
108
+ return firstHtmlImageUrl(contentHtml);
109
+ }
110
+ function extractJsonFeedAuthors(item) {
111
+ if (Array.isArray(item.authors)) {
112
+ return item.authors.map((entry) => (isRecord(entry) ? asNonEmptyString(entry.name) : undefined));
113
+ }
114
+ if (isRecord(item.author)) {
115
+ return [asNonEmptyString(item.author.name)];
116
+ }
117
+ return [];
118
+ }
119
+ function pushRawUrl(raw, into) {
120
+ if (typeof raw !== "string")
121
+ return;
122
+ const trimmed = raw.trim();
123
+ if (trimmed)
124
+ into.push(trimmed);
125
+ }
126
+ export function resolveFeedIconUrls(parsed, baseUrl) {
127
+ const resolve = (raw) => {
128
+ try {
129
+ const resolved = new URL(raw.trim(), baseUrl);
130
+ return resolved.protocol === "https:" || resolved.protocol === "http:" ? resolved.toString() : null;
131
+ }
132
+ catch {
133
+ return null;
134
+ }
135
+ };
136
+ return {
137
+ icons: parsed.icons.map(resolve).filter((url) => url !== null),
138
+ logos: parsed.logos.map(resolve).filter((url) => url !== null),
139
+ };
140
+ }
141
+ /**
142
+ * What identifies an item: its guid, or else its link or title. A guid element without text (`<guid isPermaLink="false"/>`) is read as an
143
+ * object, and one such entry must not make the whole feed unreadable.
144
+ */
145
+ export function itemGuid(item) {
146
+ if (typeof item.guid === "string" && item.guid !== "")
147
+ return item.guid;
148
+ return item.link || item.title || crypto.randomUUID();
149
+ }
150
+ /** The article address: its link, or its guid when the feed gives only that and the guid is a web address. */
151
+ export function itemLink(item) {
152
+ if (item.link)
153
+ return unwrapRedirectLink(item.link);
154
+ return item.guid && /^https?:\/\//i.test(item.guid) ? unwrapRedirectLink(item.guid) : undefined;
155
+ }
156
+ function parseJsonFeed(body) {
157
+ const raw = JSON.parse(body);
158
+ if (!isRecord(raw))
159
+ throw new Error("Invalid JSON feed: expected object");
160
+ if (typeof raw.version !== "string" || !/^https?:\/\/jsonfeed\.org\/version\/1(?:\.\d+)?$/i.test(raw.version.trim())) {
161
+ throw new Error("Invalid JSON feed: unsupported or missing version");
162
+ }
163
+ if (!Array.isArray(raw.items)) {
164
+ throw new Error("Invalid JSON feed: items must be an array");
165
+ }
166
+ const title = plainTitle(asNonEmptyString(raw.title));
167
+ const description = asNonEmptyString(raw.description);
168
+ if (!title && !description && raw.items.length === 0) {
169
+ throw new Error("Invalid JSON feed: empty feed");
170
+ }
171
+ const icons = [];
172
+ const logos = [];
173
+ pushRawUrl(raw.favicon, icons);
174
+ pushRawUrl(raw.icon, icons);
175
+ pushRawUrl(raw.icon, logos);
176
+ const items = [];
177
+ for (const entry of raw.items) {
178
+ if (!isRecord(entry))
179
+ continue;
180
+ const rawId = typeof entry.id === "string" && entry.id !== "" ? entry.id : typeof entry.id === "number" ? String(entry.id) : undefined;
181
+ const rawLink = asNonEmptyString(entry.url) ?? asNonEmptyString(entry.external_url);
182
+ const link = itemLink({ link: rawLink, guid: rawId });
183
+ const itemTitle = plainTitle(asNonEmptyString(entry.title));
184
+ const contentHtml = asNonEmptyString(entry.content_html) ?? null;
185
+ const snippetSource = asNonEmptyString(entry.summary) ?? asNonEmptyString(entry.content_text) ?? contentHtml ?? undefined;
186
+ items.push({
187
+ guid: itemGuid({ guid: rawId, link, title: itemTitle }),
188
+ title: itemTitle,
189
+ link,
190
+ contentSnippet: decodeEntities(snippetSource) ?? undefined,
191
+ contentHtml,
192
+ publishedAt: normalizePublishedAt(asNonEmptyString(entry.date_published) ?? asNonEmptyString(entry.date_modified)) ?? undefined,
193
+ imageUrl: extractJsonFeedImageUrl(entry, contentHtml),
194
+ authors: extractJsonFeedAuthors(entry),
195
+ });
196
+ }
197
+ return {
198
+ mimeType: "application/feed+json",
199
+ title,
200
+ description,
201
+ link: asNonEmptyString(raw.home_page_url),
202
+ icons,
203
+ logos,
204
+ items,
205
+ };
206
+ }
207
+ export async function parseFeedBody(body) {
208
+ if (body.trimStart().startsWith("{")) {
209
+ return parseJsonFeed(body);
210
+ }
211
+ const parsed = await xmlParser.parseString(body);
212
+ const icons = [];
213
+ const logos = [];
214
+ if (typeof parsed.icon === "string" && parsed.icon.trim())
215
+ icons.push(parsed.icon.trim());
216
+ if (typeof parsed.image?.url === "string" && parsed.image.url.trim())
217
+ logos.push(parsed.image.url.trim());
218
+ return {
219
+ mimeType: "application/rss+xml",
220
+ title: plainTitle(parsed.title),
221
+ description: asNonEmptyString(parsed.description),
222
+ link: asNonEmptyString(parsed.link),
223
+ icons,
224
+ logos,
225
+ items: parsed.items.map((item) => ({
226
+ guid: itemGuid(item),
227
+ title: plainTitle(item.title),
228
+ link: itemLink(item),
229
+ contentSnippet: decodeEntities(item.contentSnippet ?? item.content) ?? undefined,
230
+ contentHtml: item.contentEncoded ?? item["content:encoded"] ?? item.content ?? null,
231
+ publishedAt: normalizePublishedAt(item.isoDate ?? item.pubDate) ?? undefined,
232
+ imageUrl: extractXmlImageUrl(item),
233
+ authors: [item.creator, item.author],
234
+ })),
235
+ };
236
+ }
237
+ export function formatFeedAuthor(authors, feedTitle, feedUrl) {
238
+ return authorLine(authors, { title: feedTitle, url: feedUrl });
239
+ }
240
+ //# sourceMappingURL=feedParser.js.map
@@ -4,13 +4,22 @@
4
4
  */
5
5
  // Paths of medium.com that belong to the site, not to a writer or a publication.
6
6
  const MEDIUM_RESERVED = new Set(["", "feed", "m", "me", "plans", "membership", "search", "tag", "topics", "about", "jobs", "policy", "creators", "new-story", "settings", "library", "notifications"]);
7
+ const GITHUB_RESERVED = new Set([
8
+ "settings", "notifications", "explore", "topics", "trending", "collections", "events", "sponsors",
9
+ "login", "signup", "orgs", "users", "search", "marketplace", "features", "enterprise", "pricing",
10
+ "about", "security", "new", "organizations", "apps", "codespaces", "copilot", "pulls", "issues",
11
+ "discussions", "watching", "stars", "dashboard",
12
+ ]);
13
+ const YOUTUBE_CHANNEL_ID = /^UC[A-Za-z0-9_-]{10,64}$/;
14
+ const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
7
15
  export function platformFeedCandidates(url) {
8
16
  const host = url.hostname.toLowerCase().replace(/^(www|old|new|m)\./, "");
9
17
  const segments = url.pathname.split("/").filter(Boolean);
10
18
  if (host === "reddit.com") {
11
19
  // /r/name, /r/name/top, /user/name: every one of them has a feed at the end of its base path.
12
- if ((segments[0] === "r" || segments[0] === "user") && segments[1])
20
+ if ((segments[0] === "r" || segments[0] === "user") && segments[1] && SAFE_SEGMENT.test(segments[1])) {
13
21
  return [`https://www.reddit.com/${segments[0]}/${segments[1]}/.rss`];
22
+ }
14
23
  return [];
15
24
  }
16
25
  if (host === "medium.com") {
@@ -19,12 +28,76 @@ export function platformFeedCandidates(url) {
19
28
  return [];
20
29
  return [`https://medium.com/feed/${first}`];
21
30
  }
22
- if (host === "youtube.com" && url.pathname === "/playlist") {
23
- const list = url.searchParams.get("list");
24
- return list && /^[A-Za-z0-9_-]{10,64}$/.test(list) ? [`https://www.youtube.com/feeds/videos.xml?playlist_id=${list}`] : [];
31
+ if (host === "youtube.com") {
32
+ if (url.pathname === "/playlist") {
33
+ const list = url.searchParams.get("list");
34
+ return list && /^[A-Za-z0-9_-]{10,64}$/.test(list) ? [`https://www.youtube.com/feeds/videos.xml?playlist_id=${list}`] : [];
35
+ }
36
+ if (segments[0] === "channel" && segments[1] && YOUTUBE_CHANNEL_ID.test(segments[1])) {
37
+ return [`https://www.youtube.com/feeds/videos.xml?channel_id=${segments[1]}`];
38
+ }
39
+ return [];
40
+ }
41
+ if (host === "bsky.app") {
42
+ if (segments[0] === "profile" && segments[1] && /^[A-Za-z0-9._:-]{1,253}$/.test(segments[1])) {
43
+ return [`https://bsky.app/profile/${segments[1]}/rss`];
44
+ }
45
+ return [];
46
+ }
47
+ if (host === "github.com") {
48
+ const owner = segments[0];
49
+ if (!owner || GITHUB_RESERVED.has(owner.toLowerCase()))
50
+ return [];
51
+ if (segments.length >= 2 && SAFE_SEGMENT.test(owner) && SAFE_SEGMENT.test(segments[1])) {
52
+ const feedKind = segments[2] === "commits" ? "commits.atom" : "releases.atom";
53
+ return [`https://github.com/${owner}/${segments[1]}/${feedKind}`];
54
+ }
55
+ if (/^[A-Za-z0-9-]+$/.test(owner)) {
56
+ return [`https://github.com/${owner}.atom`];
57
+ }
58
+ return [];
59
+ }
60
+ if (host === "substack.com") {
61
+ if (segments[0]?.startsWith("@")) {
62
+ const handle = segments[0].slice(1);
63
+ if (/^[A-Za-z0-9_-]{1,64}$/.test(handle))
64
+ return [`https://${handle}.substack.com/feed`];
65
+ }
66
+ return [];
67
+ }
68
+ if (host.endsWith(".substack.com") && host !== "substack.com") {
69
+ return [`https://${host}/feed`];
70
+ }
71
+ if (host === "codeberg.org") {
72
+ if (segments.length >= 2 && SAFE_SEGMENT.test(segments[0]) && SAFE_SEGMENT.test(segments[1])) {
73
+ return [`https://codeberg.org/${segments[0]}/${segments[1]}/releases.rss`];
74
+ }
75
+ return [];
25
76
  }
26
77
  return [];
27
78
  }
79
+ /**
80
+ * Mastodon / Fediverse profiles (`https://instance/@handle`) expose an RSS feed at `/@handle.rss`,
81
+ * often without a `<link rel="alternate">` on their SPA shell. Checked as a fallback after HTML discovery.
82
+ */
83
+ export function fediverseFeedCandidate(url) {
84
+ const host = url.hostname.toLowerCase().replace(/^(www|m)\./, "");
85
+ if (host === "medium.com" || host === "youtube.com" || host === "substack.com" || host === "tiktok.com")
86
+ return null;
87
+ const segments = url.pathname.split("/").filter(Boolean);
88
+ if (segments[0]?.startsWith("@") && /^@[A-Za-z0-9_.-]{1,100}$/.test(segments[0])) {
89
+ return `${url.origin}/${segments[0]}.rss`;
90
+ }
91
+ return null;
92
+ }
93
+ /** Extracts a YouTube channel RSS feed URL from channel page HTML (`/@handle`, `/c/...`, `/user/...`). */
94
+ export function youtubeChannelFeedFromHtml(html, url) {
95
+ const host = url.hostname.toLowerCase().replace(/^(www|m)\./, "");
96
+ if (host !== "youtube.com")
97
+ return null;
98
+ const match = /"(?:externalId|channelId)"\s*:\s*"(UC[A-Za-z0-9_-]{10,64})"/.exec(html);
99
+ return match ? `https://www.youtube.com/feeds/videos.xml?channel_id=${match[1]}` : null;
100
+ }
28
101
  /** The numeric id of a show on Apple Podcasts (`…/podcast/name/id1204393114`), if the address is one. */
29
102
  export function applePodcastId(url) {
30
103
  if (url.hostname.toLowerCase() !== "podcasts.apple.com")
@@ -1,143 +1,16 @@
1
- import Parser from "rss-parser";
2
1
  import { fetchFeed } from "./fetcher.js";
3
2
  import { discoverIconUrls, iconCheckDue } from "./icon.js";
4
3
  import { refreshFeedIcon } from "./feedIcon.js";
5
- import { decodeEntities, plainTitle } from "./text.js";
6
- import { unwrapRedirectLink } from "./redirectLinks.js";
7
4
  import { enqueueNewItemNotifications, startPushOutbox, stopPushOutbox } from "../pushOutbox.js";
8
5
  import { hasUserCapability } from "../auth/capabilities.js";
9
6
  import { findFeedById, listSubscriberIds, updateFeedAfterPoll, updateFeedIcon, upsertItems } from "./repository.js";
10
7
  import { db } from "../db/index.js";
11
8
  import { configurePollHostCooldowns, PollQueue } from "./pollQueue.js";
12
9
  import { feedRequests, PollDeferredError, sourceHost } from "./requestGate.js";
13
- import { normalizePublishedAt } from "./dates.js";
14
- import { authorLine } from "./author.js";
15
10
  import { readPollSettings } from "./pollSettings.js";
11
+ import { formatFeedAuthor, itemGuid, itemLink, parseFeedBody, resolveFeedIconUrls } from "./feedParser.js";
12
+ export { itemGuid, itemLink };
16
13
  configurePollHostCooldowns();
17
- function mediaAttribute(value, key) {
18
- if (typeof value !== "object" || value === null)
19
- return undefined;
20
- const record = value;
21
- const attributes = record.$;
22
- if (typeof attributes === "object" && attributes !== null) {
23
- const nested = attributes[key];
24
- if (nested !== undefined)
25
- return nested;
26
- }
27
- return record[key];
28
- }
29
- const parser = new Parser({
30
- customFields: {
31
- feed: ["icon"],
32
- item: [
33
- ["media:content", "mediaContent", { keepArray: false }],
34
- ["media:thumbnail", "mediaThumbnail", { keepArray: false }],
35
- ["content:encoded", "contentEncoded", { keepArray: false }],
36
- ],
37
- },
38
- });
39
- /** The feed's own addresses: `icon` is meant as an icon, the `image` of an RSS channel is its logo and ranks below the site's icon files. */
40
- function extractFeedIconUrls(parsed, baseUrl) {
41
- const result = { icons: [], logos: [] };
42
- if (!parsed)
43
- return result;
44
- const read = (raw, into) => {
45
- if (typeof raw !== "string" || !raw.trim())
46
- return;
47
- try {
48
- const resolved = new URL(raw.trim(), baseUrl);
49
- if (resolved.protocol === "https:" || resolved.protocol === "http:")
50
- into.push(resolved.toString());
51
- }
52
- catch {
53
- // Ignore malformed feed icon URLs.
54
- }
55
- };
56
- read(parsed.icon, result.icons);
57
- read(parsed.image?.url, result.logos);
58
- return result;
59
- }
60
- function cleanImageUrl(url) {
61
- return url.trim().replace(/&(?:#038|amp);/g, "&");
62
- }
63
- function isValidImageUrl(url) {
64
- if (typeof url !== "string")
65
- return false;
66
- const trimmed = url.trim();
67
- let parsed;
68
- try {
69
- parsed = new URL(trimmed);
70
- }
71
- catch {
72
- return false;
73
- }
74
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
75
- return false;
76
- const host = parsed.hostname.toLowerCase();
77
- if (host === "pixel.wp.com" || host.endsWith(".pixel.wp.com"))
78
- return false;
79
- const pathAndQuery = (parsed.pathname + parsed.search).toLowerCase();
80
- if (pathAndQuery.includes("/1x1") || pathAndQuery.includes("pixel") || pathAndQuery.includes("tracking") || pathAndQuery.includes("beacon")) {
81
- return false;
82
- }
83
- return true;
84
- }
85
- function extractImageUrl(item) {
86
- // 1. media:content (Media RSS)
87
- const mediaContent = item.mediaContent ?? item["media:content"];
88
- if (mediaContent) {
89
- if (isValidImageUrl(mediaContent))
90
- return cleanImageUrl(mediaContent);
91
- const url = mediaAttribute(mediaContent, "url");
92
- const medium = mediaAttribute(mediaContent, "medium");
93
- const type = mediaAttribute(mediaContent, "type");
94
- if (isValidImageUrl(url) && (medium === "image" || !medium || (typeof type === "string" && type.startsWith("image/")))) {
95
- return cleanImageUrl(url);
96
- }
97
- }
98
- // 2. media:thumbnail
99
- const mediaThumbnail = item.mediaThumbnail ?? item["media:thumbnail"];
100
- if (mediaThumbnail) {
101
- if (isValidImageUrl(mediaThumbnail))
102
- return cleanImageUrl(mediaThumbnail);
103
- const url = mediaAttribute(mediaThumbnail, "url");
104
- if (isValidImageUrl(url))
105
- return cleanImageUrl(url);
106
- }
107
- // 3. enclosure
108
- if (item.enclosure?.url) {
109
- const url = item.enclosure.url;
110
- const type = item.enclosure.type ?? "";
111
- if (type.startsWith("image/") || /\.(jpe?g|png|webp|gif|avif|svg)(\?.*)?$/i.test(url)) {
112
- if (isValidImageUrl(url))
113
- return cleanImageUrl(url);
114
- }
115
- }
116
- // 4. First <img> tag in HTML content or summary
117
- const htmlContent = item.contentEncoded ?? item["content:encoded"] ?? item.content ?? item.summary ?? "";
118
- if (typeof htmlContent === "string" && htmlContent.includes("<img")) {
119
- const match = htmlContent.match(/<img[^>]+src=["'](https?:\/\/[^"'\s>]+)["']/i);
120
- if (match && isValidImageUrl(match[1])) {
121
- return cleanImageUrl(match[1]);
122
- }
123
- }
124
- return null;
125
- }
126
- /**
127
- * What identifies an item: its guid, or else its link or title. A guid element without text (`<guid isPermaLink="false"/>`) is read as an
128
- * object, and one such entry must not make the whole feed unreadable.
129
- */
130
- export function itemGuid(item) {
131
- if (typeof item.guid === "string" && item.guid !== "")
132
- return item.guid;
133
- return item.link || item.title || crypto.randomUUID();
134
- }
135
- /** The article address: its link, or its guid when the feed gives only that and the guid is a web address. */
136
- export function itemLink(item) {
137
- if (item.link)
138
- return unwrapRedirectLink(item.link);
139
- return item.guid && /^https?:\/\//i.test(item.guid) ? unwrapRedirectLink(item.guid) : undefined;
140
- }
141
14
  /**
142
15
  * Checks the feed's icon when it is due. The check starts right away but is not awaited, has its own deadline, and cannot retry or
143
16
  * fail a committed feed; downloads join the shared request limit as background work.
@@ -151,7 +24,7 @@ function scheduleIconMaintenance(feed, parsed) {
151
24
  try {
152
25
  const siteUrl = parsed?.link || feed.site_url;
153
26
  const htmlUrls = siteUrl ? await discoverIconUrls(siteUrl, signal) : [];
154
- const feedUrls = extractFeedIconUrls(parsed, siteUrl || feed.url);
27
+ const feedUrls = parsed ? resolveFeedIconUrls(parsed, siteUrl || feed.url) : { icons: [], logos: [] };
155
28
  signal.throwIfAborted();
156
29
  await refreshFeedIcon(feed.id, siteUrl, [...htmlUrls, ...feedUrls.icons], signal, feedUrls.logos);
157
30
  }
@@ -174,7 +47,7 @@ async function pollAttempt(feed, signal, interactive) {
174
47
  signal,
175
48
  priority: interactive ? "interactive" : "background",
176
49
  });
177
- const parsed = fetched.notModified ? null : await parser.parseString(fetched.body);
50
+ const parsed = fetched.notModified ? null : await parseFeedBody(fetched.body);
178
51
  signal.throwIfAborted();
179
52
  const current = findFeedById(feed.id);
180
53
  if (!current || current.url !== feed.url)
@@ -183,18 +56,20 @@ async function pollAttempt(feed, signal, interactive) {
183
56
  if (!feedHasActiveSubscriber(feed.id))
184
57
  return { newItems: 0, error: "feed_poll_not_allowed" };
185
58
  const items = parsed?.items.map(item => ({
186
- guid: itemGuid(item),
187
- title: plainTitle(item.title), link: itemLink(item),
188
- contentSnippet: decodeEntities(item.contentSnippet ?? item.content) ?? undefined,
189
- contentHtml: item.contentEncoded ?? item["content:encoded"] ?? item.content ?? null,
190
- publishedAt: normalizePublishedAt(item.isoDate ?? item.pubDate) ?? undefined, imageUrl: extractImageUrl(item),
191
- author: authorLine([item.creator, item.author], { title: current.title, url: current.site_url ?? current.url }),
59
+ guid: item.guid,
60
+ title: item.title,
61
+ link: item.link,
62
+ contentSnippet: item.contentSnippet,
63
+ contentHtml: item.contentHtml,
64
+ publishedAt: item.publishedAt,
65
+ imageUrl: item.imageUrl,
66
+ author: formatFeedAuthor(item.authors, current.title, current.site_url ?? current.url),
192
67
  }));
193
68
  // No await in this transaction. Items, health/validators and job completion become visible together.
194
69
  const newItems = db.transaction(() => {
195
70
  const count = items ? upsertItems(feed.id, items) : 0;
196
71
  updateFeedAfterPoll(feed.id, {
197
- ...(parsed ? { title: plainTitle(parsed.title), siteUrl: parsed.link, etag: fetched.etag, lastModified: fetched.lastModified } : {}),
72
+ ...(parsed ? { title: parsed.title, siteUrl: parsed.link, etag: fetched.etag, lastModified: fetched.lastModified } : {}),
198
73
  error: null,
199
74
  });
200
75
  if (count > 0 && feed.last_success_at)
@@ -246,7 +121,7 @@ export function pollingMetrics() { return pollingQueue().metrics(); }
246
121
  /** Fetch and parse a feed without storing anything, to validate a URL before switching to it. */
247
122
  export async function probeFeed(url) {
248
123
  const fetched = await fetchFeed(url, { priority: "interactive" });
249
- const parsed = await parser.parseString(fetched.body);
124
+ const parsed = await parseFeedBody(fetched.body);
250
125
  return { title: parsed.title ?? null, itemCount: parsed.items.length };
251
126
  }
252
127
  /**