fetch_link_card_service.rb 5.9 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_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. Request.new(:get, @url).add_headers('Accept' => 'text/html', 'User-Agent' => Mastodon::Version.user_agent + ' Bot').perform do |res|
  37. # We follow redirects, and ideally we want to save the preview card for
  38. # the destination URL and not any link shortener in-between, so here
  39. # we set the URL to the one of the last response in the redirect chain
  40. @url = res.request.uri.to_s
  41. @card = PreviewCard.find_or_initialize_by(url: @url) if @card.url != @url
  42. if res.code == 200 && res.mime_type == 'text/html'
  43. @html_charset = res.charset
  44. @html = res.body_with_limit
  45. else
  46. @html_charset = nil
  47. @html = nil
  48. end
  49. end
  50. end
  51. def attach_card
  52. @status.preview_cards << @card
  53. Rails.cache.delete(@status)
  54. Trends.links.register(@status)
  55. end
  56. def parse_urls
  57. urls = begin
  58. if @status.local?
  59. @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[1]).normalize }
  60. else
  61. document = Nokogiri::HTML(@status.text)
  62. links = document.css('a')
  63. links.filter_map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.filter_map(&:normalize)
  64. end
  65. end
  66. urls.reject { |uri| bad_url?(uri) }.first
  67. end
  68. def bad_url?(uri)
  69. # Avoid local instance URLs and invalid URLs
  70. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  71. end
  72. def mention_link?(anchor)
  73. @status.mentions.any? do |mention|
  74. anchor['href'] == ActivityPub::TagManager.instance.url_for(mention.account)
  75. end
  76. end
  77. def skip_link?(anchor)
  78. # Avoid links for hashtags and mentions (microformats)
  79. anchor['rel']&.include?('tag') || anchor['class']&.match?(/u-url|h-card/) || mention_link?(anchor)
  80. end
  81. def attempt_oembed
  82. service = FetchOEmbedService.new
  83. url_domain = Addressable::URI.parse(@url).normalized_host
  84. cached_endpoint = Rails.cache.read("oembed_endpoint:#{url_domain}")
  85. embed = service.call(@url, cached_endpoint: cached_endpoint) unless cached_endpoint.nil?
  86. embed ||= service.call(@url, html: html) unless html.nil?
  87. return false if embed.nil?
  88. url = Addressable::URI.parse(service.endpoint_url)
  89. @card.type = embed[:type]
  90. @card.title = embed[:title] || ''
  91. @card.author_name = embed[:author_name] || ''
  92. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  93. @card.provider_name = embed[:provider_name] || ''
  94. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  95. @card.width = 0
  96. @card.height = 0
  97. case @card.type
  98. when 'link'
  99. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  100. when 'photo'
  101. return false if embed[:url].blank?
  102. @card.embed_url = (url + embed[:url]).to_s
  103. @card.image_remote_url = (url + embed[:url]).to_s
  104. @card.width = embed[:width].presence || 0
  105. @card.height = embed[:height].presence || 0
  106. when 'video'
  107. @card.width = embed[:width].presence || 0
  108. @card.height = embed[:height].presence || 0
  109. @card.html = Sanitize.fragment(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  110. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  111. when 'rich'
  112. # Most providers rely on <script> tags, which is a no-no
  113. return false
  114. end
  115. @card.save_with_optional_image!
  116. end
  117. def attempt_opengraph
  118. return if html.nil?
  119. link_details_extractor = LinkDetailsExtractor.new(@url, @html, @html_charset)
  120. @card = PreviewCard.find_or_initialize_by(url: link_details_extractor.canonical_url) if link_details_extractor.canonical_url != @card.url
  121. @card.assign_attributes(link_details_extractor.to_preview_card_attributes)
  122. @card.save_with_optional_image! unless @card.title.blank? && @card.html.blank?
  123. end
  124. end