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.

181 lines
7.1 KiB

  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. URL_PATTERN = %r{
  4. (#{Twitter::TwitterText::Regex[:valid_url_preceding_chars]}) # $1 preceeding chars
  5. ( # $2 URL
  6. (https?:\/\/) # $3 Protocol (required)
  7. (#{Twitter::TwitterText::Regex[:valid_domain]}) # $4 Domain(s)
  8. (?::(#{Twitter::TwitterText::Regex[:valid_port_number]}))? # $5 Port number (optional)
  9. (/#{Twitter::TwitterText::Regex[:valid_url_path]}*)? # $6 URL Path and anchor
  10. (\?#{Twitter::TwitterText::Regex[:valid_url_query_chars]}*#{Twitter::TwitterText::Regex[:valid_url_query_ending_chars]})? # $7 Query String
  11. )
  12. }iox
  13. def call(status)
  14. @status = status
  15. @url = parse_urls
  16. return if @url.nil? || @status.preview_cards.any?
  17. @url = @url.to_s
  18. RedisLock.acquire(lock_options) do |lock|
  19. if lock.acquired?
  20. @card = PreviewCard.find_by(url: @url)
  21. process_url if @card.nil? || @card.updated_at <= 2.weeks.ago || @card.missing_image?
  22. else
  23. raise Mastodon::RaceConditionError
  24. end
  25. end
  26. attach_card if @card&.persisted?
  27. rescue HTTP::Error, OpenSSL::SSL::SSLError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  28. Rails.logger.debug "Error fetching link #{@url}: #{e}"
  29. nil
  30. end
  31. private
  32. def process_url
  33. @card ||= PreviewCard.new(url: @url)
  34. attempt_oembed || attempt_opengraph
  35. end
  36. def html
  37. return @html if defined?(@html)
  38. Request.new(:get, @url).add_headers('Accept' => 'text/html', 'User-Agent' => Mastodon::Version.user_agent + ' Bot').perform do |res|
  39. res.headers['Content-Type'] = res.headers['Content-Type'][0] if res.headers['Content-Type'].kind_of?(Array)
  40. if res.code == 200 && res.mime_type == 'text/html'
  41. @html_charset = res.charset
  42. @html = res.body_with_limit
  43. else
  44. @html_charset = nil
  45. @html = nil
  46. end
  47. end
  48. end
  49. def attach_card
  50. @status.preview_cards << @card
  51. Rails.cache.delete(@status)
  52. end
  53. def parse_urls
  54. if @status.local?
  55. urls = @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[1]).normalize }
  56. else
  57. html = Nokogiri::HTML(@status.text)
  58. links = html.css('a')
  59. urls = links.filter_map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.filter_map(&:normalize)
  60. end
  61. urls.reject { |uri| bad_url?(uri) }.first
  62. end
  63. def bad_url?(uri)
  64. # Avoid local instance URLs and invalid URLs
  65. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  66. end
  67. # rubocop:disable Naming/MethodParameterName
  68. def mention_link?(a)
  69. @status.mentions.any? do |mention|
  70. a['href'] == ActivityPub::TagManager.instance.url_for(mention.account)
  71. end
  72. end
  73. def skip_link?(a)
  74. # Avoid links for hashtags and mentions (microformats)
  75. a['rel']&.include?('tag') || a['class']&.match?(/u-url|h-card/) || mention_link?(a)
  76. end
  77. # rubocop:enable Naming/MethodParameterName
  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 = Formatter.instance.sanitize(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. detector = CharlockHolmes::EncodingDetector.new
  117. detector.strip_tags = true
  118. guess = detector.detect(@html, @html_charset)
  119. encoding = guess&.fetch(:confidence, 0).to_i > 60 ? guess&.fetch(:encoding, nil) : nil
  120. page = Nokogiri::HTML(@html, nil, encoding)
  121. player_url = meta_property(page, 'twitter:player')
  122. if player_url && !bad_url?(Addressable::URI.parse(player_url))
  123. @card.type = :video
  124. @card.width = meta_property(page, 'twitter:player:width') || 0
  125. @card.height = meta_property(page, 'twitter:player:height') || 0
  126. @card.html = content_tag(:iframe, nil, src: player_url,
  127. width: @card.width,
  128. height: @card.height,
  129. allowtransparency: 'true',
  130. scrolling: 'no',
  131. frameborder: '0')
  132. else
  133. @card.type = :link
  134. end
  135. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  136. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  137. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  138. return if @card.title.blank? && @card.html.blank?
  139. @card.save_with_optional_image!
  140. end
  141. def meta_property(page, property)
  142. page.at_xpath("//meta[contains(concat(' ', normalize-space(@property), ' '), ' #{property} ')]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  143. end
  144. def lock_options
  145. { redis: Redis.current, key: "fetch:#{@url}", autorelease: 15.minutes.seconds }
  146. end
  147. end