remote_follow.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # frozen_string_literal: true
  2. class RemoteFollow
  3. include ActiveModel::Validations
  4. include RoutingHelper
  5. attr_accessor :acct, :addressable_template
  6. validates :acct, presence: true, domain: { acct: true }
  7. def initialize(attrs = {})
  8. @acct = normalize_acct(attrs[:acct])
  9. end
  10. def valid?
  11. return false unless super
  12. fetch_template!
  13. errors.empty?
  14. end
  15. def subscribe_address_for(account)
  16. addressable_template.expand(uri: ActivityPub::TagManager.instance.uri_for(account)).to_s
  17. end
  18. def interact_address_for(status)
  19. addressable_template.expand(uri: ActivityPub::TagManager.instance.uri_for(status)).to_s
  20. end
  21. private
  22. def normalize_acct(value)
  23. return if value.blank?
  24. username, domain = value.strip.gsub(/\A@/, '').split('@')
  25. domain = if TagManager.instance.local_domain?(domain)
  26. nil
  27. else
  28. TagManager.instance.normalize_domain(domain)
  29. end
  30. [username, domain].compact.join('@')
  31. rescue Addressable::URI::InvalidURIError
  32. value
  33. end
  34. def fetch_template!
  35. return missing_resource_error if acct.blank?
  36. _, domain = acct.split('@')
  37. if domain.nil?
  38. @addressable_template = Addressable::Template.new("#{authorize_interaction_url}?uri={uri}")
  39. elsif redirect_uri_template.nil?
  40. missing_resource_error
  41. else
  42. @addressable_template = Addressable::Template.new(redirect_uri_template)
  43. end
  44. end
  45. def redirect_uri_template
  46. acct_resource&.link('http://ostatus.org/schema/1.0/subscribe', 'template')
  47. end
  48. def acct_resource
  49. @acct_resource ||= Webfinger.new("acct:#{acct}").perform
  50. rescue Webfinger::Error, *Mastodon::HTTP_CONNECTION_ERRORS
  51. nil
  52. end
  53. def missing_resource_error
  54. errors.add(:acct, I18n.t('remote_follow.missing_resource'))
  55. end
  56. end