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.

71 lines
1.9 KiB

  1. class FetchRemoteStatusService < 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 process_atom(url, fetch(url))
  8. elsif !response['Link'].blank?
  9. return process_headers(response)
  10. else
  11. return process_html(fetch(url))
  12. end
  13. end
  14. private
  15. def process_atom(url, body)
  16. Rails.logger.debug "Processing Atom for remote status"
  17. xml = Nokogiri::XML(body)
  18. account = extract_author(url, xml)
  19. return nil if account.nil?
  20. statuses = ProcessFeedService.new.(body, account)
  21. return statuses.first
  22. end
  23. def process_html(body)
  24. Rails.logger.debug "Processing HTML for remote status"
  25. page = Nokogiri::HTML(body)
  26. alternate_link = page.xpath('//link[@rel="alternate"]').find { |link| link['type'] == 'application/atom+xml' }
  27. return nil if alternate_link.nil?
  28. return process_atom(alternate_link['href'], fetch(alternate_link['href']))
  29. end
  30. def process_headers(response)
  31. Rails.logger.debug "Processing link header for remote status"
  32. link_header = LinkHeader.parse(response['Link'])
  33. alternate_link = link_header.find_link(['rel', 'alternate'], ['type', 'application/atom+xml'])
  34. return nil if alternate_link.nil?
  35. return process_atom(alternate_link.href, fetch(alternate_link.href))
  36. end
  37. def extract_author(url, xml)
  38. url_parts = Addressable::URI.parse(url)
  39. username = xml.at_xpath('//xmlns:author/xmlns:name').try(:content)
  40. domain = url_parts.host
  41. return nil if username.nil?
  42. Rails.logger.debug "Going to webfinger #{username}@#{domain}"
  43. return FollowRemoteAccountService.new.("#{username}@#{domain}")
  44. end
  45. def fetch(url)
  46. http_client.get(url).to_s
  47. end
  48. def http_client
  49. HTTP.timeout(:per_operation, write: 20, connect: 20, read: 50)
  50. end
  51. end