fetch_link_card_service.rb 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. URL_PATTERN = %r{
  4. ( # $1 URL
  5. (https?:\/\/) # $2 Protocol (required)
  6. (#{Twitter::Regex[:valid_domain]}) # $3 Domain(s)
  7. (?::(#{Twitter::Regex[:valid_port_number]}))? # $4 Port number (optional)
  8. (/#{Twitter::Regex[:valid_url_path]}*)? # $5 URL Path and anchor
  9. (\?#{Twitter::Regex[:valid_url_query_chars]}*#{Twitter::Regex[:valid_url_query_ending_chars]})? # $6 Query String
  10. )
  11. }iox
  12. def call(status)
  13. @status = status
  14. @url = parse_urls
  15. return if @url.nil? || @status.preview_cards.any?
  16. @url = @url.to_s
  17. RedisLock.acquire(lock_options) do |lock|
  18. if lock.acquired?
  19. @card = PreviewCard.find_by(url: @url)
  20. process_url if @card.nil? || @card.updated_at <= 2.weeks.ago || @card.missing_image?
  21. else
  22. raise Mastodon::RaceConditionError
  23. end
  24. end
  25. attach_card if @card&.persisted?
  26. rescue HTTP::Error, OpenSSL::SSL::SSLError, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  27. Rails.logger.debug "Error fetching link #{@url}: #{e}"
  28. nil
  29. end
  30. private
  31. def process_url
  32. @card ||= PreviewCard.new(url: @url)
  33. attempt_oembed || attempt_opengraph
  34. end
  35. def html
  36. return @html if defined?(@html)
  37. Request.new(:get, @url).add_headers('Accept' => 'text/html', 'User-Agent' => Mastodon::Version.user_agent + ' Bot').perform do |res|
  38. if res.code == 200 && res.mime_type == 'text/html'
  39. @html = res.body_with_limit
  40. @html_charset = res.charset
  41. else
  42. @html = nil
  43. @html_charset = nil
  44. end
  45. end
  46. end
  47. def attach_card
  48. @status.preview_cards << @card
  49. Rails.cache.delete(@status)
  50. end
  51. def parse_urls
  52. if @status.local?
  53. urls = @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[0]).normalize }
  54. else
  55. html = Nokogiri::HTML(@status.text)
  56. links = html.css('a')
  57. urls = links.map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.compact.map(&:normalize).compact
  58. end
  59. urls.reject { |uri| bad_url?(uri) }.first
  60. end
  61. def bad_url?(uri)
  62. # Avoid local instance URLs and invalid URLs
  63. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  64. end
  65. # rubocop:disable Naming/MethodParameterName
  66. def mention_link?(a)
  67. @status.mentions.any? do |mention|
  68. a['href'] == ActivityPub::TagManager.instance.url_for(mention.account)
  69. end
  70. end
  71. def skip_link?(a)
  72. # Avoid links for hashtags and mentions (microformats)
  73. a['rel']&.include?('tag') || a['class']&.match?(/u-url|h-card/) || mention_link?(a)
  74. end
  75. # rubocop:enable Naming/MethodParameterName
  76. def attempt_oembed
  77. service = FetchOEmbedService.new
  78. url_domain = Addressable::URI.parse(@url).normalized_host
  79. cached_endpoint = Rails.cache.read("oembed_endpoint:#{url_domain}")
  80. embed = service.call(@url, cached_endpoint: cached_endpoint) unless cached_endpoint.nil?
  81. embed ||= service.call(@url, html: html) unless html.nil?
  82. return false if embed.nil?
  83. url = Addressable::URI.parse(service.endpoint_url)
  84. @card.type = embed[:type]
  85. @card.title = embed[:title] || ''
  86. @card.author_name = embed[:author_name] || ''
  87. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  88. @card.provider_name = embed[:provider_name] || ''
  89. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  90. @card.width = 0
  91. @card.height = 0
  92. case @card.type
  93. when 'link'
  94. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  95. when 'photo'
  96. return false if embed[:url].blank?
  97. @card.embed_url = (url + embed[:url]).to_s
  98. @card.image_remote_url = (url + embed[:url]).to_s
  99. @card.width = embed[:width].presence || 0
  100. @card.height = embed[:height].presence || 0
  101. when 'video'
  102. @card.width = embed[:width].presence || 0
  103. @card.height = embed[:height].presence || 0
  104. @card.html = Formatter.instance.sanitize(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  105. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  106. when 'rich'
  107. # Most providers rely on <script> tags, which is a no-no
  108. return false
  109. end
  110. @card.save_with_optional_image!
  111. end
  112. def attempt_opengraph
  113. return if html.nil?
  114. detector = CharlockHolmes::EncodingDetector.new
  115. detector.strip_tags = true
  116. guess = detector.detect(@html, @html_charset)
  117. encoding = guess&.fetch(:confidence, 0).to_i > 60 ? guess&.fetch(:encoding, nil) : nil
  118. page = Nokogiri::HTML(@html, nil, encoding)
  119. player_url = meta_property(page, 'twitter:player')
  120. if player_url && !bad_url?(Addressable::URI.parse(player_url))
  121. @card.type = :video
  122. @card.width = meta_property(page, 'twitter:player:width') || 0
  123. @card.height = meta_property(page, 'twitter:player:height') || 0
  124. @card.html = content_tag(:iframe, nil, src: player_url,
  125. width: @card.width,
  126. height: @card.height,
  127. allowtransparency: 'true',
  128. scrolling: 'no',
  129. frameborder: '0')
  130. else
  131. @card.type = :link
  132. end
  133. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  134. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  135. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  136. return if @card.title.blank? && @card.html.blank?
  137. @card.save_with_optional_image!
  138. end
  139. def meta_property(page, property)
  140. page.at_xpath("//meta[contains(concat(' ', normalize-space(@property), ' '), ' #{property} ')]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  141. end
  142. def lock_options
  143. { redis: Redis.current, key: "fetch:#{@url}" }
  144. end
  145. end