fetch_remote_resource_service.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # frozen_string_literal: true
  2. class FetchRemoteResourceService < BaseService
  3. include JsonLdHelper
  4. attr_reader :url
  5. def call(url)
  6. @url = url
  7. return process_local_url if local_url?
  8. process_url unless fetched_atom_feed.nil?
  9. end
  10. private
  11. def process_url
  12. case type
  13. when 'Person'
  14. FetchRemoteAccountService.new.call(atom_url, body, protocol)
  15. when 'Note'
  16. FetchRemoteStatusService.new.call(atom_url, body, protocol)
  17. end
  18. end
  19. def fetched_atom_feed
  20. @_fetched_atom_feed ||= FetchAtomService.new.call(url)
  21. end
  22. def atom_url
  23. fetched_atom_feed.first
  24. end
  25. def body
  26. fetched_atom_feed.second
  27. end
  28. def protocol
  29. fetched_atom_feed.third
  30. end
  31. def type
  32. return json_data['type'] if protocol == :activitypub
  33. case xml_root
  34. when 'feed'
  35. 'Person'
  36. when 'entry'
  37. 'Note'
  38. end
  39. end
  40. def json_data
  41. @_json_data ||= body_to_json(body)
  42. end
  43. def xml_root
  44. xml_data.root.name
  45. end
  46. def xml_data
  47. @_xml_data ||= Nokogiri::XML(body, nil, 'utf-8')
  48. end
  49. def local_url?
  50. TagManager.instance.local_url?(@url)
  51. end
  52. def process_local_url
  53. recognized_params = Rails.application.routes.recognize_path(@url)
  54. return unless recognized_params[:action] == 'show'
  55. if recognized_params[:controller] == 'stream_entries'
  56. status = StreamEntry.find_by(id: recognized_params[:id])&.status
  57. check_local_status(status)
  58. elsif recognized_params[:controller] == 'statuses'
  59. status = Status.find_by(id: recognized_params[:id])
  60. check_local_status(status)
  61. elsif recognized_params[:controller] == 'accounts'
  62. Account.find_local(recognized_params[:username])
  63. end
  64. end
  65. def check_local_status(status)
  66. return if status.nil?
  67. status if status.public_visibility? || status.unlisted_visibility?
  68. end
  69. end