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.

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