rss-reader.js 32 KB

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