The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

178 lines
6.5 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 || @card.missing_image?
  21. else
  22. raise Mastodon::RaceConditionError
  23. end
  24. end
  25. attach_card if @card&.persisted?
  26. rescue HTTP::Error, OpenSSL::SSL::SSLError, 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. attempt_oembed || attempt_opengraph
  34. end
  35. def html
  36. return @html if defined?(@html)
  37. Request.new(:get, @url).add_headers('Accept' => 'text/html').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. end
  47. def attach_card
  48. @status.preview_cards << @card
  49. Rails.cache.delete(@status)
  50. end
  51. def parse_urls
  52. if @status.local?
  53. urls = @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[0]).normalize }
  54. else
  55. html = Nokogiri::HTML(@status.text)
  56. links = html.css('a')
  57. urls = links.map { |a| Addressable::URI.parse(a['href']) unless skip_link?(a) }.compact.map(&:normalize).compact
  58. end
  59. urls.reject { |uri| bad_url?(uri) }.first
  60. end
  61. def bad_url?(uri)
  62. # Avoid local instance URLs and invalid URLs
  63. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  64. end
  65. def mention_link?(a)
  66. @status.mentions.any? do |mention|
  67. a['href'] == ActivityPub::TagManager.instance.url_for(mention.account)
  68. end
  69. end
  70. def skip_link?(a)
  71. # Avoid links for hashtags and mentions (microformats)
  72. a['rel']&.include?('tag') || a['class']&.match?(/u-url|h-card/) || mention_link?(a)
  73. end
  74. def attempt_oembed
  75. service = FetchOEmbedService.new
  76. url_domain = Addressable::URI.parse(@url).normalized_host
  77. cached_endpoint = Rails.cache.read("oembed_endpoint:#{url_domain}")
  78. embed = service.call(@url, cached_endpoint: cached_endpoint) unless cached_endpoint.nil?
  79. embed ||= service.call(@url, html: html) unless html.nil?
  80. return false if embed.nil?
  81. url = Addressable::URI.parse(service.endpoint_url)
  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. return if html.nil?
  112. detector = CharlockHolmes::EncodingDetector.new
  113. detector.strip_tags = true
  114. guess = detector.detect(@html, @html_charset)
  115. encoding = guess&.fetch(:confidence, 0).to_i > 60 ? guess&.fetch(:encoding, nil) : nil
  116. page = Nokogiri::HTML(@html, nil, encoding)
  117. player_url = meta_property(page, 'twitter:player')
  118. if player_url && !bad_url?(Addressable::URI.parse(player_url))
  119. @card.type = :video
  120. @card.width = meta_property(page, 'twitter:player:width') || 0
  121. @card.height = meta_property(page, 'twitter:player:height') || 0
  122. @card.html = content_tag(:iframe, nil, src: player_url,
  123. width: @card.width,
  124. height: @card.height,
  125. allowtransparency: 'true',
  126. scrolling: 'no',
  127. frameborder: '0')
  128. else
  129. @card.type = :link
  130. end
  131. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  132. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  133. @card.image_remote_url = (Addressable::URI.parse(@url) + meta_property(page, 'og:image')).to_s if meta_property(page, 'og:image')
  134. return if @card.title.blank? && @card.html.blank?
  135. @card.save_with_optional_image!
  136. end
  137. def meta_property(page, property)
  138. page.at_xpath("//meta[contains(concat(' ', normalize-space(@property), ' '), ' #{property} ')]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  139. end
  140. def lock_options
  141. { redis: Redis.current, key: "fetch:#{@url}" }
  142. end
  143. end