website_agent.rb 28 KB

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