1
0

fetch_link_card_service.rb 6.6 KB

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