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.

161 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. end
  22. end
  23. attach_card if @card&.persisted?
  24. rescue HTTP::Error, Addressable::URI::InvalidURIError, Mastodon::LengthValidationError => e
  25. Rails.logger.debug "Error fetching link #{@url}: #{e}"
  26. nil
  27. end
  28. private
  29. def process_url
  30. @card ||= PreviewCard.new(url: @url)
  31. failed = Request.new(:head, @url).perform do |res|
  32. res.code != 405 && (res.code != 200 || res.mime_type != 'text/html')
  33. end
  34. return if failed
  35. Request.new(:get, @url).perform do |res|
  36. if res.code == 200 && res.mime_type == 'text/html'
  37. @html = res.body_with_limit
  38. @html_charset = res.charset
  39. else
  40. @html = nil
  41. @html_charset = nil
  42. end
  43. end
  44. return if @html.nil?
  45. attempt_oembed || attempt_opengraph
  46. end
  47. def attach_card
  48. @status.preview_cards << @card
  49. end
  50. def parse_urls
  51. if @status.local?
  52. urls = @status.text.scan(URL_PATTERN).map { |array| Addressable::URI.parse(array[0]).normalize }
  53. else
  54. html = Nokogiri::HTML(@status.text)
  55. links = html.css('a')
  56. urls = links.map { |a| Addressable::URI.parse(a['href']).normalize unless skip_link?(a) }.compact
  57. end
  58. urls.reject { |uri| bad_url?(uri) }.first
  59. end
  60. def bad_url?(uri)
  61. # Avoid local instance URLs and invalid URLs
  62. uri.host.blank? || TagManager.instance.local_url?(uri.to_s) || !%w(http https).include?(uri.scheme)
  63. end
  64. def skip_link?(a)
  65. # Avoid links for hashtags and mentions (microformats)
  66. a['rel']&.include?('tag') || a['class']&.include?('u-url')
  67. end
  68. def attempt_oembed
  69. embed = FetchOEmbedService.new.call(@url, html: @html)
  70. return false if embed.nil?
  71. @card.type = embed[:type]
  72. @card.title = embed[:title] || ''
  73. @card.author_name = embed[:author_name] || ''
  74. @card.author_url = embed[:author_url] || ''
  75. @card.provider_name = embed[:provider_name] || ''
  76. @card.provider_url = embed[:provider_url] || ''
  77. @card.width = 0
  78. @card.height = 0
  79. case @card.type
  80. when 'link'
  81. @card.image_remote_url = embed[:thumbnail_url] if embed[:thumbnail_url].present?
  82. when 'photo'
  83. return false if embed[:url].blank?
  84. @card.embed_url = embed[:url]
  85. @card.image_remote_url = embed[:url]
  86. @card.width = embed[:width].presence || 0
  87. @card.height = embed[:height].presence || 0
  88. when 'video'
  89. @card.width = embed[:width].presence || 0
  90. @card.height = embed[:height].presence || 0
  91. @card.html = Formatter.instance.sanitize(embed[:html], Sanitize::Config::MASTODON_OEMBED)
  92. @card.image_remote_url = embed[:thumbnail_url] if embed[:thumbnail_url].present?
  93. when 'rich'
  94. # Most providers rely on <script> tags, which is a no-no
  95. return false
  96. end
  97. @card.save_with_optional_image!
  98. end
  99. def attempt_opengraph
  100. detector = CharlockHolmes::EncodingDetector.new
  101. detector.strip_tags = true
  102. guess = detector.detect(@html, @html_charset)
  103. page = Nokogiri::HTML(@html, nil, guess&.fetch(:encoding, nil))
  104. if meta_property(page, 'twitter:player')
  105. @card.type = :video
  106. @card.width = meta_property(page, 'twitter:player:width') || 0
  107. @card.height = meta_property(page, 'twitter:player:height') || 0
  108. @card.html = content_tag(:iframe, nil, src: meta_property(page, 'twitter:player'),
  109. width: @card.width,
  110. height: @card.height,
  111. allowtransparency: 'true',
  112. scrolling: 'no',
  113. frameborder: '0')
  114. else
  115. @card.type = :link
  116. end
  117. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  118. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  119. @card.image_remote_url = meta_property(page, 'og:image') if meta_property(page, 'og:image')
  120. return if @card.title.blank? && @card.html.blank?
  121. @card.save_with_optional_image!
  122. end
  123. def meta_property(page, property)
  124. page.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  125. end
  126. def lock_options
  127. { redis: Redis.current, key: "fetch:#{@url}" }
  128. end
  129. end