fetch_link_card_service.rb 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. include Redisable
  4. include Lockable
  5. URL_PATTERN = %r{
  6. (#{Twitter::TwitterText::Regex[:valid_url_preceding_chars]}) # $1 preceding chars
  7. ( # $2 URL
  8. (https?://) # $3 Protocol (required)
  9. (#{Twitter::TwitterText::Regex[:valid_domain]}) # $4 Domain(s)
  10. (?::(#{Twitter::TwitterText::Regex[:valid_port_number]}))? # $5 Port number (optional)
  11. (/#{Twitter::TwitterText::Regex[:valid_url_path]}*)? # $6 URL Path and anchor
  12. (\?#{Twitter::TwitterText::Regex[:valid_url_query_chars]}*#{Twitter::TwitterText::Regex[:valid_url_query_ending_chars]})? # $7 Query String
  13. )
  14. }iox
  15. def call(status)
  16. @status = status
  17. @original_url = parse_urls
  18. return if @original_url.nil? || @status.preview_cards.any?
  19. @url = @original_url.to_s
  20. with_redis_lock("fetch:#{@original_url}") do
  21. @card = PreviewCard.find_by(url: @url)
  22. process_url if @card.nil? || @card.updated_at <= 2.weeks.ago || @card.missing_image?
  23. end
  24. attach_card if @card&.persisted?
  25. rescue HTTP::Error, OpenSSL::SSL::SSLError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  26. Rails.logger.debug { "Error fetching link #{@original_url}: #{e}" }
  27. nil
  28. end
  29. private
  30. def process_url
  31. @card ||= PreviewCard.new(url: @url)
  32. attempt_oembed || attempt_opengraph
  33. end
  34. def html
  35. return @html if defined?(@html)
  36. @html = Request.new(:get, @url).add_headers('Accept' => 'text/html', 'User-Agent' => "#{Mastodon::Version.user_agent} Bot").perform do |res|
  37. next unless res.code == 200 && res.mime_type == 'text/html'
  38. # We follow redirects, and ideally we want to save the preview card for
  39. # the destination URL and not any link shortener in-between, so here
  40. # we set the URL to the one of the last response in the redirect chain
  41. @url = res.request.uri.to_s
  42. @card = PreviewCard.find_or_initialize_by(url: @url) if @card.url != @url
  43. @html_charset = res.charset
  44. res.body_with_limit
  45. end
  46. end
  47. def attach_card
  48. with_redis_lock("attach_card:#{@status.id}") do
  49. return if @status.preview_cards.any?
  50. @status.preview_cards << @card
  51. Rails.cache.delete(@status)
  52. Trends.links.register(@status)
  53. end
  54. end
  55. def parse_urls
  56. urls = if @status.local?
  57. @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[1]).normalize }
  58. else
  59. document = Nokogiri::HTML(@status.text)
  60. links = document.css('a')
  61. links.filter_map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.filter_map(&:normalize)
  62. end
  63. urls.reject { |uri| bad_url?(uri) }.first
  64. end
  65. def bad_url?(uri)
  66. # Avoid local instance URLs and invalid URLs
  67. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  68. end
  69. def mention_link?(anchor)
  70. @status.mentions.any? do |mention|
  71. anchor['href'] == ActivityPub::TagManager.instance.url_for(mention.account)
  72. end
  73. end
  74. def skip_link?(anchor)
  75. # Avoid links for hashtags and mentions (microformats)
  76. anchor['rel']&.include?('tag') || anchor['class']&.match?(/u-url|h-card/) || mention_link?(anchor)
  77. end
  78. def attempt_oembed
  79. service = FetchOEmbedService.new
  80. url_domain = Addressable::URI.parse(@url).normalized_host
  81. cached_endpoint = Rails.cache.read("oembed_endpoint:#{url_domain}")
  82. embed = service.call(@url, cached_endpoint: cached_endpoint) unless cached_endpoint.nil?
  83. embed ||= service.call(@url, html: html) unless html.nil?
  84. return false if embed.nil?
  85. url = Addressable::URI.parse(service.endpoint_url)
  86. @card.type = embed[:type]
  87. @card.title = embed[:title] || ''
  88. @card.author_name = embed[:author_name] || ''
  89. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  90. @card.provider_name = embed[:provider_name] || ''
  91. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  92. @card.width = 0
  93. @card.height = 0
  94. case @card.type
  95. when 'link'
  96. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  97. when 'photo'
  98. return false if embed[:url].blank?
  99. @card.embed_url = (url + embed[:url]).to_s
  100. @card.image_remote_url = (url + embed[:url]).to_s
  101. @card.width = embed[:width].presence || 0
  102. @card.height = embed[:height].presence || 0
  103. when 'video'
  104. @card.width = embed[:width].presence || 0
  105. @card.height = embed[:height].presence || 0
  106. @card.html = Sanitize.fragment(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  107. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  108. when 'rich'
  109. # Most providers rely on <script> tags, which is a no-no
  110. return false
  111. end
  112. @card.save_with_optional_image!
  113. end
  114. def attempt_opengraph
  115. return if html.nil?
  116. link_details_extractor = LinkDetailsExtractor.new(@url, @html, @html_charset)
  117. @card = PreviewCard.find_or_initialize_by(url: link_details_extractor.canonical_url) if link_details_extractor.canonical_url != @card.url
  118. @card.assign_attributes(link_details_extractor.to_preview_card_attributes)
  119. @card.save_with_optional_image! unless @card.title.blank? && @card.html.blank?
  120. end
  121. end