You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4 KiB

  1. class FetchAtomService < BaseService
  2. def call(url)
  3. response = http_client.head(url)
  4. Rails.logger.debug "Remote status HEAD request returned code #{response.code}"
  5. return nil if response.code != 200
  6. if response.mime_type == 'application/atom+xml'
  7. return [url, fetch(url)]
  8. elsif !response['Link'].blank?
  9. return process_headers(url, response)
  10. else
  11. return process_html(fetch(url))
  12. end
  13. rescue OpenSSL::SSL::SSLError => e
  14. Rails.logger.debug "SSL error: #{e}"
  15. end
  16. private
  17. def process_html(body)
  18. Rails.logger.debug 'Processing HTML'
  19. page = Nokogiri::HTML(body)
  20. alternate_link = page.xpath('//link[@rel="alternate"]').find { |link| link['type'] == 'application/atom+xml' }
  21. return nil if alternate_link.nil?
  22. return [alternate_link['href'], fetch(alternate_link['href'])]
  23. end
  24. def process_headers(url, response)
  25. Rails.logger.debug 'Processing link header'
  26. link_header = LinkHeader.parse(response['Link'].is_a?(Array) ? response['Link'].first : response['Link'])
  27. alternate_link = link_header.find_link(['rel', 'alternate'], ['type', 'application/atom+xml'])
  28. return process_html(fetch(url)) if alternate_link.nil?
  29. return [alternate_link.href, fetch(alternate_link.href)]
  30. end
  31. def fetch(url)
  32. http_client.get(url).to_s
  33. end
  34. def http_client
  35. HTTP.timeout(:per_operation, write: 20, connect: 20, read: 50).follow
  36. end
  37. end