rss-reader.js 31 KB

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