website_agent.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. require 'nokogiri'
  2. require 'date'
  3. module Agents
  4. class WebsiteAgent < Agent
  5. include WebRequestConcern
  6. can_dry_run!
  7. can_order_created_events!
  8. default_schedule "every_12h"
  9. UNIQUENESS_LOOK_BACK = 200
  10. UNIQUENESS_FACTOR = 3
  11. description <<-MD
  12. The Website Agent scrapes a website, XML document, or JSON feed and creates Events based on the results.
  13. Specify a `url` and select a `mode` for when to create Events based on the scraped data, either `all` or `on_change`.
  14. `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)
  15. The WebsiteAgent can also scrape based on incoming events. It will scrape the url contained in the `url` key of the incoming event payload, or if you set `url_from_event` it is used as a Liquid template to generate the url to access. If you specify `merge` as the `mode`, it will retain the old payload and update it with the new values.
  16. # Supported Document Types
  17. The `type` value can be `xml`, `html`, `json`, or `text`.
  18. To tell the Agent how to parse the content, specify `extract` as a hash with keys naming the extractions and values of hashes.
  19. 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.
  20. # Scraping HTML and XML
  21. 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` (default: `.`) on each node in the node set, converting the result into string. Here's an example:
  22. "extract": {
  23. "url": { "css": "#comic img", "value": "@src" },
  24. "title": { "css": "#comic img", "value": "@title" },
  25. "body_text": { "css": "div.main", "value": ".//text()" }
  26. }
  27. "@_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. To extract the innerHTML, use "./node()"; and to extract the outer HTML, use ".".
  28. 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(.)`.
  29. Beware that when parsing an XML document (i.e. `type` is `xml`) using `xpath` expressions all namespaces are stripped from the document unless a toplevel option `use_namespaces` is set to true.
  30. # Scraping JSON
  31. When parsing JSON, these sub-hashes specify [JSONPaths](http://goessner.net/articles/JsonPath/) to the values that you care about. For example:
  32. "extract": {
  33. "title": { "path": "results.data[*].title" },
  34. "description": { "path": "results.data[*].description" }
  35. }
  36. # Scraping Text
  37. 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:
  38. "extract": {
  39. "word": { "regexp": "^(.+?): (.+)$", index: 1 },
  40. "definition": { "regexp": "^(.+?): (.+)$", index: 2 }
  41. }
  42. Or if you prefer names to numbers for index:
  43. "extract": {
  44. "word": { "regexp": "^(?<word>.+?): (?<definition>.+)$", index: 'word' },
  45. "definition": { "regexp": "^(?<word>.+?): (?<definition>.+)$", index: 'definition' }
  46. }
  47. To extract the whole content as one event:
  48. "extract": {
  49. "content": { "regexp": "\A(?m:.)*\z", index: 0 }
  50. }
  51. 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.
  52. # General Options
  53. Can be configured to use HTTP basic auth by including the `basic_auth` parameter with `"username:password"`, or `["username", "password"]`.
  54. 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.
  55. 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.
  56. Set `force_encoding` to an encoding name if the website is known to respond with a missing, invalid or wrong charset in the Content-Type header. Note that a text content without a charset is taken as encoded in UTF-8 (not ISO-8859-1).
  57. Set `user_agent` to a custom User-Agent name if the website does not like the default value (`#{default_user_agent}`).
  58. The `headers` field is optional. When present, it should be a hash of headers to send with the request.
  59. Set `disable_ssl_verification` to `true` to disable ssl verification.
  60. Set `unzip` to `gzip` to inflate the resource using gzip.
  61. # Liquid Templating
  62. In Liquid templating, the following variable is available:
  63. * `_response_`: A response object with the following keys:
  64. * `status`: HTTP status as integer. (Almost always 200)
  65. * `headers`: Response headers; for example, `{{ _response_.headers.Content-Type }}` expands to the value of the Content-Type header. Keys are insensitive to cases and -/_.
  66. # Ordering Events
  67. #{description_events_order}
  68. MD
  69. event_description do
  70. "Events will have the following fields:\n\n %s" % [
  71. Utils.pretty_print(Hash[options['extract'].keys.map { |key|
  72. [key, "..."]
  73. }])
  74. ]
  75. end
  76. def working?
  77. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  78. end
  79. def default_options
  80. {
  81. 'expected_update_period_in_days' => "2",
  82. 'url' => "http://xkcd.com",
  83. 'type' => "html",
  84. 'mode' => "on_change",
  85. 'extract' => {
  86. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  87. 'title' => { 'css' => "#comic img", 'value' => "@alt" },
  88. 'hovertext' => { 'css' => "#comic img", 'value' => "@title" }
  89. }
  90. }
  91. end
  92. def validate_options
  93. # Check for required fields
  94. errors.add(:base, "either url or url_from_event is required") unless options['url'].present? || options['url_from_event'].present?
  95. errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present?
  96. validate_extract_options!
  97. # Check for optional fields
  98. if options['mode'].present?
  99. errors.add(:base, "mode must be set to on_change, all or merge") unless %w[on_change all merge].include?(options['mode'])
  100. end
  101. if options['expected_update_period_in_days'].present?
  102. errors.add(:base, "Invalid expected_update_period_in_days format") unless is_positive_integer?(options['expected_update_period_in_days'])
  103. end
  104. if options['uniqueness_look_back'].present?
  105. errors.add(:base, "Invalid uniqueness_look_back format") unless is_positive_integer?(options['uniqueness_look_back'])
  106. end
  107. validate_web_request_options!
  108. end
  109. def validate_extract_options!
  110. extraction_type = (extraction_type() rescue extraction_type(options))
  111. case extract = options['extract']
  112. when Hash
  113. if extract.each_value.any? { |value| !value.is_a?(Hash) }
  114. errors.add(:base, 'extract must be a hash of hashes.')
  115. else
  116. case extraction_type
  117. when 'html', 'xml'
  118. extract.each do |name, details|
  119. case details['css']
  120. when String
  121. # ok
  122. when nil
  123. case details['xpath']
  124. when String
  125. # ok
  126. when nil
  127. errors.add(:base, "When type is html or xml, all extractions must have a css or xpath attribute (bad extraction details for #{name.inspect})")
  128. else
  129. errors.add(:base, "Wrong type of \"xpath\" value in extraction details for #{name.inspect}")
  130. end
  131. else
  132. errors.add(:base, "Wrong type of \"css\" value in extraction details for #{name.inspect}")
  133. end
  134. case details['value']
  135. when String, nil
  136. # ok
  137. else
  138. errors.add(:base, "Wrong type of \"value\" value in extraction details for #{name.inspect}")
  139. end
  140. end
  141. when 'json'
  142. extract.each do |name, details|
  143. case details['path']
  144. when String
  145. # ok
  146. when nil
  147. errors.add(:base, "When type is json, all extractions must have a path attribute (bad extraction details for #{name.inspect})")
  148. else
  149. errors.add(:base, "Wrong type of \"path\" value in extraction details for #{name.inspect}")
  150. end
  151. end
  152. when 'text'
  153. extract.each do |name, details|
  154. case regexp = details['regexp']
  155. when String
  156. begin
  157. re = Regexp.new(regexp)
  158. rescue => e
  159. errors.add(:base, "invalid regexp for #{name.inspect}: #{e.message}")
  160. end
  161. when nil
  162. errors.add(:base, "When type is text, all extractions must have a regexp attribute (bad extraction details for #{name.inspect})")
  163. else
  164. errors.add(:base, "Wrong type of \"regexp\" value in extraction details for #{name.inspect}")
  165. end
  166. case index = details['index']
  167. when Integer, /\A\d+\z/
  168. # ok
  169. when String
  170. if re && !re.names.include?(index)
  171. errors.add(:base, "no named capture #{index.inspect} found in regexp for #{name.inspect})")
  172. end
  173. when nil
  174. errors.add(:base, "When type is text, all extractions must have an index attribute (bad extraction details for #{name.inspect})")
  175. else
  176. errors.add(:base, "Wrong type of \"index\" value in extraction details for #{name.inspect}")
  177. end
  178. end
  179. when /\{/
  180. # Liquid templating
  181. else
  182. errors.add(:base, "Unknown extraction type #{extraction_type.inspect}")
  183. end
  184. end
  185. when nil
  186. unless extraction_type == 'json'
  187. errors.add(:base, 'extract is required for all types except json')
  188. end
  189. else
  190. errors.add(:base, 'extract must be a hash')
  191. end
  192. end
  193. def check
  194. check_urls(interpolated['url'])
  195. end
  196. def check_urls(in_url)
  197. return unless in_url.present?
  198. Array(in_url).each do |url|
  199. check_url(url)
  200. end
  201. end
  202. def check_url(url, payload = {})
  203. unless /\Ahttps?:\/\//i === url
  204. error "Ignoring a non-HTTP url: #{url.inspect}"
  205. return
  206. end
  207. log "Fetching #{url}"
  208. response = faraday.get(url)
  209. raise "Failed: #{response.inspect}" unless response.success?
  210. interpolation_context.stack {
  211. interpolation_context['_response_'] = ResponseDrop.new(response)
  212. body = response.body
  213. doc = parse(body)
  214. if extract_full_json?
  215. if store_payload!(previous_payloads(1), doc)
  216. log "Storing new result for '#{name}': #{doc.inspect}"
  217. create_event payload: payload.merge(doc)
  218. end
  219. return
  220. end
  221. output =
  222. case extraction_type
  223. when 'json'
  224. extract_json(doc)
  225. when 'text'
  226. extract_text(doc)
  227. else
  228. extract_xml(doc)
  229. end
  230. num_unique_lengths = interpolated['extract'].keys.map { |name| output[name].length }.uniq
  231. if num_unique_lengths.length != 1
  232. raise "Got an uneven number of matches for #{interpolated['name']}: #{interpolated['extract'].inspect}"
  233. end
  234. old_events = previous_payloads num_unique_lengths.first
  235. num_unique_lengths.first.times do |index|
  236. result = {}
  237. interpolated['extract'].keys.each do |name|
  238. result[name] = output[name][index]
  239. if name.to_s == 'url'
  240. result[name] = (response.env[:url] + result[name]).to_s
  241. end
  242. end
  243. if store_payload!(old_events, result)
  244. log "Storing new parsed result for '#{name}': #{result.inspect}"
  245. create_event payload: payload.merge(result)
  246. end
  247. end
  248. }
  249. rescue => e
  250. error "Error when fetching url: #{e.message}\n#{e.backtrace.join("\n")}"
  251. end
  252. def receive(incoming_events)
  253. incoming_events.each do |event|
  254. interpolate_with(event) do
  255. url_to_scrape =
  256. if url_template = options['url_from_event'].presence
  257. interpolate_string(url_template)
  258. else
  259. event.payload['url']
  260. end
  261. check_url(url_to_scrape,
  262. interpolated['mode'].to_s == "merge" ? event.payload : {})
  263. end
  264. end
  265. end
  266. private
  267. # This method returns true if the result should be stored as a new event.
  268. # If mode is set to 'on_change', this method may return false and update an existing
  269. # event to expire further in the future.
  270. def store_payload!(old_events, result)
  271. case interpolated['mode'].presence
  272. when 'on_change'
  273. result_json = result.to_json
  274. if found = old_events.find { |event| event.payload.to_json == result_json }
  275. found.update!(expires_at: new_event_expiration_date)
  276. false
  277. else
  278. true
  279. end
  280. when 'all', 'merge', ''
  281. true
  282. else
  283. raise "Illegal options[mode]: #{interpolated['mode']}"
  284. end
  285. end
  286. def previous_payloads(num_events)
  287. if interpolated['uniqueness_look_back'].present?
  288. look_back = interpolated['uniqueness_look_back'].to_i
  289. else
  290. # Larger of UNIQUENESS_FACTOR * num_events and UNIQUENESS_LOOK_BACK
  291. look_back = UNIQUENESS_FACTOR * num_events
  292. if look_back < UNIQUENESS_LOOK_BACK
  293. look_back = UNIQUENESS_LOOK_BACK
  294. end
  295. end
  296. events.order("id desc").limit(look_back) if interpolated['mode'] == "on_change"
  297. end
  298. def extract_full_json?
  299. !interpolated['extract'].present? && extraction_type == "json"
  300. end
  301. def extraction_type(interpolated = interpolated())
  302. (interpolated['type'] || begin
  303. case interpolated['url']
  304. when /\.(rss|xml)$/i
  305. "xml"
  306. when /\.json$/i
  307. "json"
  308. when /\.(txt|text)$/i
  309. "text"
  310. else
  311. "html"
  312. end
  313. end).to_s
  314. end
  315. def use_namespaces?
  316. if value = interpolated.key?('use_namespaces')
  317. boolify(interpolated['use_namespaces'])
  318. else
  319. interpolated['extract'].none? { |name, extraction_details|
  320. extraction_details.key?('xpath')
  321. }
  322. end
  323. end
  324. def extract_each(&block)
  325. interpolated['extract'].each_with_object({}) { |(name, extraction_details), output|
  326. output[name] = block.call(extraction_details)
  327. }
  328. end
  329. def extract_json(doc)
  330. extract_each { |extraction_details|
  331. result = Utils.values_at(doc, extraction_details['path'])
  332. log "Extracting #{extraction_type} at #{extraction_details['path']}: #{result}"
  333. result
  334. }
  335. end
  336. def extract_text(doc)
  337. extract_each { |extraction_details|
  338. regexp = Regexp.new(extraction_details['regexp'])
  339. case index = extraction_details['index']
  340. when /\A\d+\z/
  341. index = index.to_i
  342. end
  343. result = []
  344. doc.scan(regexp) {
  345. result << Regexp.last_match[index]
  346. }
  347. log "Extracting #{extraction_type} at #{regexp}: #{result}"
  348. result
  349. }
  350. end
  351. def extract_xml(doc)
  352. extract_each { |extraction_details|
  353. case
  354. when css = extraction_details['css']
  355. nodes = doc.css(css)
  356. when xpath = extraction_details['xpath']
  357. nodes = doc.xpath(xpath)
  358. else
  359. raise '"css" or "xpath" is required for HTML or XML extraction'
  360. end
  361. case nodes
  362. when Nokogiri::XML::NodeSet
  363. result = nodes.map { |node|
  364. case value = node.xpath(extraction_details['value'] || '.')
  365. when Float
  366. # Node#xpath() returns any numeric value as float;
  367. # convert it to integer as appropriate.
  368. value = value.to_i if value.to_i == value
  369. end
  370. value.to_s
  371. }
  372. else
  373. raise "The result of HTML/XML extraction was not a NodeSet"
  374. end
  375. log "Extracting #{extraction_type} at #{xpath || css}: #{result}"
  376. result
  377. }
  378. end
  379. def parse(data)
  380. case type = extraction_type
  381. when "xml"
  382. doc = Nokogiri::XML(data)
  383. # ignore xmlns, useful when parsing atom feeds
  384. doc.remove_namespaces! unless use_namespaces?
  385. doc
  386. when "json"
  387. JSON.parse(data)
  388. when "html"
  389. Nokogiri::HTML(data)
  390. when "text"
  391. data
  392. else
  393. raise "Unknown extraction type: #{type}"
  394. end
  395. end
  396. def is_positive_integer?(value)
  397. Integer(value) >= 0
  398. rescue
  399. false
  400. end
  401. # Wraps Faraday::Response
  402. class ResponseDrop < LiquidDroppable::Drop
  403. def headers
  404. HeaderDrop.new(@object.headers)
  405. end
  406. # Integer value of HTTP status
  407. def status
  408. @object.status
  409. end
  410. end
  411. # Wraps Faraday::Utils::Headers
  412. class HeaderDrop < LiquidDroppable::Drop
  413. def before_method(name)
  414. @object[name.tr('_', '-')]
  415. end
  416. end
  417. end
  418. end