website_agent.rb 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. no_bulk_receive!
  9. default_schedule "every_12h"
  10. UNIQUENESS_LOOK_BACK = 200
  11. UNIQUENESS_FACTOR = 3
  12. description <<-MD
  13. The Website Agent scrapes a website, XML document, or JSON feed and creates Events based on the results.
  14. Specify a `url` and select a `mode` for when to create Events based on the scraped data, either `all`, `on_change`, or `merge` (if fetching based on an Event, see below).
  15. The `url` option 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).
  16. The WebsiteAgent can also scrape based on incoming events.
  17. * Set the `url_from_event` option to a [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) template to generate the url to access based on the Event. (To fetch the url in the Event's `url` key, for example, set `url_from_event` to `{{ url }}`.)
  18. * Alternatively, set `data_from_event` to a [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) template to use data directly without fetching any URL. (For example, set it to `{{ html }}` to use HTML contained in the `html` key of the incoming Event.)
  19. * If you specify `merge` for the `mode` option, Huginn will retain the old payload and update it with new values.
  20. # Supported Document Types
  21. The `type` value can be `xml`, `html`, `json`, or `text`.
  22. To tell the Agent how to parse the content, specify `extract` as a hash with keys naming the extractions and values of hashes.
  23. Note that for all of the formats, whatever you extract MUST have the same number of matches for each extractor except when it has `repeat` set to true. 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.
  24. For extractors with `hidden` set to true, they will be excluded from the payloads of events created by the Agent, but can be used and interpolated in the `template` option explained below.
  25. For extractors with `repeat` set to true, their first matches will be included in all extracts. This is useful such as when you want to include the title of a page in all events created from the page.
  26. # Scraping HTML and XML
  27. 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 a string. Here's an example:
  28. "extract": {
  29. "url": { "css": "#comic img", "value": "@src" },
  30. "title": { "css": "#comic img", "value": "@title" },
  31. "body_text": { "css": "div.main", "value": "string(.)" },
  32. "page_title": { "css": "title", "value": "string(.)", "repeat": true }
  33. }
  34. "@_attr_" is the XPath expression to extract the value of an attribute named _attr_ from a node, and `string(.)` gives a string with all the enclosed text nodes concatenated without entity escaping (such as `&amp;`). To extract the innerHTML, use `./node()`; and to extract the outer HTML, use `.`.
  35. You can also use [XPath functions](https://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 commas from formatted numbers, etc. Instead of passing `string(.)` to these functions, you can just pass `.` like `normalize-space(.)` and `translate(., ',', '')`.
  36. Beware that when parsing an XML document (i.e. `type` is `xml`) using `xpath` expressions, all namespaces are stripped from the document unless the top-level option `use_namespaces` is set to `true`.
  37. # Scraping JSON
  38. When parsing JSON, these sub-hashes specify [JSONPaths](http://goessner.net/articles/JsonPath/) to the values that you care about.
  39. Sample incoming event:
  40. { "results": {
  41. "data": [
  42. {
  43. "title": "Lorem ipsum 1",
  44. "description": "Aliquam pharetra leo ipsum."
  45. "price": 8.95
  46. },
  47. {
  48. "title": "Lorem ipsum 2",
  49. "description": "Suspendisse a pulvinar lacus."
  50. "price": 12.99
  51. },
  52. {
  53. "title": "Lorem ipsum 3",
  54. "description": "Praesent ac arcu tellus."
  55. "price": 8.99
  56. }
  57. ]
  58. }
  59. }
  60. Sample rule:
  61. "extract": {
  62. "title": { "path": "results.data[*].title" },
  63. "description": { "path": "results.data[*].description" }
  64. }
  65. In this example the `*` wildcard character makes the parser to iterate through all items of the `data` array. Three events will be created as a result.
  66. Sample outgoing events:
  67. [
  68. {
  69. "title": "Lorem ipsum 1",
  70. "description": "Aliquam pharetra leo ipsum."
  71. },
  72. {
  73. "title": "Lorem ipsum 2",
  74. "description": "Suspendisse a pulvinar lacus."
  75. },
  76. {
  77. "title": "Lorem ipsum 3",
  78. "description": "Praesent ac arcu tellus."
  79. }
  80. ]
  81. The `extract` option can be skipped for the JSON type, causing the full JSON response to be returned.
  82. # Scraping Text
  83. 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:
  84. "extract": {
  85. "word": { "regexp": "^(.+?): (.+)$", index: 1 },
  86. "definition": { "regexp": "^(.+?): (.+)$", index: 2 }
  87. }
  88. Or if you prefer names to numbers for index:
  89. "extract": {
  90. "word": { "regexp": "^(?<word>.+?): (?<definition>.+)$", index: 'word' },
  91. "definition": { "regexp": "^(?<word>.+?): (?<definition>.+)$", index: 'definition' }
  92. }
  93. To extract the whole content as one event:
  94. "extract": {
  95. "content": { "regexp": "\A(?m:.)*\z", index: 0 }
  96. }
  97. 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.
  98. # General Options
  99. Can be configured to use HTTP basic auth by including the `basic_auth` parameter with `"username:password"`, or `["username", "password"]`.
  100. 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.
  101. 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.
  102. Set `force_encoding` to an encoding name (such as `UTF-8` and `ISO-8859-1`) if the website is known to respond with a missing, invalid, or wrong charset in the Content-Type header. Below are the steps used by Huginn to detect the encoding of fetched content:
  103. 1. If `force_encoding` is given, that value is used.
  104. 2. If the Content-Type header contains a charset parameter, that value is used.
  105. 3. When `type` is `html` or `xml`, Huginn checks for the presence of a BOM, XML declaration with attribute "encoding", or an HTML meta tag with charset information, and uses that if found.
  106. 4. Huginn falls back to UTF-8 (not ISO-8859-1).
  107. Set `user_agent` to a custom User-Agent name if the website does not like the default value (`#{default_user_agent}`).
  108. The `headers` field is optional. When present, it should be a hash of headers to send with the request.
  109. Set `disable_ssl_verification` to `true` to disable ssl verification.
  110. Set `unzip` to `gzip` to inflate the resource using gzip.
  111. Set `http_success_codes` to an array of status codes (e.g., `[404, 422]`) to treat HTTP response codes beyond 200 as successes.
  112. If a `template` option is given, its value must be a hash, whose key-value pairs are interpolated after extraction for each iteration and merged with the payload. In the template, keys of extracted data can be interpolated, and some additional variables are also available as explained in the next section. For example:
  113. "template": {
  114. "url": "{{ url | to_uri: _response_.url }}",
  115. "description": "{{ body_text }}",
  116. "last_modified": "{{ _response_.headers.Last-Modified | date: '%FT%T' }}"
  117. }
  118. In the `on_change` mode, change is detected based on the resulted event payload after applying this option. If you want to add some keys to each event but ignore any change in them, set `mode` to `all` and put a DeDuplicationAgent downstream.
  119. # Liquid Templating
  120. In [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) templating, the following variables are available:
  121. * `_url_`: The URL specified to fetch the content from. When parsing `data_from_event`, this is not set.
  122. * `_response_`: A response object with the following keys:
  123. * `status`: HTTP status as integer. (Almost always 200) When parsing `data_from_event`, this is set to the value of the `status` key in the incoming Event, if it is a number or a string convertible to an integer.
  124. * `headers`: Response headers; for example, `{{ _response_.headers.Content-Type }}` expands to the value of the Content-Type header. Keys are insensitive to cases and -/_. When parsing `data_from_event`, this is constructed from the value of the `headers` key in the incoming Event, if it is a hash.
  125. * `url`: The final URL of the fetched page, following redirects. When parsing `data_from_event`, this is set to the value of the `url` key in the incoming Event. Using this in the `template` option, you can resolve relative URLs extracted from a document like `{{ link | to_uri: _response_.url }}` and `{{ content | rebase_hrefs: _response_.url }}`.
  126. # Ordering Events
  127. #{description_events_order}
  128. MD
  129. event_description do
  130. if keys = event_keys
  131. "Events will have the following fields:\n\n %s" % [
  132. Utils.pretty_print(Hash[event_keys.map { |key|
  133. [key, "..."]
  134. }])
  135. ]
  136. else
  137. "Events will be the raw JSON returned by the URL."
  138. end
  139. end
  140. def event_keys
  141. extract = options['extract'] or return nil
  142. extract.each_with_object([]) { |(key, value), keys|
  143. keys << key unless boolify(value['hidden'])
  144. } | (options['template'].presence.try!(:keys) || [])
  145. end
  146. def working?
  147. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  148. end
  149. def default_options
  150. {
  151. 'expected_update_period_in_days' => "2",
  152. 'url' => "https://xkcd.com",
  153. 'type' => "html",
  154. 'mode' => "on_change",
  155. 'extract' => {
  156. 'url' => { 'css' => "#comic img", 'value' => "@src" },
  157. 'title' => { 'css' => "#comic img", 'value' => "@alt" },
  158. 'hovertext' => { 'css' => "#comic img", 'value' => "@title" }
  159. }
  160. }
  161. end
  162. def validate_options
  163. # Check for required fields
  164. errors.add(:base, "either url, url_from_event, or data_from_event are required") unless options['url'].present? || options['url_from_event'].present? || options['data_from_event'].present?
  165. errors.add(:base, "expected_update_period_in_days is required") unless options['expected_update_period_in_days'].present?
  166. validate_extract_options!
  167. validate_template_options!
  168. validate_http_success_codes!
  169. # Check for optional fields
  170. if options['mode'].present?
  171. errors.add(:base, "mode must be set to on_change, all or merge") unless %w[on_change all merge].include?(options['mode'])
  172. end
  173. if options['expected_update_period_in_days'].present?
  174. errors.add(:base, "Invalid expected_update_period_in_days format") unless is_positive_integer?(options['expected_update_period_in_days'])
  175. end
  176. if options['uniqueness_look_back'].present?
  177. errors.add(:base, "Invalid uniqueness_look_back format") unless is_positive_integer?(options['uniqueness_look_back'])
  178. end
  179. validate_web_request_options!
  180. end
  181. def validate_http_success_codes!
  182. consider_success = options["http_success_codes"]
  183. if consider_success.present?
  184. if (consider_success.class != Array)
  185. errors.add(:http_success_codes, "must be an array and specify at least one status code")
  186. else
  187. if consider_success.uniq.count != consider_success.count
  188. errors.add(:http_success_codes, "duplicate http code found")
  189. else
  190. if consider_success.any?{|e| e.to_s !~ /^\d+$/ }
  191. errors.add(:http_success_codes, "please make sure to use only numeric values for code, ex 404, or \"404\"")
  192. end
  193. end
  194. end
  195. end
  196. end
  197. def validate_extract_options!
  198. extraction_type = (extraction_type() rescue extraction_type(options))
  199. case extract = options['extract']
  200. when Hash
  201. if extract.each_value.any? { |value| !value.is_a?(Hash) }
  202. errors.add(:base, 'extract must be a hash of hashes.')
  203. else
  204. case extraction_type
  205. when 'html', 'xml'
  206. extract.each do |name, details|
  207. case details['css']
  208. when String
  209. # ok
  210. when nil
  211. case details['xpath']
  212. when String
  213. # ok
  214. when nil
  215. errors.add(:base, "When type is html or xml, all extractions must have a css or xpath attribute (bad extraction details for #{name.inspect})")
  216. else
  217. errors.add(:base, "Wrong type of \"xpath\" value in extraction details for #{name.inspect}")
  218. end
  219. else
  220. errors.add(:base, "Wrong type of \"css\" value in extraction details for #{name.inspect}")
  221. end
  222. case details['value']
  223. when String, nil
  224. # ok
  225. else
  226. errors.add(:base, "Wrong type of \"value\" value in extraction details for #{name.inspect}")
  227. end
  228. end
  229. when 'json'
  230. extract.each do |name, details|
  231. case details['path']
  232. when String
  233. # ok
  234. when nil
  235. errors.add(:base, "When type is json, all extractions must have a path attribute (bad extraction details for #{name.inspect})")
  236. else
  237. errors.add(:base, "Wrong type of \"path\" value in extraction details for #{name.inspect}")
  238. end
  239. end
  240. when 'text'
  241. extract.each do |name, details|
  242. case regexp = details['regexp']
  243. when String
  244. begin
  245. re = Regexp.new(regexp)
  246. rescue => e
  247. errors.add(:base, "invalid regexp for #{name.inspect}: #{e.message}")
  248. end
  249. when nil
  250. errors.add(:base, "When type is text, all extractions must have a regexp attribute (bad extraction details for #{name.inspect})")
  251. else
  252. errors.add(:base, "Wrong type of \"regexp\" value in extraction details for #{name.inspect}")
  253. end
  254. case index = details['index']
  255. when Integer, /\A\d+\z/
  256. # ok
  257. when String
  258. if re && !re.names.include?(index)
  259. errors.add(:base, "no named capture #{index.inspect} found in regexp for #{name.inspect})")
  260. end
  261. when nil
  262. errors.add(:base, "When type is text, all extractions must have an index attribute (bad extraction details for #{name.inspect})")
  263. else
  264. errors.add(:base, "Wrong type of \"index\" value in extraction details for #{name.inspect}")
  265. end
  266. end
  267. when /\{/
  268. # Liquid templating
  269. else
  270. errors.add(:base, "Unknown extraction type #{extraction_type.inspect}")
  271. end
  272. end
  273. when nil
  274. unless extraction_type == 'json'
  275. errors.add(:base, 'extract is required for all types except json')
  276. end
  277. else
  278. errors.add(:base, 'extract must be a hash')
  279. end
  280. end
  281. def validate_template_options!
  282. template = options['template'].presence or return
  283. unless Hash === template &&
  284. template.each_pair.all? { |key, value| String === value }
  285. errors.add(:base, 'template must be a hash of strings.')
  286. end
  287. end
  288. def check
  289. check_urls(interpolated['url'])
  290. end
  291. def check_urls(in_url, existing_payload = {})
  292. return unless in_url.present?
  293. Array(in_url).each do |url|
  294. check_url(url, existing_payload)
  295. end
  296. end
  297. def check_url(url, existing_payload = {})
  298. unless /\Ahttps?:\/\//i === url
  299. error "Ignoring a non-HTTP url: #{url.inspect}"
  300. return
  301. end
  302. uri = Utils.normalize_uri(url)
  303. log "Fetching #{uri}"
  304. response = faraday.get(uri)
  305. raise "Failed: #{response.inspect}" unless consider_response_successful?(response)
  306. interpolation_context.stack {
  307. interpolation_context['_url_'] = uri.to_s
  308. interpolation_context['_response_'] = ResponseDrop.new(response)
  309. handle_data(response.body, response.env[:url], existing_payload)
  310. }
  311. rescue => e
  312. error "Error when fetching url: #{e.message}\n#{e.backtrace.join("\n")}"
  313. end
  314. def default_encoding
  315. case extraction_type
  316. when 'html', 'xml'
  317. # Let Nokogiri detect the encoding
  318. nil
  319. else
  320. super
  321. end
  322. end
  323. def handle_data(body, url, existing_payload)
  324. # Beware, url may be a URI object, string or nil
  325. doc = parse(body)
  326. if extract_full_json?
  327. if store_payload!(previous_payloads(1), doc)
  328. log "Storing new result for '#{name}': #{doc.inspect}"
  329. create_event payload: existing_payload.merge(doc)
  330. end
  331. return
  332. end
  333. output =
  334. case extraction_type
  335. when 'json'
  336. extract_json(doc)
  337. when 'text'
  338. extract_text(doc)
  339. else
  340. extract_xml(doc)
  341. end
  342. num_tuples = output.size or
  343. raise "At least one non-repeat key is required"
  344. old_events = previous_payloads num_tuples
  345. template = options['template'].presence
  346. output.each do |extracted|
  347. result = extracted.except(*output.hidden_keys)
  348. if template
  349. result.update(interpolate_options(template, extracted))
  350. end
  351. if store_payload!(old_events, result)
  352. log "Storing new parsed result for '#{name}': #{result.inspect}"
  353. create_event payload: existing_payload.merge(result)
  354. end
  355. end
  356. end
  357. def receive(incoming_events)
  358. incoming_events.each do |event|
  359. interpolate_with(event) do
  360. existing_payload = interpolated['mode'].to_s == "merge" ? event.payload : {}
  361. if data_from_event = options['data_from_event'].presence
  362. data = interpolate_options(data_from_event)
  363. if data.present?
  364. handle_event_data(data, event, existing_payload)
  365. else
  366. error "No data was found in the Event payload using the template #{data_from_event}", inbound_event: event
  367. end
  368. else
  369. url_to_scrape =
  370. if url_template = options['url_from_event'].presence
  371. interpolate_options(url_template)
  372. else
  373. interpolated['url']
  374. end
  375. check_urls(url_to_scrape, existing_payload)
  376. end
  377. end
  378. end
  379. end
  380. private
  381. def consider_response_successful?(response)
  382. response.success? || begin
  383. consider_success = options["http_success_codes"]
  384. consider_success.present? && (consider_success.include?(response.status.to_s) || consider_success.include?(response.status))
  385. end
  386. end
  387. def handle_event_data(data, event, existing_payload)
  388. interpolation_context.stack {
  389. interpolation_context['_response_'] = ResponseFromEventDrop.new(event)
  390. handle_data(data, event.payload['url'].presence, existing_payload)
  391. }
  392. rescue => e
  393. error "Error when handling event data: #{e.message}\n#{e.backtrace.join("\n")}", inbound_event: event
  394. end
  395. # This method returns true if the result should be stored as a new event.
  396. # If mode is set to 'on_change', this method may return false and update an existing
  397. # event to expire further in the future.
  398. def store_payload!(old_events, result)
  399. case interpolated['mode'].presence
  400. when 'on_change'
  401. result_json = result.to_json
  402. if found = old_events.find { |event| event.payload.to_json == result_json }
  403. found.update!(expires_at: new_event_expiration_date)
  404. false
  405. else
  406. true
  407. end
  408. when 'all', 'merge', ''
  409. true
  410. else
  411. raise "Illegal options[mode]: #{interpolated['mode']}"
  412. end
  413. end
  414. def previous_payloads(num_events)
  415. if interpolated['uniqueness_look_back'].present?
  416. look_back = interpolated['uniqueness_look_back'].to_i
  417. else
  418. # Larger of UNIQUENESS_FACTOR * num_events and UNIQUENESS_LOOK_BACK
  419. look_back = UNIQUENESS_FACTOR * num_events
  420. if look_back < UNIQUENESS_LOOK_BACK
  421. look_back = UNIQUENESS_LOOK_BACK
  422. end
  423. end
  424. events.order("id desc").limit(look_back) if interpolated['mode'] == "on_change"
  425. end
  426. def extract_full_json?
  427. !interpolated['extract'].present? && extraction_type == "json"
  428. end
  429. def extraction_type(interpolated = interpolated())
  430. (interpolated['type'] || begin
  431. case interpolated['url']
  432. when /\.(rss|xml)$/i
  433. "xml"
  434. when /\.json$/i
  435. "json"
  436. when /\.(txt|text)$/i
  437. "text"
  438. else
  439. "html"
  440. end
  441. end).to_s
  442. end
  443. def use_namespaces?
  444. if interpolated.key?('use_namespaces')
  445. boolify(interpolated['use_namespaces'])
  446. else
  447. interpolated['extract'].none? { |name, extraction_details|
  448. extraction_details.key?('xpath')
  449. }
  450. end
  451. end
  452. def extract_each(&block)
  453. interpolated['extract'].each_with_object(Output.new) { |(name, extraction_details), output|
  454. if boolify(extraction_details['repeat'])
  455. values = Repeater.new { |repeater|
  456. block.call(extraction_details, repeater)
  457. }
  458. else
  459. values = []
  460. block.call(extraction_details, values)
  461. end
  462. log "Values extracted: #{values}"
  463. begin
  464. output[name] = values
  465. rescue UnevenSizeError
  466. raise "Got an uneven number of matches for #{interpolated['name']}: #{interpolated['extract'].inspect}"
  467. else
  468. output.hidden_keys << name if boolify(extraction_details['hidden'])
  469. end
  470. }
  471. end
  472. def extract_json(doc)
  473. extract_each { |extraction_details, values|
  474. log "Extracting #{extraction_type} at #{extraction_details['path']}"
  475. Utils.values_at(doc, extraction_details['path']).each { |value|
  476. values << value
  477. }
  478. }
  479. end
  480. def extract_text(doc)
  481. extract_each { |extraction_details, values|
  482. regexp = Regexp.new(extraction_details['regexp'])
  483. log "Extracting #{extraction_type} with #{regexp}"
  484. case index = extraction_details['index']
  485. when /\A\d+\z/
  486. index = index.to_i
  487. end
  488. doc.scan(regexp) {
  489. values << Regexp.last_match[index]
  490. }
  491. }
  492. end
  493. def extract_xml(doc)
  494. extract_each { |extraction_details, values|
  495. case
  496. when css = extraction_details['css']
  497. nodes = doc.css(css)
  498. when xpath = extraction_details['xpath']
  499. nodes = doc.xpath(xpath)
  500. else
  501. raise '"css" or "xpath" is required for HTML or XML extraction'
  502. end
  503. log "Extracting #{extraction_type} at #{xpath || css}"
  504. case nodes
  505. when Nokogiri::XML::NodeSet
  506. nodes.each { |node|
  507. case value = node.xpath(extraction_details['value'] || '.')
  508. when Float
  509. # Node#xpath() returns any numeric value as float;
  510. # convert it to integer as appropriate.
  511. value = value.to_i if value.to_i == value
  512. end
  513. values << value.to_s
  514. }
  515. else
  516. raise "The result of HTML/XML extraction was not a NodeSet"
  517. end
  518. }
  519. end
  520. def parse(data)
  521. case type = extraction_type
  522. when "xml"
  523. doc = Nokogiri::XML(data)
  524. # ignore xmlns, useful when parsing atom feeds
  525. doc.remove_namespaces! unless use_namespaces?
  526. doc
  527. when "json"
  528. JSON.parse(data)
  529. when "html"
  530. Nokogiri::HTML(data)
  531. when "text"
  532. data
  533. else
  534. raise "Unknown extraction type: #{type}"
  535. end
  536. end
  537. def is_positive_integer?(value)
  538. Integer(value) >= 0
  539. rescue
  540. false
  541. end
  542. class UnevenSizeError < ArgumentError
  543. end
  544. class Output
  545. def initialize
  546. @hash = {}
  547. @size = nil
  548. @hidden_keys = []
  549. end
  550. attr_reader :size
  551. attr_reader :hidden_keys
  552. def []=(key, value)
  553. case size = value.size
  554. when Integer
  555. if @size && @size != size
  556. raise UnevenSizeError, 'got an uneven size'
  557. end
  558. @size = size
  559. end
  560. @hash[key] = value
  561. end
  562. def each
  563. @size.times.zip(*@hash.values) do |index, *values|
  564. yield @hash.each_key.lazy.zip(values).to_h
  565. end
  566. end
  567. end
  568. class Repeater < Enumerator
  569. # Repeater.new { |y|
  570. # # ...
  571. # y << value
  572. # } #=> [value, ...]
  573. def initialize(&block)
  574. @value = nil
  575. super(Float::INFINITY) { |y|
  576. loop { y << @value }
  577. }
  578. catch(@done = Object.new) {
  579. block.call(self)
  580. }
  581. end
  582. def <<(value)
  583. @value = value
  584. throw @done
  585. end
  586. def to_s
  587. "[#{@value.inspect}, ...]"
  588. end
  589. end
  590. # Wraps Faraday::Response
  591. class ResponseDrop < LiquidDroppable::Drop
  592. def headers
  593. HeaderDrop.new(@object.headers)
  594. end
  595. # Integer value of HTTP status
  596. def status
  597. @object.status
  598. end
  599. # The URL
  600. def url
  601. @object.env.url.to_s
  602. end
  603. end
  604. class ResponseFromEventDrop < LiquidDroppable::Drop
  605. def headers
  606. headers = Faraday::Utils::Headers.from(@object.payload[:headers]) rescue {}
  607. HeaderDrop.new(headers)
  608. end
  609. # Integer value of HTTP status
  610. def status
  611. Integer(@object.payload[:status]) rescue nil
  612. end
  613. # The URL
  614. def url
  615. @object.payload[:url]
  616. end
  617. end
  618. # Wraps Faraday::Utils::Headers
  619. class HeaderDrop < LiquidDroppable::Drop
  620. def liquid_method_missing(name)
  621. @object[name.tr('_', '-')]
  622. end
  623. end
  624. end
  625. end