闭社主体 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.

47 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. rescue OpenSSL::SSL::SSLError, HTTP::Error, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  10. Rails.logger.debug "Error fetching link #{@url}: #{e}"
  11. nil
  12. end
  13. private
  14. def perform_request!
  15. @body = Request.new(:get, @url).add_headers('Accept' => 'text/html').perform do |res|
  16. res.code != 200 ? nil : res.body_with_limit
  17. end
  18. end
  19. def link_back_present?
  20. return false if @body.blank?
  21. links = Nokogiri::HTML(@body).xpath('//a[contains(concat(" ", normalize-space(@rel), " "), " me ")]|//link[contains(concat(" ", normalize-space(@rel), " "), " me ")]')
  22. if links.any? { |link| link['href'] == @link_back }
  23. true
  24. elsif links.empty?
  25. false
  26. else
  27. link_redirects_back?(links.first['href'])
  28. end
  29. end
  30. def link_redirects_back?(test_url)
  31. redirect_to_url = Request.new(:head, test_url, follow: false).perform do |res|
  32. res.headers['Location']
  33. end
  34. redirect_to_url == @link_back
  35. end
  36. end