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.

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