rss-reader.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. /**
  2. * @node rss-reader
  3. * @name RSS Reader
  4. * @category data
  5. * @version 1.2.0
  6. * @description Read and parse RSS/Atom feeds with optional filtering by keyword, date, or count. Supports stateful new item detection.
  7. * @icon rss
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. url: {
  13. type: 'string',
  14. title: 'Feed URL',
  15. description: 'URL of the RSS or Atom feed'
  16. },
  17. filterKeyword: {
  18. type: 'string',
  19. title: 'Keyword Filter',
  20. description: 'Filter items by keyword (matches title and description)'
  21. },
  22. filterNewerThan: {
  23. type: 'string',
  24. title: 'Newer Than',
  25. description: 'Only include items newer than this date (ISO 8601 format, e.g., 2024-01-15T00:00:00Z)'
  26. },
  27. maxItems: {
  28. type: 'number',
  29. title: 'Max Items',
  30. description: 'Maximum number of items to return (0 = unlimited)',
  31. default: 0
  32. },
  33. userAgent: {
  34. type: 'string',
  35. title: 'User-Agent',
  36. description: 'Sent with the request. Several feeds refuse an unnamed client outright - Reddit answers 403 - and some rate-limit a browser string harder than a named one. Identify yourself here',
  37. default: 'smartbotic-rss/1.0 (+https://smartbotics.ai)'
  38. },
  39. timeout: {
  40. type: 'number',
  41. title: 'Timeout (ms)',
  42. default: 30000
  43. },
  44. retries: {
  45. type: 'number', title: 'Retries', default: 2,
  46. description: 'Extra attempts when the feed times out or answers 429, 500, 502, 503 or 504. A feed that is briefly unreachable should not end a scheduled run'
  47. },
  48. retryDelayMs: {
  49. type: 'number', title: 'Retry Delay (ms)', default: 2000,
  50. description: 'Wait before the first retry. Doubles on each further attempt, and a Retry-After from the server wins over both'
  51. },
  52. retryMaxDelayMs: {
  53. type: 'number', title: 'Max Retry Delay (ms)', default: 30000,
  54. description: 'Upper bound for the backoff'
  55. },
  56. skipOnError: {
  57. type: 'boolean', title: 'Skip On Error', default: false,
  58. description: 'Return success false and no items instead of failing the workflow. For a workflow reading several feeds, this is what lets the others carry on when one is unreachable - without it the first bad feed ends the run'
  59. },
  60. detectNewItems: {
  61. type: 'boolean',
  62. title: 'Detect New Items',
  63. description: 'When enabled, only output items that have not been seen in previous executions',
  64. default: false
  65. },
  66. stateCollection: {
  67. type: 'string',
  68. title: 'State Collection',
  69. description: 'Select a read-write collection to store seen item identifiers',
  70. dynamicOptions: {
  71. source: 'storage.collections',
  72. labelField: 'name',
  73. valueField: 'name',
  74. filter: { access: 'read-write' }
  75. },
  76. showWhen: { field: 'detectNewItems', value: true }
  77. }
  78. },
  79. required: ['url']
  80. };
  81. const inputSchema = {
  82. type: 'object',
  83. properties: {
  84. url: {
  85. type: 'string',
  86. description: 'Override feed URL from input'
  87. },
  88. filterKeyword: {
  89. type: 'string',
  90. description: 'Override keyword filter from input'
  91. },
  92. filterNewerThan: {
  93. type: 'string',
  94. description: 'Override date filter from input'
  95. },
  96. maxItems: {
  97. type: 'number',
  98. description: 'Override max items from input'
  99. }
  100. }
  101. };
  102. const outputSchema = {
  103. type: 'object',
  104. properties: {
  105. success: { type: 'boolean', description: 'False when the feed could not be read and Skip On Error let the run carry on' },
  106. error: { type: 'string', description: 'Why it could not be read, when it could not' },
  107. feedTitle: { type: 'string', description: 'Title of the feed' },
  108. feedLink: { type: 'string', description: 'Link to the feed homepage' },
  109. feedDescription: { type: 'string', description: 'Description of the feed' },
  110. feedLanguage: { type: 'string', description: 'Language of the feed' },
  111. feedPubDate: { type: 'string', description: 'Publication date of the feed' },
  112. feedGenerator: { type: 'string', description: 'Generator of the feed' },
  113. feedImage: {
  114. type: 'object',
  115. description: 'Feed image/logo',
  116. properties: {
  117. url: { type: 'string' },
  118. title: { type: 'string' },
  119. link: { type: 'string' }
  120. }
  121. },
  122. itemCount: { type: 'number', description: 'Number of items returned' },
  123. newItemCount: { type: 'number', description: 'Items this run will process. With Detect New Items off that is every item returned, so a workflow can branch on this whichever mode it is in' },
  124. totalFeedItemCount: { type: 'number', description: 'Total items in feed before filtering (when detectNewItems is enabled)' },
  125. items: {
  126. type: 'array',
  127. description: 'Array of feed items',
  128. items: {
  129. type: 'object',
  130. properties: {
  131. title: { type: 'string', description: 'Item title' },
  132. link: { type: 'string', description: 'Item link/URL' },
  133. description: { type: 'string', description: 'Item summary/description' },
  134. content: { type: 'string', description: 'Full content (content:encoded)' },
  135. pubDate: { type: 'string', description: 'Publication date' },
  136. author: { type: 'string', description: 'Author name' },
  137. categories: { type: 'array', items: { type: 'string' }, description: 'Categories/tags' },
  138. guid: { type: 'string', description: 'Unique identifier' },
  139. comments: { type: 'string', description: 'Comments URL' },
  140. source: { type: 'string', description: 'Source attribution' },
  141. enclosure: {
  142. type: 'object',
  143. description: 'Media enclosure (attachment)',
  144. properties: {
  145. url: { type: 'string', description: 'Media URL' },
  146. type: { type: 'string', description: 'MIME type' },
  147. length: { type: 'number', description: 'File size in bytes' }
  148. }
  149. },
  150. media: {
  151. type: 'object',
  152. description: 'Media content (media:content)',
  153. properties: {
  154. url: { type: 'string' },
  155. type: { type: 'string' },
  156. width: { type: 'number' },
  157. height: { type: 'number' }
  158. }
  159. },
  160. thumbnail: {
  161. type: 'object',
  162. description: 'Thumbnail image (media:thumbnail)',
  163. properties: {
  164. url: { type: 'string' },
  165. width: { type: 'number' },
  166. height: { type: 'number' }
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. };
  174. /**
  175. * Simple XML parser utilities for RSS/Atom feeds
  176. * Handles basic XML structure without external dependencies
  177. */
  178. function xmlGetTagContent(xml, tagName) {
  179. var pattern = new RegExp('<' + tagName + '[^>]*>([\\s\\S]*?)<\\/' + tagName + '>', 'i');
  180. var match = xml.match(pattern);
  181. if (match) {
  182. return match[1].trim();
  183. }
  184. return null;
  185. }
  186. function xmlGetAllTagContents(xml, tagName) {
  187. var results = [];
  188. var regex = new RegExp('<' + tagName + '[^>]*>([\\s\\S]*?)<\\/' + tagName + '>', 'gi');
  189. var match;
  190. while ((match = regex.exec(xml)) !== null) {
  191. results.push(match[1].trim());
  192. }
  193. return results;
  194. }
  195. function xmlGetTagAttributes(xml, tagName) {
  196. // Match self-closing tag or opening tag
  197. var regex = new RegExp('<' + tagName + '([^>]*?)\\/?>', 'i');
  198. var match = xml.match(regex);
  199. if (!match) return null;
  200. var attrString = match[1];
  201. var attrs = {};
  202. // Parse attributes: name="value" or name='value'
  203. var attrRegex = /(\w+)=["']([^"']*)["']/g;
  204. var attrMatch;
  205. while ((attrMatch = attrRegex.exec(attrString)) !== null) {
  206. attrs[attrMatch[1]] = attrMatch[2];
  207. }
  208. return attrs;
  209. }
  210. function xmlDecodeHtmlEntities(text) {
  211. if (!text) return '';
  212. return text
  213. .replace(/&lt;/g, '<')
  214. .replace(/&gt;/g, '>')
  215. .replace(/&amp;/g, '&')
  216. .replace(/&quot;/g, '"')
  217. .replace(/&apos;/g, "'")
  218. .replace(/&#(\d+);/g, function(_, dec) { return String.fromCharCode(dec); })
  219. .replace(/&#x([0-9a-f]+);/gi, function(_, hex) { return String.fromCharCode(parseInt(hex, 16)); });
  220. }
  221. function xmlStripCdata(text) {
  222. if (!text) return '';
  223. return text.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1');
  224. }
  225. function xmlCleanText(text) {
  226. if (!text) return '';
  227. return xmlDecodeHtmlEntities(xmlStripCdata(text)).trim();
  228. }
  229. /**
  230. * Parse RSS 2.0 feed
  231. */
  232. function parseRss(xml) {
  233. var channel = xmlGetTagContent(xml, 'channel');
  234. if (!channel) {
  235. throw new Error('Invalid RSS feed: no channel element found');
  236. }
  237. var feedTitle = xmlGetTagContent(channel, 'title');
  238. var feedLink = xmlGetTagContent(channel, 'link');
  239. var feedDesc = xmlGetTagContent(channel, 'description');
  240. var feedLanguage = xmlGetTagContent(channel, 'language');
  241. var feedPubDate = xmlGetTagContent(channel, 'pubDate');
  242. var feedLastBuildDate = xmlGetTagContent(channel, 'lastBuildDate');
  243. var feedGenerator = xmlGetTagContent(channel, 'generator');
  244. var feedImage = xmlGetTagContent(channel, 'image');
  245. var feed = {
  246. title: xmlCleanText(feedTitle) || '',
  247. link: xmlCleanText(feedLink) || '',
  248. description: xmlCleanText(feedDesc) || '',
  249. language: xmlCleanText(feedLanguage) || '',
  250. pubDate: xmlCleanText(feedPubDate) || '',
  251. lastBuildDate: xmlCleanText(feedLastBuildDate) || '',
  252. generator: xmlCleanText(feedGenerator) || '',
  253. items: []
  254. };
  255. // Parse feed image if present
  256. if (feedImage) {
  257. feed.image = {
  258. url: xmlCleanText(xmlGetTagContent(feedImage, 'url')) || '',
  259. title: xmlCleanText(xmlGetTagContent(feedImage, 'title')) || '',
  260. link: xmlCleanText(xmlGetTagContent(feedImage, 'link')) || ''
  261. };
  262. }
  263. var itemRegex = /<item[^>]*>([\s\S]*?)<\/item>/gi;
  264. var match;
  265. while ((match = itemRegex.exec(channel)) !== null) {
  266. var itemXml = match[1];
  267. var catArray = xmlGetAllTagContents(itemXml, 'category');
  268. var categories = [];
  269. for (var ci = 0; ci < catArray.length; ci++) {
  270. categories.push(xmlCleanText(catArray[ci]));
  271. }
  272. var item = {
  273. title: xmlCleanText(xmlGetTagContent(itemXml, 'title')) || '',
  274. link: xmlCleanText(xmlGetTagContent(itemXml, 'link')) || '',
  275. description: xmlCleanText(xmlGetTagContent(itemXml, 'description')) || '',
  276. content: xmlCleanText(xmlGetTagContent(itemXml, 'content:encoded')) || '',
  277. pubDate: xmlCleanText(xmlGetTagContent(itemXml, 'pubDate')) || '',
  278. author: xmlCleanText(xmlGetTagContent(itemXml, 'author') ||
  279. xmlGetTagContent(itemXml, 'dc:creator')) || '',
  280. categories: categories,
  281. guid: xmlCleanText(xmlGetTagContent(itemXml, 'guid')) || '',
  282. comments: xmlCleanText(xmlGetTagContent(itemXml, 'comments')) || '',
  283. source: xmlCleanText(xmlGetTagContent(itemXml, 'source')) || ''
  284. };
  285. // Parse enclosure (media attachment)
  286. var enclosureAttrs = xmlGetTagAttributes(itemXml, 'enclosure');
  287. if (enclosureAttrs) {
  288. item.enclosure = {
  289. url: enclosureAttrs.url || '',
  290. type: enclosureAttrs.type || '',
  291. length: enclosureAttrs.length ? parseInt(enclosureAttrs.length, 10) : 0
  292. };
  293. }
  294. // Parse media:content (common in media RSS)
  295. var mediaAttrs = xmlGetTagAttributes(itemXml, 'media:content');
  296. if (mediaAttrs) {
  297. item.media = {
  298. url: mediaAttrs.url || '',
  299. type: mediaAttrs.type || mediaAttrs.medium || '',
  300. width: mediaAttrs.width ? parseInt(mediaAttrs.width, 10) : 0,
  301. height: mediaAttrs.height ? parseInt(mediaAttrs.height, 10) : 0
  302. };
  303. }
  304. // Parse media:thumbnail
  305. var thumbAttrs = xmlGetTagAttributes(itemXml, 'media:thumbnail');
  306. if (thumbAttrs) {
  307. item.thumbnail = {
  308. url: thumbAttrs.url || '',
  309. width: thumbAttrs.width ? parseInt(thumbAttrs.width, 10) : 0,
  310. height: thumbAttrs.height ? parseInt(thumbAttrs.height, 10) : 0
  311. };
  312. }
  313. feed.items.push(item);
  314. }
  315. return feed;
  316. }
  317. /**
  318. * Parse Atom feed
  319. */
  320. function parseAtom(xml) {
  321. var feedContent = xmlGetTagContent(xml, 'feed');
  322. if (!feedContent) {
  323. throw new Error('Invalid Atom feed: no feed element found');
  324. }
  325. function getAtomLink(content, rel) {
  326. var linkRegex = /<link([^>]*)>/gi;
  327. var match;
  328. while ((match = linkRegex.exec(content)) !== null) {
  329. var attrs = match[1];
  330. var relMatch = attrs.match(/rel=["']([^"']*)["']/);
  331. var hrefMatch = attrs.match(/href=["']([^"']*)["']/);
  332. if (hrefMatch) {
  333. var linkRel = relMatch ? relMatch[1] : 'alternate';
  334. if (linkRel === rel || (!rel && linkRel === 'alternate')) {
  335. return hrefMatch[1];
  336. }
  337. }
  338. }
  339. return '';
  340. }
  341. function getAtomLinkByType(content, type) {
  342. var linkRegex = /<link([^>]*)>/gi;
  343. var match;
  344. while ((match = linkRegex.exec(content)) !== null) {
  345. var attrs = match[1];
  346. var typeMatch = attrs.match(/type=["']([^"']*)["']/);
  347. var hrefMatch = attrs.match(/href=["']([^"']*)["']/);
  348. if (hrefMatch && typeMatch && typeMatch[1].indexOf(type) !== -1) {
  349. return {
  350. url: hrefMatch[1],
  351. type: typeMatch[1]
  352. };
  353. }
  354. }
  355. return null;
  356. }
  357. var feed = {
  358. title: xmlCleanText(xmlGetTagContent(feedContent, 'title')) || '',
  359. link: getAtomLink(feedContent, 'alternate') || getAtomLink(feedContent, null) || '',
  360. description: xmlCleanText(xmlGetTagContent(feedContent, 'subtitle')) || '',
  361. language: '',
  362. pubDate: xmlCleanText(xmlGetTagContent(feedContent, 'updated')) || '',
  363. lastBuildDate: '',
  364. generator: xmlCleanText(xmlGetTagContent(feedContent, 'generator')) || '',
  365. items: []
  366. };
  367. // Parse feed icon/logo
  368. var feedIcon = xmlGetTagContent(feedContent, 'icon');
  369. var feedLogo = xmlGetTagContent(feedContent, 'logo');
  370. if (feedIcon || feedLogo) {
  371. feed.image = {
  372. url: xmlCleanText(feedLogo || feedIcon) || '',
  373. title: feed.title,
  374. link: feed.link
  375. };
  376. }
  377. var entryRegex = /<entry[^>]*>([\s\S]*?)<\/entry>/gi;
  378. var match;
  379. while ((match = entryRegex.exec(feedContent)) !== null) {
  380. var entryXml = match[1];
  381. var categories = [];
  382. var catRegex = /<category([^>]*)>/gi;
  383. var catMatch;
  384. while ((catMatch = catRegex.exec(entryXml)) !== null) {
  385. var termMatch = catMatch[1].match(/term=["']([^"']*)["']/);
  386. if (termMatch) {
  387. categories.push(xmlCleanText(termMatch[1]));
  388. }
  389. }
  390. var author = '';
  391. var authorContent = xmlGetTagContent(entryXml, 'author');
  392. if (authorContent) {
  393. author = xmlCleanText(xmlGetTagContent(authorContent, 'name')) || '';
  394. }
  395. var pubDate = xmlCleanText(
  396. xmlGetTagContent(entryXml, 'published') ||
  397. xmlGetTagContent(entryXml, 'updated')
  398. ) || '';
  399. var summary = xmlCleanText(xmlGetTagContent(entryXml, 'summary')) || '';
  400. var content = xmlCleanText(xmlGetTagContent(entryXml, 'content')) || '';
  401. var item = {
  402. title: xmlCleanText(xmlGetTagContent(entryXml, 'title')) || '',
  403. link: getAtomLink(entryXml, 'alternate') || getAtomLink(entryXml, null) || '',
  404. description: summary || content,
  405. content: content,
  406. pubDate: pubDate,
  407. author: author,
  408. categories: categories,
  409. guid: xmlCleanText(xmlGetTagContent(entryXml, 'id')) || '',
  410. comments: '',
  411. source: ''
  412. };
  413. // Check for enclosure link
  414. var enclosureLink = getAtomLinkByType(entryXml, 'image');
  415. if (!enclosureLink) {
  416. enclosureLink = getAtomLinkByType(entryXml, 'audio');
  417. }
  418. if (!enclosureLink) {
  419. enclosureLink = getAtomLinkByType(entryXml, 'video');
  420. }
  421. if (enclosureLink) {
  422. item.enclosure = {
  423. url: enclosureLink.url,
  424. type: enclosureLink.type,
  425. length: 0
  426. };
  427. }
  428. // Parse media:content
  429. var mediaAttrs = xmlGetTagAttributes(entryXml, 'media:content');
  430. if (mediaAttrs) {
  431. item.media = {
  432. url: mediaAttrs.url || '',
  433. type: mediaAttrs.type || mediaAttrs.medium || '',
  434. width: mediaAttrs.width ? parseInt(mediaAttrs.width, 10) : 0,
  435. height: mediaAttrs.height ? parseInt(mediaAttrs.height, 10) : 0
  436. };
  437. }
  438. // Parse media:thumbnail
  439. var thumbAttrs = xmlGetTagAttributes(entryXml, 'media:thumbnail');
  440. if (thumbAttrs) {
  441. item.thumbnail = {
  442. url: thumbAttrs.url || '',
  443. width: thumbAttrs.width ? parseInt(thumbAttrs.width, 10) : 0,
  444. height: thumbAttrs.height ? parseInt(thumbAttrs.height, 10) : 0
  445. };
  446. }
  447. feed.items.push(item);
  448. }
  449. return feed;
  450. }
  451. /**
  452. * Parse date string to timestamp
  453. */
  454. function parseDate(dateStr) {
  455. if (!dateStr) return 0;
  456. var timestamp = Date.parse(dateStr);
  457. if (!isNaN(timestamp)) {
  458. return timestamp;
  459. }
  460. var rfc822Regex = /(\d{1,2})\s+(\w{3})\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})/;
  461. var match = dateStr.match(rfc822Regex);
  462. if (match) {
  463. var months = {
  464. Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
  465. Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11
  466. };
  467. var day = parseInt(match[1], 10);
  468. var month = months[match[2]];
  469. var year = parseInt(match[3], 10);
  470. var hour = parseInt(match[4], 10);
  471. var minute = parseInt(match[5], 10);
  472. var second = parseInt(match[6], 10);
  473. if (month !== undefined) {
  474. return new Date(year, month, day, hour, minute, second).getTime();
  475. }
  476. }
  477. return 0;
  478. }
  479. /**
  480. * Filter items by keyword
  481. */
  482. function filterByKeyword(items, keyword) {
  483. if (!keyword) return items;
  484. var lowerKeyword = keyword.toLowerCase();
  485. var result = [];
  486. for (var i = 0; i < items.length; i++) {
  487. var item = items[i];
  488. var title = (item.title || '').toLowerCase();
  489. var description = (item.description || '').toLowerCase();
  490. if (title.indexOf(lowerKeyword) !== -1 || description.indexOf(lowerKeyword) !== -1) {
  491. result.push(item);
  492. }
  493. }
  494. return result;
  495. }
  496. /**
  497. * Filter items by date
  498. */
  499. function filterByDate(items, newerThanStr) {
  500. if (!newerThanStr) return items;
  501. var threshold = parseDate(newerThanStr);
  502. if (threshold === 0) {
  503. smartbotic.log.warn('Could not parse date filter: ' + newerThanStr);
  504. return items;
  505. }
  506. var result = [];
  507. for (var i = 0; i < items.length; i++) {
  508. var item = items[i];
  509. var itemDate = parseDate(item.pubDate);
  510. if (itemDate > threshold) {
  511. result.push(item);
  512. }
  513. }
  514. return result;
  515. }
  516. /**
  517. * Limit number of items
  518. */
  519. function limitItems(items, maxItems) {
  520. if (!maxItems || maxItems <= 0) return items;
  521. return items.slice(0, maxItems);
  522. }
  523. /**
  524. * Get unique identifier for an RSS/Atom item
  525. * Prefers GUID, falls back to link
  526. */
  527. function getItemIdentifier(item) {
  528. return item.guid || item.link || '';
  529. }
  530. /**
  531. * Generate a stable document ID from feed URL for state storage
  532. */
  533. function generateStateDocId(feedUrl) {
  534. // Create a simple hash from the feed URL for a stable doc ID
  535. var hash = 0;
  536. for (var i = 0; i < feedUrl.length; i++) {
  537. var char = feedUrl.charCodeAt(i);
  538. hash = ((hash << 5) - hash) + char;
  539. hash = hash & hash; // Convert to 32-bit integer
  540. }
  541. return 'rss-state-' + Math.abs(hash).toString(36);
  542. }
  543. /**
  544. * Load seen item identifiers from storage
  545. */
  546. function loadSeenItems(collection, feedUrl) {
  547. var docId = generateStateDocId(feedUrl);
  548. try {
  549. var result = smartbotic.storage.get(collection, docId);
  550. if (result.found && result.document && result.document.seenIds) {
  551. // Use plain object as a set (for QuickJS compatibility)
  552. var seenObj = {};
  553. var storedIds = result.document.seenIds;
  554. // Handle both array format and object format (in case of legacy data)
  555. if (Array.isArray(storedIds)) {
  556. smartbotic.log.debug('Loaded ' + storedIds.length + ' seen item IDs from storage');
  557. for (var i = 0; i < storedIds.length; i++) {
  558. seenObj[storedIds[i]] = true;
  559. }
  560. } else if (typeof storedIds === 'object' && storedIds !== null) {
  561. // Object format - keys are the IDs
  562. var keys = Object.keys(storedIds);
  563. smartbotic.log.debug('Loaded ' + keys.length + ' seen item IDs from storage (object format)');
  564. for (var j = 0; j < keys.length; j++) {
  565. seenObj[keys[j]] = true;
  566. }
  567. }
  568. return {
  569. seenIds: seenObj,
  570. docId: docId,
  571. exists: true,
  572. version: result.document._version || 1
  573. };
  574. }
  575. } catch (error) {
  576. smartbotic.log.warn('Error loading seen items from storage: ' + error.message);
  577. }
  578. return {
  579. seenIds: {},
  580. docId: docId,
  581. exists: false,
  582. version: 0
  583. };
  584. }
  585. /**
  586. * Save seen item identifiers to storage
  587. */
  588. function saveSeenItems(collection, docId, seenIds, feedUrl, exists, version) {
  589. // Convert object keys to array
  590. var seenArray = Object.keys(seenIds);
  591. var documentData = {
  592. feedUrl: feedUrl,
  593. seenIds: seenArray,
  594. lastUpdated: new Date().toISOString(),
  595. itemCount: seenArray.length
  596. };
  597. try {
  598. if (exists) {
  599. // Update existing document
  600. var updateResult = smartbotic.storage.update(collection, docId, documentData, version, false);
  601. if (!updateResult.success) {
  602. smartbotic.log.error('Failed to update seen items: ' + updateResult.error);
  603. return false;
  604. }
  605. smartbotic.log.debug('Updated ' + seenArray.length + ' seen item IDs in storage');
  606. } else {
  607. // Insert new document
  608. var insertResult = smartbotic.storage.insert(collection, documentData, docId, 0);
  609. if (!insertResult.success) {
  610. // If insert fails because document exists, try update instead
  611. if (insertResult.error && insertResult.error.indexOf('already exists') !== -1) {
  612. smartbotic.log.debug('Document exists, trying update instead');
  613. var retryResult = smartbotic.storage.update(collection, docId, documentData, 0, false);
  614. if (!retryResult.success) {
  615. smartbotic.log.error('Failed to update seen items on retry: ' + retryResult.error);
  616. return false;
  617. }
  618. smartbotic.log.debug('Updated ' + seenArray.length + ' seen item IDs in storage (retry)');
  619. } else {
  620. smartbotic.log.error('Failed to save seen items: ' + insertResult.error);
  621. return false;
  622. }
  623. } else {
  624. smartbotic.log.debug('Saved ' + seenArray.length + ' seen item IDs to storage');
  625. }
  626. }
  627. return true;
  628. } catch (error) {
  629. smartbotic.log.error('Error saving seen items to storage: ' + error.message);
  630. return false;
  631. }
  632. }
  633. /**
  634. * Filter items to only include new (unseen) items
  635. */
  636. function filterNewItems(items, seenIds) {
  637. var newItems = [];
  638. for (var i = 0; i < items.length; i++) {
  639. var id = getItemIdentifier(items[i]);
  640. if (id && !seenIds[id]) {
  641. newItems.push(items[i]);
  642. }
  643. }
  644. return newItems;
  645. }
  646. async function readFeed(config, input) {
  647. var url = input.url || config.url;
  648. var filterKeyword = input.filterKeyword || config.filterKeyword;
  649. var filterNewerThan = input.filterNewerThan || config.filterNewerThan;
  650. var maxItems = input.maxItems !== undefined ? input.maxItems : config.maxItems;
  651. var timeout = config.timeout || 30000;
  652. var detectNewItems = config.detectNewItems || false;
  653. var stateCollection = config.stateCollection;
  654. if (!url) {
  655. throw new Error('Feed URL is required');
  656. }
  657. // Validate stateful mode configuration
  658. if (detectNewItems && !stateCollection) {
  659. throw new Error('State collection is required when "Detect New Items" is enabled. Please select a read-write collection in the workflow storage settings.');
  660. }
  661. // No User-Agent at all is what several feeds reject, Reddit among them, so
  662. // there is always one.
  663. var userAgent = String(config.userAgent || '').trim() ||
  664. 'smartbotic-rss/1.0 (+https://smartbotics.ai)';
  665. smartbotic.log.info('Fetching RSS/Atom feed from ' + url);
  666. var response = smartbotic.http.request({
  667. method: 'GET',
  668. url: url,
  669. timeout: timeout,
  670. // Reading a feed is safe to repeat, and a feed that times out once is
  671. // the usual reason a scheduled run dies - the request is retried rather
  672. // than the whole pass being thrown away. Handled by the HTTP helper, so
  673. // the waiting happens without this node holding a loop.
  674. retries: config.retries !== undefined && config.retries !== null && config.retries !== ''
  675. ? Number(config.retries) : 2,
  676. retryDelayMs: Number(config.retryDelayMs) || 2000,
  677. retryMaxDelayMs: Number(config.retryMaxDelayMs) || 30000,
  678. headers: {
  679. 'Accept': 'application/rss+xml, application/atom+xml, application/xml, text/xml, */*',
  680. 'User-Agent': userAgent
  681. }
  682. });
  683. if (response.status < 200 || response.status >= 300) {
  684. var hint = '';
  685. if (response.status === 403) {
  686. hint = '. The feed refused this client - most feeds that do this want a descriptive ' +
  687. 'User-Agent, which is the User-Agent setting on this node';
  688. } else if (response.status === 429) {
  689. hint = '. The feed is rate limiting this address - poll it less often, or from ' +
  690. 'somewhere else. Reddit throttles hard and counts every request, including ' +
  691. 'failed ones';
  692. } else if (response.status === 404) {
  693. hint = '. Check the address: ' + url;
  694. }
  695. throw new Error('Failed to fetch feed: HTTP ' + response.status + hint);
  696. }
  697. var xml = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
  698. if (!xml || xml.trim().length === 0) {
  699. throw new Error('Empty response from feed URL');
  700. }
  701. var feed;
  702. if (xml.indexOf('<feed') !== -1 && xml.indexOf('xmlns') !== -1 && xml.indexOf('atom') !== -1) {
  703. smartbotic.log.debug('Detected Atom feed format');
  704. feed = parseAtom(xml);
  705. } else if (xml.indexOf('<rss') !== -1 || xml.indexOf('<channel') !== -1) {
  706. smartbotic.log.debug('Detected RSS feed format');
  707. feed = parseRss(xml);
  708. } else {
  709. throw new Error('Unknown feed format: neither RSS nor Atom detected');
  710. }
  711. var items = feed.items;
  712. var totalFeedItemCount = items.length;
  713. // Apply standard filters first (keyword, date)
  714. if (filterKeyword) {
  715. smartbotic.log.debug('Filtering by keyword: ' + filterKeyword);
  716. items = filterByKeyword(items, filterKeyword);
  717. }
  718. if (filterNewerThan) {
  719. smartbotic.log.debug('Filtering items newer than: ' + filterNewerThan);
  720. items = filterByDate(items, filterNewerThan);
  721. }
  722. // Stateful new item detection
  723. var newItemCount = items.length;
  724. var stateInfo = null;
  725. if (detectNewItems) {
  726. smartbotic.log.info('Detecting new items using collection: ' + stateCollection);
  727. // Load previously seen items
  728. stateInfo = loadSeenItems(stateCollection, url);
  729. // Filter to only new items
  730. var newItems = filterNewItems(items, stateInfo.seenIds);
  731. newItemCount = newItems.length;
  732. smartbotic.log.info('Found ' + newItemCount + ' new items out of ' + items.length + ' filtered items');
  733. // Update seen IDs with all current items (both new and previously seen)
  734. // This ensures we track all items from the current feed
  735. for (var i = 0; i < items.length; i++) {
  736. var id = getItemIdentifier(items[i]);
  737. if (id) {
  738. stateInfo.seenIds[id] = true;
  739. }
  740. }
  741. // Use only new items for output
  742. items = newItems;
  743. }
  744. // Apply max items limit last
  745. if (maxItems && maxItems > 0) {
  746. smartbotic.log.debug('Limiting to ' + maxItems + ' items');
  747. items = limitItems(items, maxItems);
  748. }
  749. smartbotic.log.info('Returning ' + items.length + ' items from feed');
  750. // Persist seen items state after successful processing
  751. if (detectNewItems && stateInfo) {
  752. var saved = saveSeenItems(
  753. stateCollection,
  754. stateInfo.docId,
  755. stateInfo.seenIds,
  756. url,
  757. stateInfo.exists,
  758. stateInfo.version
  759. );
  760. if (!saved) {
  761. smartbotic.log.warn('Failed to persist seen items state, but continuing with output');
  762. }
  763. }
  764. var result = {
  765. feedTitle: feed.title,
  766. feedLink: feed.link,
  767. feedDescription: feed.description,
  768. itemCount: items.length,
  769. items: items
  770. };
  771. // Always reported, in both modes.
  772. //
  773. // These used to appear only when Detect New Items was on, so a workflow
  774. // branching on newItemCount > 0 quietly started taking the other branch the
  775. // moment someone turned detection off: the field was not zero, it was gone,
  776. // and a comparison against a missing field is false. With detection off
  777. // every item returned is one this run will process, so newItemCount is the
  778. // item count - which is what a workflow asking "is there anything to do?"
  779. // means either way.
  780. result.newItemCount = detectNewItems ? newItemCount : items.length;
  781. result.totalFeedItemCount = detectNewItems ? totalFeedItemCount : items.length;
  782. return result;
  783. }
  784. async function execute(config, input) {
  785. try {
  786. var result = await readFeed(config, input);
  787. result.success = true;
  788. result.error = '';
  789. return result;
  790. } catch (err) {
  791. if (config.skipOnError !== true) {
  792. throw err;
  793. }
  794. var message = (err && err.message) ? err.message : String(err);
  795. smartbotic.log.warn('RSS Reader: ' + (config.url || '') + ' could not be read, skipping: ' + message);
  796. // Shaped like a successful read with nothing in it, so a merge or a
  797. // loop downstream does not have to know the difference - and carrying
  798. // the reason means a run that produced nothing can still say why.
  799. return {
  800. success: false,
  801. error: message,
  802. feedTitle: '',
  803. feedLink: '',
  804. feedDescription: '',
  805. itemCount: 0,
  806. items: [],
  807. newItemCount: 0,
  808. totalFeedItemCount: 0
  809. };
  810. }
  811. }
  812. module.exports = { configSchema, inputSchema, outputSchema, execute };