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.

173 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. @mentions = status.mentions
  17. @url = @url.to_s
  18. RedisLock.acquire(lock_options) do |lock|
  19. if lock.acquired?
  20. @card = PreviewCard.find_by(url: @url)
  21. process_url if @card.nil? || @card.updated_at <= 2.weeks.ago
  22. else
  23. raise Mastodon::RaceConditionError
  24. end
  25. end
  26. attach_card if @card&.persisted?
  27. rescue HTTP::Error, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError => e
  28. Rails.logger.debug "Error fetching link #{@url}: #{e}"
  29. nil
  30. end
  31. private
  32. def process_url
  33. @card ||= PreviewCard.new(url: @url)
  34. failed = Request.new(:head, @url).perform do |res|
  35. res.code != 405 && res.code != 501 && (res.code != 200 || res.mime_type != 'text/html')
  36. end
  37. return if failed
  38. Request.new(:get, @url).perform do |res|
  39. if res.code == 200 && res.mime_type == 'text/html'
  40. @html = res.body_with_limit
  41. @html_charset = res.charset
  42. else
  43. @html = nil
  44. @html_charset = nil
  45. end
  46. end
  47. return if @html.nil?
  48. attempt_oembed || attempt_opengraph
  49. end
  50. def attach_card
  51. @status.preview_cards << @card
  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. return false if @mentions.nil?
  69. @mentions.any? do |mention|
  70. a['href'] == TagManager.instance.url_for(mention.target)
  71. end
  72. end
  73. def skip_link?(a)
  74. # Avoid links for hashtags and mentions (microformats)
  75. a['rel']&.include?('tag') || a['class']&.include?('u-url') || mention_link?(a)
  76. end
  77. def attempt_oembed
  78. service = FetchOEmbedService.new
  79. embed = service.call(@url, html: @html)
  80. url = Addressable::URI.parse(service.endpoint_url)
  81. return false if embed.nil?
  82. @card.type = embed[:type]
  83. @card.title = embed[:title] || ''
  84. @card.author_name = embed[:author_name] || ''
  85. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  86. @card.provider_name = embed[:provider_name] || ''
  87. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  88. @card.width = 0
  89. @card.height = 0
  90. case @card.type
  91. when 'link'
  92. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  93. when 'photo'
  94. return false if embed[:url].blank?
  95. @card.embed_url = (url + embed[:url]).to_s
  96. @card.image_remote_url = (url + embed[:url]).to_s
  97. @card.width = embed[:width].presence || 0
  98. @card.height = embed[:height].presence || 0
  99. when 'video'
  100. @card.width = embed[:width].presence || 0
  101. @card.height = embed[:height].presence || 0
  102. @card.html = Formatter.instance.sanitize(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  103. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  104. when 'rich'
  105. # Most providers rely on <script> tags, which is a no-no
  106. return false
  107. end
  108. @card.save_with_optional_image!
  109. end
  110. def attempt_opengraph
  111. detector = CharlockHolmes::EncodingDetector.new
  112. detector.strip_tags = true
  113. guess = detector.detect(@html, @html_charset)
  114. page = Nokogiri::HTML(@html, nil, guess&.fetch(:encoding, nil))
  115. if meta_property(page, 'twitter:player')
  116. @card.type = :video
  117. @card.width = meta_property(page, 'twitter:player:width') || 0
  118. @card.height = meta_property(page, 'twitter:player:height') || 0
  119. @card.html = content_tag(:iframe, nil, src: meta_property(page, 'twitter:player'),
  120. width: @card.width,
  121. height: @card.height,
  122. allowtransparency: 'true',
  123. scrolling: 'no',
  124. frameborder: '0')
  125. else
  126. @card.type = :link
  127. end
  128. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  129. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  130. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  131. return if @card.title.blank? && @card.html.blank?
  132. @card.save_with_optional_image!
  133. end
  134. def meta_property(page, property)
  135. page.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  136. end
  137. def lock_options
  138. { redis: Redis.current, key: "fetch:#{@url}" }
  139. end
  140. end