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.

52 lines
1.6 KiB

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