闭社主体 forked from https://github.com/tootsuite/mastodon
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.

48 lines
1.3 KiB

  1. # frozen_string_literal: true
  2. class VerifyLinkService < BaseService
  3. def call(field)
  4. @link_back = ActivityPub::TagManager.instance.url_for(field.account)
  5. @url = field.value_for_verification
  6. perform_request!
  7. return unless link_back_present?
  8. field.mark_verified!
  9. field.account.save!
  10. rescue HTTP::Error, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  11. Rails.logger.debug "Error fetching link #{@url}: #{e}"
  12. nil
  13. end
  14. private
  15. def perform_request!
  16. @body = Request.new(:get, @url).add_headers('Accept' => 'text/html').perform do |res|
  17. res.code != 200 ? nil : res.body_with_limit
  18. end
  19. end
  20. def link_back_present?
  21. return false if @body.blank?
  22. links = Nokogiri::HTML(@body).xpath('//a[contains(concat(" ", normalize-space(@rel), " "), " me ")]|//link[contains(concat(" ", normalize-space(@rel), " "), " me ")]')
  23. if links.any? { |link| link['href'] == @link_back }
  24. true
  25. elsif links.empty?
  26. false
  27. else
  28. link_redirects_back?(links.first['href'])
  29. end
  30. end
  31. def link_redirects_back?(test_url)
  32. redirect_to_url = Request.new(:head, test_url, follow: false).perform do |res|
  33. res.headers['Location']
  34. end
  35. redirect_to_url == @link_back
  36. end
  37. end