rss_agent.rb 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. require 'rss'
  2. require 'feed-normalizer'
  3. module Agents
  4. class RssAgent < Agent
  5. include WebRequestConcern
  6. cannot_receive_events!
  7. can_dry_run!
  8. default_schedule "every_1d"
  9. DEFAULT_EVENTS_ORDER = [['{{date_published}}', 'time'], ['{{last_updated}}', 'time']]
  10. description do
  11. <<-MD
  12. This Agent consumes RSS feeds and emits events when they change.
  13. This Agent is fairly simple, using [feed-normalizer](https://github.com/aasmith/feed-normalizer) as a base. For complex feeds
  14. with additional field types, we recommend using a WebsiteAgent. See [this example](https://github.com/cantino/huginn/wiki/Agent-configuration-examples#itunes-trailers).
  15. If you want to *output* an RSS feed, use the DataOutputAgent.
  16. Options:
  17. * `url` - The URL of the RSS feed (an array of URLs can also be used; items with identical guids across feeds will be considered duplicates).
  18. * `clean` - Attempt to use [feed-normalizer](https://github.com/aasmith/feed-normalizer)'s' `clean!` method to cleanup HTML in the feed. Set to `true` to use.
  19. * `expected_update_period_in_days` - How often you expect this RSS feed to change. If more than this amount of time passes without an update, the Agent will mark itself as not working.
  20. * `headers` - When present, it should be a hash of headers to send with the request.
  21. * `basic_auth` - Specify HTTP basic auth parameters: `"username:password"`, or `["username", "password"]`.
  22. * `disable_ssl_verification` - Set to `true` to disable ssl verification.
  23. * `disable_url_encoding` - Set to `true` to disable url encoding.
  24. * `user_agent` - A custom User-Agent name (default: "Faraday v#{Faraday::VERSION}").
  25. * `max_events_per_run` - Limit number of events created (items parsed) per run for feed.
  26. # Ordering Events
  27. #{description_events_order}
  28. In this Agent, the default value for `events_order` is `#{DEFAULT_EVENTS_ORDER.to_json}`.
  29. MD
  30. end
  31. def default_options
  32. {
  33. 'expected_update_period_in_days' => "5",
  34. 'clean' => 'false',
  35. 'url' => "https://github.com/cantino/huginn/commits/master.atom"
  36. }
  37. end
  38. event_description <<-MD
  39. Events look like:
  40. {
  41. "id": "829f845279611d7925146725317b868d",
  42. "date_published": "2014-09-11 01:30:00 -0700",
  43. "last_updated": "Thu, 11 Sep 2014 01:30:00 -0700",
  44. "url": "http://example.com/...",
  45. "urls": [ "http://example.com/..." ],
  46. "description": "Some description",
  47. "content": "Some content",
  48. "title": "Some title",
  49. "authors": [ ... ],
  50. "categories": [ ... ]
  51. }
  52. MD
  53. def working?
  54. event_created_within?((interpolated['expected_update_period_in_days'].presence || 10).to_i) && !recent_error_logs?
  55. end
  56. def validate_options
  57. errors.add(:base, "url is required") unless options['url'].present?
  58. unless options['expected_update_period_in_days'].present? && options['expected_update_period_in_days'].to_i > 0
  59. errors.add(:base, "Please provide 'expected_update_period_in_days' to indicate how many days can pass without an update before this Agent is considered to not be working")
  60. end
  61. validate_web_request_options!
  62. validate_events_order
  63. end
  64. def events_order
  65. super.presence || DEFAULT_EVENTS_ORDER
  66. end
  67. def check
  68. Array(interpolated['url']).each do |url|
  69. response = faraday.get(url)
  70. if response.success?
  71. feed = FeedNormalizer::FeedNormalizer.parse(response.body)
  72. feed.clean! if boolify(interpolated['clean'])
  73. max_events = (interpolated['max_events_per_run'].presence || 0).to_i
  74. created_event_count = 0
  75. sort_events(feed_to_events(feed)).each.with_index do |event, index|
  76. break if max_events && max_events > 0 && index >= max_events
  77. entry_id = event.payload[:id]
  78. if check_and_track(entry_id)
  79. created_event_count += 1
  80. create_event(event)
  81. end
  82. end
  83. log "Fetched #{url} and created #{created_event_count} event(s)."
  84. else
  85. error "Failed to fetch #{url}: #{response.inspect}"
  86. end
  87. end
  88. end
  89. protected
  90. def get_entry_id(entry)
  91. entry.id.presence || Digest::MD5.hexdigest(entry.content)
  92. end
  93. def check_and_track(entry_id)
  94. memory['seen_ids'] ||= []
  95. if memory['seen_ids'].include?(entry_id)
  96. false
  97. else
  98. memory['seen_ids'].unshift entry_id
  99. memory['seen_ids'].pop if memory['seen_ids'].length > 500
  100. true
  101. end
  102. end
  103. def feed_to_events(feed)
  104. feed.entries.map { |entry|
  105. Event.new(payload: {
  106. id: get_entry_id(entry),
  107. date_published: entry.date_published,
  108. last_updated: entry.last_updated,
  109. url: entry.url,
  110. urls: entry.urls,
  111. description: entry.description,
  112. content: entry.content,
  113. title: entry.title,
  114. authors: entry.authors,
  115. categories: entry.categories
  116. })
  117. }
  118. end
  119. end
  120. end