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.

174 lines
6.3 KiB

  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
  21. else
  22. raise Mastodon::RaceConditionError
  23. end
  24. end
  25. attach_card if @card&.persisted?
  26. rescue HTTP::Error, 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. failed = Request.new(:head, @url).perform do |res|
  34. res.code != 405 && res.code != 501 && (res.code != 200 || res.mime_type != 'text/html')
  35. end
  36. return if failed
  37. Request.new(:get, @url).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. return if @html.nil?
  47. attempt_oembed || attempt_opengraph
  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[0]).normalize }
  56. else
  57. html = Nokogiri::HTML(@status.text)
  58. links = html.css('a')
  59. urls = links.map { |a| Addressable::URI.parse(a['href']).normalize unless skip_link?(a) }.compact
  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. def mention_link?(a)
  68. @status.mentions.any? do |mention|
  69. a['href'] == TagManager.instance.url_for(mention.account)
  70. end
  71. end
  72. def skip_link?(a)
  73. # Avoid links for hashtags and mentions (microformats)
  74. a['rel']&.include?('tag') || a['class']&.include?('u-url') || mention_link?(a)
  75. end
  76. def attempt_oembed
  77. service = FetchOEmbedService.new
  78. embed = service.call(@url, html: @html)
  79. url = Addressable::URI.parse(service.endpoint_url)
  80. return false if embed.nil?
  81. @card.type = embed[:type]
  82. @card.title = embed[:title] || ''
  83. @card.author_name = embed[:author_name] || ''
  84. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  85. @card.provider_name = embed[:provider_name] || ''
  86. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  87. @card.width = 0
  88. @card.height = 0
  89. case @card.type
  90. when 'link'
  91. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  92. when 'photo'
  93. return false if embed[:url].blank?
  94. @card.embed_url = (url + embed[:url]).to_s
  95. @card.image_remote_url = (url + embed[:url]).to_s
  96. @card.width = embed[:width].presence || 0
  97. @card.height = embed[:height].presence || 0
  98. when 'video'
  99. @card.width = embed[:width].presence || 0
  100. @card.height = embed[:height].presence || 0
  101. @card.html = Formatter.instance.sanitize(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  102. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  103. when 'rich'
  104. # Most providers rely on <script> tags, which is a no-no
  105. return false
  106. end
  107. @card.save_with_optional_image!
  108. end
  109. def attempt_opengraph
  110. detector = CharlockHolmes::EncodingDetector.new
  111. detector.strip_tags = true
  112. guess = detector.detect(@html, @html_charset)
  113. encoding = guess&.fetch(:confidence, 0).to_i > 60 ? guess&.fetch(:encoding, nil) : nil
  114. page = Nokogiri::HTML(@html, nil, encoding)
  115. player_url = meta_property(page, 'twitter:player')
  116. if player_url && !bad_url?(Addressable::URI.parse(player_url))
  117. @card.type = :video
  118. @card.width = meta_property(page, 'twitter:player:width') || 0
  119. @card.height = meta_property(page, 'twitter:player:height') || 0
  120. @card.html = content_tag(:iframe, nil, src: player_url,
  121. width: @card.width,
  122. height: @card.height,
  123. allowtransparency: 'true',
  124. scrolling: 'no',
  125. frameborder: '0')
  126. else
  127. @card.type = :link
  128. end
  129. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  130. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  131. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  132. return if @card.title.blank? && @card.html.blank?
  133. @card.save_with_optional_image!
  134. end
  135. def meta_property(page, property)
  136. page.at_xpath("//meta[contains(concat(' ', normalize-space(@property), ' '), ' #{property} ')]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  137. end
  138. def lock_options
  139. { redis: Redis.current, key: "fetch:#{@url}" }
  140. end
  141. end