fetch_link_card_service.rb 5.6 KB

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