webfinger_resource.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # frozen_string_literal: true
  2. class WebfingerResource
  3. attr_reader :resource
  4. class InvalidRequest < StandardError; end
  5. def initialize(resource)
  6. @resource = resource
  7. end
  8. def username
  9. case resource
  10. when %r{\A(https?://)?#{instance_actor_regexp}/?\Z}
  11. Rails.configuration.x.local_domain
  12. when /\Ahttps?/i
  13. username_from_url
  14. when /@/
  15. username_from_acct
  16. else
  17. raise InvalidRequest
  18. end
  19. end
  20. private
  21. def instance_actor_regexp
  22. hosts = [Rails.configuration.x.local_domain, Rails.configuration.x.web_domain]
  23. hosts.concat(Rails.configuration.x.alternate_domains) if Rails.configuration.x.alternate_domains.present?
  24. Regexp.union(hosts)
  25. end
  26. def username_from_url
  27. if account_show_page?
  28. path_params[:username]
  29. elsif instance_actor_page?
  30. Rails.configuration.x.local_domain
  31. else
  32. raise ActiveRecord::RecordNotFound
  33. end
  34. end
  35. def instance_actor_page?
  36. path_params[:controller] == 'instance_actors'
  37. end
  38. def account_show_page?
  39. path_params[:controller] == 'accounts' && path_params[:action] == 'show'
  40. end
  41. def path_params
  42. Rails.application.routes.recognize_path(resource)
  43. end
  44. def username_from_acct
  45. if domain_matches_local?
  46. local_username
  47. else
  48. raise ActiveRecord::RecordNotFound
  49. end
  50. end
  51. def split_acct
  52. resource_without_acct_string.split('@')
  53. end
  54. def resource_without_acct_string
  55. resource.delete_prefix('acct:')
  56. end
  57. def local_username
  58. split_acct.first
  59. end
  60. def local_domain
  61. split_acct.last
  62. end
  63. def domain_matches_local?
  64. TagManager.instance.local_domain?(local_domain) || TagManager.instance.web_domain?(local_domain)
  65. end
  66. end