fetch_atom_service.rb 1.5 KB

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