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.

165 lines
5.9 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::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. failed = Request.new(:head, @url).perform do |res|
  34. res.code != 405 && res.code != 501 && (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. service = FetchOEmbedService.new
  72. embed = service.call(@url, html: @html)
  73. url = Addressable::URI.parse(service.endpoint_url)
  74. return false if embed.nil?
  75. @card.type = embed[:type]
  76. @card.title = embed[:title] || ''
  77. @card.author_name = embed[:author_name] || ''
  78. @card.author_url = embed[:author_url].present? ? (url + embed[:author_url]).to_s : ''
  79. @card.provider_name = embed[:provider_name] || ''
  80. @card.provider_url = embed[:provider_url].present? ? (url + embed[:provider_url]).to_s : ''
  81. @card.width = 0
  82. @card.height = 0
  83. case @card.type
  84. when 'link'
  85. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  86. when 'photo'
  87. return false if embed[:url].blank?
  88. @card.embed_url = (url + embed[:url]).to_s
  89. @card.image_remote_url = (url + embed[:url]).to_s
  90. @card.width = embed[:width].presence || 0
  91. @card.height = embed[:height].presence || 0
  92. when 'video'
  93. @card.width = embed[:width].presence || 0
  94. @card.height = embed[:height].presence || 0
  95. @card.html = Formatter.instance.sanitize(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  96. @card.image_remote_url = (url + embed[:thumbnail_url]).to_s if embed[:thumbnail_url].present?
  97. when 'rich'
  98. # Most providers rely on <script> tags, which is a no-no
  99. return false
  100. end
  101. @card.save_with_optional_image!
  102. end
  103. def attempt_opengraph
  104. detector = CharlockHolmes::EncodingDetector.new
  105. detector.strip_tags = true
  106. guess = detector.detect(@html, @html_charset)
  107. page = Nokogiri::HTML(@html, nil, guess&.fetch(:encoding, nil))
  108. if meta_property(page, 'twitter:player')
  109. @card.type = :video
  110. @card.width = meta_property(page, 'twitter:player:width') || 0
  111. @card.height = meta_property(page, 'twitter:player:height') || 0
  112. @card.html = content_tag(:iframe, nil, src: meta_property(page, 'twitter:player'),
  113. width: @card.width,
  114. height: @card.height,
  115. allowtransparency: 'true',
  116. scrolling: 'no',
  117. frameborder: '0')
  118. else
  119. @card.type = :link
  120. end
  121. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  122. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  123. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  124. return if @card.title.blank? && @card.html.blank?
  125. @card.save_with_optional_image!
  126. end
  127. def meta_property(page, property)
  128. page.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  129. end
  130. def lock_options
  131. { redis: Redis.current, key: "fetch:#{@url}" }
  132. end
  133. end