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.

168 lines
6.2 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 || @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. Request.new(:get, @url).perform do |res|
  34. if res.code == 200 && res.mime_type == 'text/html'
  35. @html = res.body_with_limit
  36. @html_charset = res.charset
  37. else
  38. @html = nil
  39. @html_charset = nil
  40. end
  41. end
  42. return if @html.nil?
  43. attempt_oembed || attempt_opengraph
  44. end
  45. def attach_card
  46. @status.preview_cards << @card
  47. Rails.cache.delete(@status)
  48. end
  49. def parse_urls
  50. if @status.local?
  51. urls = @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[0]).normalize }
  52. else
  53. html = Nokogiri::HTML(@status.text)
  54. links = html.css('a')
  55. urls = links.map { |a| Addressable::URI.parse(a['href']).normalize unless skip_link?(a) }.compact
  56. end
  57. urls.reject { |uri| bad_url?(uri) }.first
  58. end
  59. def bad_url?(uri)
  60. # Avoid local instance URLs and invalid URLs
  61. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  62. end
  63. def mention_link?(a)
  64. @status.mentions.any? do |mention|
  65. a['href'] == ActivityPub::TagManager.instance.url_for(mention.account)
  66. end
  67. end
  68. def skip_link?(a)
  69. # Avoid links for hashtags and mentions (microformats)
  70. a['rel']&.include?('tag') || a['class']&.include?('u-url') || mention_link?(a)
  71. end
  72. def attempt_oembed
  73. service = FetchOEmbedService.new
  74. embed = service.call(@url, html: @html)
  75. url = Addressable::URI.parse(service.endpoint_url)
  76. return false if embed.nil?
  77. @card.type = embed[:type]
  78. @card.title = embed[:title] || ''
  79. @card.author_name = embed[:author_name] || ''
  80. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  81. @card.provider_name = embed[:provider_name] || ''
  82. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  83. @card.width = 0
  84. @card.height = 0
  85. case @card.type
  86. when 'link'
  87. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  88. when 'photo'
  89. return false if embed[:url].blank?
  90. @card.embed_url = (url + embed[:url]).to_s
  91. @card.image_remote_url = (url + embed[:url]).to_s
  92. @card.width = embed[:width].presence || 0
  93. @card.height = embed[:height].presence || 0
  94. when 'video'
  95. @card.width = embed[:width].presence || 0
  96. @card.height = embed[:height].presence || 0
  97. @card.html = Formatter.instance.sanitize(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  98. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  99. when 'rich'
  100. # Most providers rely on <script> tags, which is a no-no
  101. return false
  102. end
  103. @card.save_with_optional_image!
  104. end
  105. def attempt_opengraph
  106. detector = CharlockHolmes::EncodingDetector.new
  107. detector.strip_tags = true
  108. guess = detector.detect(@html, @html_charset)
  109. encoding = guess&.fetch(:confidence, 0).to_i > 60 ? guess&.fetch(:encoding, nil) : nil
  110. page = Nokogiri::HTML(@html, nil, encoding)
  111. player_url = meta_property(page, 'twitter:player')
  112. if player_url && !bad_url?(Addressable::URI.parse(player_url))
  113. @card.type = :video
  114. @card.width = meta_property(page, 'twitter:player:width') || 0
  115. @card.height = meta_property(page, 'twitter:player:height') || 0
  116. @card.html = content_tag(:iframe, nil, src: player_url,
  117. width: @card.width,
  118. height: @card.height,
  119. allowtransparency: 'true',
  120. scrolling: 'no',
  121. frameborder: '0')
  122. else
  123. @card.type = :link
  124. end
  125. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  126. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  127. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  128. return if @card.title.blank? && @card.html.blank?
  129. @card.save_with_optional_image!
  130. end
  131. def meta_property(page, property)
  132. page.at_xpath("//meta[contains(concat(' ', normalize-space(@property), ' '), ' #{property} ')]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  133. end
  134. def lock_options
  135. { redis: Redis.current, key: "fetch:#{@url}" }
  136. end
  137. end