1
0

resolve_url_service.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # frozen_string_literal: true
  2. class ResolveURLService < BaseService
  3. include JsonLdHelper
  4. include Authorization
  5. def call(url, on_behalf_of: nil)
  6. @url = url
  7. @on_behalf_of = on_behalf_of
  8. if local_url?
  9. process_local_url
  10. elsif !fetched_resource.nil?
  11. process_url
  12. else
  13. process_url_from_db
  14. end
  15. end
  16. private
  17. def process_url
  18. if equals_or_includes_any?(type, ActivityPub::FetchRemoteAccountService::SUPPORTED_TYPES)
  19. ActivityPub::FetchRemoteAccountService.new.call(resource_url, prefetched_body: body)
  20. elsif equals_or_includes_any?(type, ActivityPub::Activity::Create::SUPPORTED_TYPES + ActivityPub::Activity::Create::CONVERTED_TYPES)
  21. status = FetchRemoteStatusService.new.call(resource_url, body)
  22. authorize_with @on_behalf_of, status, :show? unless status.nil?
  23. status
  24. end
  25. end
  26. def process_url_from_db
  27. return unless @on_behalf_of.present? && [401, 403, 404].include?(fetch_resource_service.response_code)
  28. # It may happen that the resource is a private toot, and thus not fetchable,
  29. # but we can return the toot if we already know about it.
  30. status = Status.find_by(uri: @url) || Status.find_by(url: @url)
  31. authorize_with @on_behalf_of, status, :show? unless status.nil?
  32. status
  33. rescue Mastodon::NotPermittedError
  34. nil
  35. end
  36. def fetched_resource
  37. @fetched_resource ||= fetch_resource_service.call(@url)
  38. end
  39. def fetch_resource_service
  40. @_fetch_resource_service ||= FetchResourceService.new
  41. end
  42. def resource_url
  43. fetched_resource.first
  44. end
  45. def body
  46. fetched_resource.second[:prefetched_body]
  47. end
  48. def type
  49. json_data['type']
  50. end
  51. def json_data
  52. @json_data ||= body_to_json(body)
  53. end
  54. def local_url?
  55. TagManager.instance.local_url?(@url)
  56. end
  57. def process_local_url
  58. recognized_params = Rails.application.routes.recognize_path(@url)
  59. return unless recognized_params[:action] == 'show'
  60. if recognized_params[:controller] == 'statuses'
  61. status = Status.find_by(id: recognized_params[:id])
  62. check_local_status(status)
  63. elsif recognized_params[:controller] == 'accounts'
  64. Account.find_local(recognized_params[:username])
  65. end
  66. end
  67. def check_local_status(status)
  68. return if status.nil?
  69. authorize_with @on_behalf_of, status, :show?
  70. status
  71. rescue Mastodon::NotPermittedError
  72. nil
  73. end
  74. end