Нет описания http://j1x-huginn.herokuapp.com

website_agent.rb 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. 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.
  52. In Liquid templating, the following variable is available:
  53. * `_response_`: A response object with the following keys:
  54. * `status`: HTTP status as integer. (Almost always 200)
  55. * `headers`: Reponse headers; for example, `{{ _response_.headers.Content-Type }}` expands to the value of the Content-Type header. Keys are insentitive to cases and -/_.
  56. MD
  57. event_description do
  58. "Events will have the following fields:\n\n %s" % [
  59. Utils.pretty_print(Hash[options['extract'].keys.map { |key|
  60. [key, "..."]
  61. }])
  62. ]
  63. end
  64. def working?
  65. event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
  66. end
  67. def default_options
  68. {
  69. 'expected_update_period_in_days' => "2",
  70. 'url' => "http://xkcd.com",
  71. 'type' => "html",
  72. 'mode' => "on_change",
  73. 'extract' => {
  74. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  75. 'title' => { 'css' => "#comic img", 'value' => "@alt" },
  76. 'hovertext' => { 'css' => "#comic img", 'value' => "@title" }
  77. }
  78. }
  79. end
  80. def validate_options
  81. # Check for required fields
  82. errors.add(:base, "url and expected_update_period_in_days are required") unless options['expected_update_period_in_days'].present? && options['url'].present?
  83. if !options['extract'].present? && extraction_type != "json"
  84. errors.add(:base, "extract is required for all types except json")
  85. end
  86. # Check for optional fields
  87. if options['mode'].present?
  88. errors.add(:base, "mode must be set to on_change, all or merge") unless %w[on_change all merge].include?(options['mode'])
  89. end
  90. if options['expected_update_period_in_days'].present?
  91. errors.add(:base, "Invalid expected_update_period_in_days format") unless is_positive_integer?(options['expected_update_period_in_days'])
  92. end
  93. if options['uniqueness_look_back'].present?
  94. errors.add(:base, "Invalid uniqueness_look_back format") unless is_positive_integer?(options['uniqueness_look_back'])
  95. end
  96. if (encoding = options['force_encoding']).present?
  97. case encoding
  98. when String
  99. begin
  100. Encoding.find(encoding)
  101. rescue ArgumentError
  102. errors.add(:base, "Unknown encoding: #{encoding.inspect}")
  103. end
  104. else
  105. errors.add(:base, "force_encoding must be a string")
  106. end
  107. end
  108. validate_web_request_options!
  109. end
  110. def check
  111. check_urls(interpolated['url'])
  112. end
  113. def check_urls(in_url)
  114. return unless in_url.present?
  115. Array(in_url).each do |url|
  116. check_url(url)
  117. end
  118. end
  119. def check_url(url, payload = {})
  120. log "Fetching #{url}"
  121. response = faraday.get(url)
  122. raise "Failed: #{response.inspect}" unless response.success?
  123. interpolation_context.stack {
  124. interpolation_context['_response_'] = ResponseDrop.new(response)
  125. body = response.body
  126. if (encoding = interpolated['force_encoding']).present?
  127. body = body.encode(Encoding::UTF_8, encoding)
  128. end
  129. doc = parse(body)
  130. if extract_full_json?
  131. if store_payload!(previous_payloads(1), doc)
  132. log "Storing new result for '#{name}': #{doc.inspect}"
  133. create_event payload: payload.merge(doc)
  134. end
  135. return
  136. end
  137. output =
  138. case extraction_type
  139. when 'json'
  140. extract_json(doc)
  141. when 'text'
  142. extract_text(doc)
  143. else
  144. extract_xml(doc)
  145. end
  146. num_unique_lengths = interpolated['extract'].keys.map { |name| output[name].length }.uniq
  147. if num_unique_lengths.length != 1
  148. raise "Got an uneven number of matches for #{interpolated['name']}: #{interpolated['extract'].inspect}"
  149. end
  150. old_events = previous_payloads num_unique_lengths.first
  151. num_unique_lengths.first.times do |index|
  152. result = {}
  153. interpolated['extract'].keys.each do |name|
  154. result[name] = output[name][index]
  155. if name.to_s == 'url'
  156. result[name] = (response.env[:url] + result[name]).to_s
  157. end
  158. end
  159. if store_payload!(old_events, result)
  160. log "Storing new parsed result for '#{name}': #{result.inspect}"
  161. create_event payload: payload.merge(result)
  162. end
  163. end
  164. }
  165. rescue => e
  166. error "Error when fetching url: #{e.message}\n#{e.backtrace.join("\n")}"
  167. end
  168. def receive(incoming_events)
  169. incoming_events.each do |event|
  170. interpolate_with(event) do
  171. url_to_scrape = event.payload['url']
  172. next unless url_to_scrape =~ /^https?:\/\//i
  173. check_url(url_to_scrape,
  174. interpolated['mode'].to_s == "merge" ? event.payload : {})
  175. end
  176. end
  177. end
  178. private
  179. # This method returns true if the result should be stored as a new event.
  180. # If mode is set to 'on_change', this method may return false and update an existing
  181. # event to expire further in the future.
  182. def store_payload!(old_events, result)
  183. case interpolated['mode'].presence
  184. when 'on_change'
  185. result_json = result.to_json
  186. old_events.each do |old_event|
  187. if old_event.payload.to_json == result_json
  188. old_event.expires_at = new_event_expiration_date
  189. old_event.save!
  190. return false
  191. end
  192. end
  193. true
  194. when 'all', 'merge', ''
  195. true
  196. else
  197. raise "Illegal options[mode]: #{interpolated['mode']}"
  198. end
  199. end
  200. def previous_payloads(num_events)
  201. if interpolated['uniqueness_look_back'].present?
  202. look_back = interpolated['uniqueness_look_back'].to_i
  203. else
  204. # Larger of UNIQUENESS_FACTOR * num_events and UNIQUENESS_LOOK_BACK
  205. look_back = UNIQUENESS_FACTOR * num_events
  206. if look_back < UNIQUENESS_LOOK_BACK
  207. look_back = UNIQUENESS_LOOK_BACK
  208. end
  209. end
  210. events.order("id desc").limit(look_back) if interpolated['mode'] == "on_change"
  211. end
  212. def extract_full_json?
  213. !interpolated['extract'].present? && extraction_type == "json"
  214. end
  215. def extraction_type
  216. (interpolated['type'] || begin
  217. case interpolated['url']
  218. when /\.(rss|xml)$/i
  219. "xml"
  220. when /\.json$/i
  221. "json"
  222. when /\.(txt|text)$/i
  223. "text"
  224. else
  225. "html"
  226. end
  227. end).to_s
  228. end
  229. def extract_each(doc, &block)
  230. interpolated['extract'].each_with_object({}) { |(name, extraction_details), output|
  231. output[name] = block.call(extraction_details)
  232. }
  233. end
  234. def extract_json(doc)
  235. extract_each(doc) { |extraction_details|
  236. result = Utils.values_at(doc, extraction_details['path'])
  237. log "Extracting #{extraction_type} at #{extraction_details['path']}: #{result}"
  238. result
  239. }
  240. end
  241. def extract_text(doc)
  242. extract_each(doc) { |extraction_details|
  243. regexp = Regexp.new(extraction_details['regexp'])
  244. result = []
  245. doc.scan(regexp) {
  246. result << Regexp.last_match[extraction_details['index']]
  247. }
  248. log "Extracting #{extraction_type} at #{regexp}: #{result}"
  249. result
  250. }
  251. end
  252. def extract_xml(doc)
  253. extract_each(doc) { |extraction_details|
  254. case
  255. when css = extraction_details['css']
  256. nodes = doc.css(css)
  257. when xpath = extraction_details['xpath']
  258. doc.remove_namespaces! # ignore xmlns, useful when parsing atom feeds
  259. nodes = doc.xpath(xpath)
  260. else
  261. raise '"css" or "xpath" is required for HTML or XML extraction'
  262. end
  263. case nodes
  264. when Nokogiri::XML::NodeSet
  265. result = nodes.map { |node|
  266. case value = node.xpath(extraction_details['value'])
  267. when Float
  268. # Node#xpath() returns any numeric value as float;
  269. # convert it to integer as appropriate.
  270. value = value.to_i if value.to_i == value
  271. end
  272. value.to_s
  273. }
  274. else
  275. raise "The result of HTML/XML extraction was not a NodeSet"
  276. end
  277. log "Extracting #{extraction_type} at #{xpath || css}: #{result}"
  278. result
  279. }
  280. end
  281. def parse(data)
  282. case extraction_type
  283. when "xml"
  284. Nokogiri::XML(data)
  285. when "json"
  286. JSON.parse(data)
  287. when "html"
  288. Nokogiri::HTML(data)
  289. when "text"
  290. data
  291. else
  292. raise "Unknown extraction type #{extraction_type}"
  293. end
  294. end
  295. def is_positive_integer?(value)
  296. Integer(value) >= 0
  297. rescue
  298. false
  299. end
  300. # Wraps Faraday::Response
  301. class ResponseDrop < LiquidDroppable::Drop
  302. def headers
  303. HeaderDrop.new(@object.headers)
  304. end
  305. # Integer value of HTTP status
  306. def status
  307. @object.status
  308. end
  309. end
  310. # Wraps Faraday::Utilsa::Headers
  311. class HeaderDrop < LiquidDroppable::Drop
  312. def before_method(name)
  313. @object[name.tr('_', '-')]
  314. end
  315. end
  316. end
  317. end