website_agent.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. require 'nokogiri'
  2. require 'date'
  3. module Agents
  4. class WebsiteAgent < Agent
  5. include WebRequestConcern
  6. can_dry_run!
  7. default_schedule "every_12h"
  8. UNIQUENESS_LOOK_BACK = 200
  9. UNIQUENESS_FACTOR = 3
  10. description <<-MD
  11. The WebsiteAgent scrapes a website, XML document, or JSON feed and creates Events based on the results.
  12. Specify a `url` and select a `mode` for when to create Events based on the scraped data, either `all` or `on_change`.
  13. `url` can be a single url, or an array of urls (for example, for multiple pages with the exact same structure but different content to scrape)
  14. The `type` value can be `xml`, `html`, `json`, or `text`.
  15. To tell the Agent how to parse the content, specify `extract` as a hash with keys naming the extractions and values of hashes.
  16. When parsing HTML or XML, these sub-hashes specify how each extraction should be done. The Agent first selects a node set from the document for each extraction key by evaluating either a CSS selector in `css` or an XPath expression in `xpath`. It then evaluates an XPath expression in `value` on each node in the node set, converting the result into string. Here's an example:
  17. "extract": {
  18. "url": { "css": "#comic img", "value": "@src" },
  19. "title": { "css": "#comic img", "value": "@title" },
  20. "body_text": { "css": "div.main", "value": ".//text()" }
  21. }
  22. "@_attr_" is the XPath expression to extract the value of an attribute named _attr_ from a node, and ".//text()" is to extract all the enclosed texts. You can also use [XPath functions](http://www.w3.org/TR/xpath/#section-String-Functions) like `normalize-space` to strip and squeeze whitespace, `substring-after` to extract part of a text, and `translate` to remove comma from a formatted number, etc. Note that these functions take a string, not a node set, so what you may think would be written as `normalize-space(.//text())` should actually be `normalize-space(.)`.
  23. When parsing JSON, these sub-hashes specify [JSONPaths](http://goessner.net/articles/JsonPath/) to the values that you care about. For example:
  24. "extract": {
  25. "title": { "path": "results.data[*].title" },
  26. "description": { "path": "results.data[*].description" }
  27. }
  28. When parsing text, each sub-hash should contain a `regexp` and `index`. Output text is matched against the regular expression repeatedly from the beginning through to the end, collecting a captured group specified by `index` in each match. Each index should be either an integer or a string name which corresponds to <code>(?&lt;<em>name</em>&gt;...)</code>. For example, to parse lines of <code><em>word</em>: <em>definition</em></code>, the following should work:
  29. "extract": {
  30. "word": { "regexp": "^(.+?): (.+)$", index: 1 },
  31. "definition": { "regexp": "^(.+?): (.+)$", index: 2 }
  32. }
  33. Or if you prefer names to numbers for index:
  34. "extract": {
  35. "word": { "regexp": "^(?<word>.+?): (?<definition>.+)$", index: 'word' },
  36. "definition": { "regexp": "^(?<word>.+?): (?<definition>.+)$", index: 'definition' }
  37. }
  38. To extract the whole content as one event:
  39. "extract": {
  40. "content": { "regexp": "\A(?m:.)*\z", index: 0 }
  41. }
  42. Beware that `.` does not match the newline character (LF) unless the `m` flag is in effect, and `^`/`$` basically match every line beginning/end. See [this document](http://ruby-doc.org/core-#{RUBY_VERSION}/doc/regexp_rdoc.html) to learn the regular expression variant used in this service.
  43. Note that for all of the formats, whatever you extract MUST have the same number of matches for each extractor. E.g., if you're extracting rows, all extractors must match all rows. For generating CSS selectors, something like [SelectorGadget](http://selectorgadget.com) may be helpful.
  44. Can be configured to use HTTP basic auth by including the `basic_auth` parameter with `"username:password"`, or `["username", "password"]`.
  45. Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent. This is only used to set the "working" status.
  46. Set `uniqueness_look_back` to limit the number of events checked for uniqueness (typically for performance). This defaults to the larger of #{UNIQUENESS_LOOK_BACK} or #{UNIQUENESS_FACTOR}x the number of detected received results.
  47. Set `force_encoding` to an encoding name if the website does not return a Content-Type header with a proper charset.
  48. Set `user_agent` to a custom User-Agent name if the website does not like the default value (`#{default_user_agent}`).
  49. The `headers` field is optional. When present, it should be a hash of headers to send with the request.
  50. Set `disable_ssl_verification` to `true` to disable ssl verification.
  51. Set `unzip` to `gzip` to inflate the resource using gzip.
  52. The WebsiteAgent can also scrape based on incoming events. It will scrape the url contained in the `url` key of the incoming event payload. If you specify `merge` as the mode, it will retain the old payload and update it with the new values.
  53. In Liquid templating, the following variable is available:
  54. * `_response_`: A response object with the following keys:
  55. * `status`: HTTP status as integer. (Almost always 200)
  56. * `headers`: Response headers; for example, `{{ _response_.headers.Content-Type }}` expands to the value of the Content-Type header. Keys are insensitive to cases and -/_.
  57. MD
  58. event_description do
  59. "Events will have the following fields:\n\n %s" % [
  60. Utils.pretty_print(Hash[options['extract'].keys.map { |key|
  61. [key, "..."]
  62. }])
  63. ]
  64. end
  65. def working?
  66. event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
  67. end
  68. def default_options
  69. {
  70. 'expected_update_period_in_days' => "2",
  71. 'url' => "http://xkcd.com",
  72. 'type' => "html",
  73. 'mode' => "on_change",
  74. 'extract' => {
  75. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  76. 'title' => { 'css' => "#comic img", 'value' => "@alt" },
  77. 'hovertext' => { 'css' => "#comic img", 'value' => "@title" }
  78. }
  79. }
  80. end
  81. def validate_options
  82. # Check for required fields
  83. errors.add(:base, "url and expected_update_period_in_days are required") unless options['expected_update_period_in_days'].present? && options['url'].present?
  84. if !options['extract'].present? && extraction_type != "json"
  85. errors.add(:base, "extract is required for all types except json")
  86. end
  87. # Check for optional fields
  88. if options['mode'].present?
  89. errors.add(:base, "mode must be set to on_change, all or merge") unless %w[on_change all merge].include?(options['mode'])
  90. end
  91. if options['expected_update_period_in_days'].present?
  92. errors.add(:base, "Invalid expected_update_period_in_days format") unless is_positive_integer?(options['expected_update_period_in_days'])
  93. end
  94. if options['uniqueness_look_back'].present?
  95. errors.add(:base, "Invalid uniqueness_look_back format") unless is_positive_integer?(options['uniqueness_look_back'])
  96. end
  97. if (encoding = options['force_encoding']).present?
  98. case encoding
  99. when String
  100. begin
  101. Encoding.find(encoding)
  102. rescue ArgumentError
  103. errors.add(:base, "Unknown encoding: #{encoding.inspect}")
  104. end
  105. else
  106. errors.add(:base, "force_encoding must be a string")
  107. end
  108. end
  109. validate_web_request_options!
  110. validate_extract_options!
  111. end
  112. def validate_extract_options!
  113. if extraction_type == "json" && interpolated['extract'].is_a?(Hash)
  114. unless interpolated['extract'].all? { |name, details| details.is_a?(Hash) && details['path'].present? }
  115. errors.add(:base, 'When type is json, all extractions must have a path attribute.')
  116. end
  117. end
  118. end
  119. def check
  120. check_urls(interpolated['url'])
  121. end
  122. def check_urls(in_url)
  123. return unless in_url.present?
  124. Array(in_url).each do |url|
  125. check_url(url)
  126. end
  127. end
  128. def check_url(url, payload = {})
  129. log "Fetching #{url}"
  130. response = faraday.get(url)
  131. raise "Failed: #{response.inspect}" unless response.success?
  132. interpolation_context.stack {
  133. interpolation_context['_response_'] = ResponseDrop.new(response)
  134. body = response.body
  135. if (encoding = interpolated['force_encoding']).present?
  136. body = body.encode(Encoding::UTF_8, encoding)
  137. end
  138. if interpolated['unzip'] == "gzip"
  139. body = ActiveSupport::Gzip.decompress(body)
  140. end
  141. doc = parse(body)
  142. if extract_full_json?
  143. if store_payload!(previous_payloads(1), doc)
  144. log "Storing new result for '#{name}': #{doc.inspect}"
  145. create_event payload: payload.merge(doc)
  146. end
  147. return
  148. end
  149. output =
  150. case extraction_type
  151. when 'json'
  152. extract_json(doc)
  153. when 'text'
  154. extract_text(doc)
  155. else
  156. extract_xml(doc)
  157. end
  158. num_unique_lengths = interpolated['extract'].keys.map { |name| output[name].length }.uniq
  159. if num_unique_lengths.length != 1
  160. raise "Got an uneven number of matches for #{interpolated['name']}: #{interpolated['extract'].inspect}"
  161. end
  162. old_events = previous_payloads num_unique_lengths.first
  163. num_unique_lengths.first.times do |index|
  164. result = {}
  165. interpolated['extract'].keys.each do |name|
  166. result[name] = output[name][index]
  167. if name.to_s == 'url'
  168. result[name] = (response.env[:url] + result[name]).to_s
  169. end
  170. end
  171. if store_payload!(old_events, result)
  172. log "Storing new parsed result for '#{name}': #{result.inspect}"
  173. create_event payload: payload.merge(result)
  174. end
  175. end
  176. }
  177. rescue => e
  178. error "Error when fetching url: #{e.message}\n#{e.backtrace.join("\n")}"
  179. end
  180. def receive(incoming_events)
  181. incoming_events.each do |event|
  182. interpolate_with(event) do
  183. url_to_scrape = event.payload['url']
  184. next unless url_to_scrape =~ /^https?:\/\//i
  185. check_url(url_to_scrape,
  186. interpolated['mode'].to_s == "merge" ? event.payload : {})
  187. end
  188. end
  189. end
  190. private
  191. # This method returns true if the result should be stored as a new event.
  192. # If mode is set to 'on_change', this method may return false and update an existing
  193. # event to expire further in the future.
  194. def store_payload!(old_events, result)
  195. case interpolated['mode'].presence
  196. when 'on_change'
  197. result_json = result.to_json
  198. if found = old_events.find { |event| event.payload.to_json == result_json }
  199. found.update!(expires_at: new_event_expiration_date)
  200. false
  201. else
  202. true
  203. end
  204. when 'all', 'merge', ''
  205. true
  206. else
  207. raise "Illegal options[mode]: #{interpolated['mode']}"
  208. end
  209. end
  210. def previous_payloads(num_events)
  211. if interpolated['uniqueness_look_back'].present?
  212. look_back = interpolated['uniqueness_look_back'].to_i
  213. else
  214. # Larger of UNIQUENESS_FACTOR * num_events and UNIQUENESS_LOOK_BACK
  215. look_back = UNIQUENESS_FACTOR * num_events
  216. if look_back < UNIQUENESS_LOOK_BACK
  217. look_back = UNIQUENESS_LOOK_BACK
  218. end
  219. end
  220. events.order("id desc").limit(look_back) if interpolated['mode'] == "on_change"
  221. end
  222. def extract_full_json?
  223. !interpolated['extract'].present? && extraction_type == "json"
  224. end
  225. def extraction_type
  226. (interpolated['type'] || begin
  227. case interpolated['url']
  228. when /\.(rss|xml)$/i
  229. "xml"
  230. when /\.json$/i
  231. "json"
  232. when /\.(txt|text)$/i
  233. "text"
  234. else
  235. "html"
  236. end
  237. end).to_s
  238. end
  239. def extract_each(doc, &block)
  240. interpolated['extract'].each_with_object({}) { |(name, extraction_details), output|
  241. output[name] = block.call(extraction_details)
  242. }
  243. end
  244. def extract_json(doc)
  245. extract_each(doc) { |extraction_details|
  246. result = Utils.values_at(doc, extraction_details['path'])
  247. log "Extracting #{extraction_type} at #{extraction_details['path']}: #{result}"
  248. result
  249. }
  250. end
  251. def extract_text(doc)
  252. extract_each(doc) { |extraction_details|
  253. regexp = Regexp.new(extraction_details['regexp'])
  254. result = []
  255. doc.scan(regexp) {
  256. result << Regexp.last_match[extraction_details['index']]
  257. }
  258. log "Extracting #{extraction_type} at #{regexp}: #{result}"
  259. result
  260. }
  261. end
  262. def extract_xml(doc)
  263. extract_each(doc) { |extraction_details|
  264. case
  265. when css = extraction_details['css']
  266. nodes = doc.css(css)
  267. when xpath = extraction_details['xpath']
  268. doc.remove_namespaces! # ignore xmlns, useful when parsing atom feeds
  269. nodes = doc.xpath(xpath)
  270. else
  271. raise '"css" or "xpath" is required for HTML or XML extraction'
  272. end
  273. case nodes
  274. when Nokogiri::XML::NodeSet
  275. result = nodes.map { |node|
  276. case value = node.xpath(extraction_details['value'])
  277. when Float
  278. # Node#xpath() returns any numeric value as float;
  279. # convert it to integer as appropriate.
  280. value = value.to_i if value.to_i == value
  281. end
  282. value.to_s
  283. }
  284. else
  285. raise "The result of HTML/XML extraction was not a NodeSet"
  286. end
  287. log "Extracting #{extraction_type} at #{xpath || css}: #{result}"
  288. result
  289. }
  290. end
  291. def parse(data)
  292. case extraction_type
  293. when "xml"
  294. Nokogiri::XML(data)
  295. when "json"
  296. JSON.parse(data)
  297. when "html"
  298. Nokogiri::HTML(data)
  299. when "text"
  300. data
  301. else
  302. raise "Unknown extraction type #{extraction_type}"
  303. end
  304. end
  305. def is_positive_integer?(value)
  306. Integer(value) >= 0
  307. rescue
  308. false
  309. end
  310. # Wraps Faraday::Response
  311. class ResponseDrop < LiquidDroppable::Drop
  312. def headers
  313. HeaderDrop.new(@object.headers)
  314. end
  315. # Integer value of HTTP status
  316. def status
  317. @object.status
  318. end
  319. end
  320. # Wraps Faraday::Utils::Headers
  321. class HeaderDrop < LiquidDroppable::Drop
  322. def before_method(name)
  323. @object[name.tr('_', '-')]
  324. end
  325. end
  326. end
  327. end