闭社主体 forked from https://github.com/tootsuite/mastodon
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.

152 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. @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 = URI.parse(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 = URI.parse(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. when 'rich'
  84. # Most providers rely on <script> tags, which is a no-no
  85. return false
  86. end
  87. @card.save_with_optional_image!
  88. rescue OEmbed::NotFound
  89. false
  90. end
  91. def attempt_opengraph
  92. detector = CharlockHolmes::EncodingDetector.new
  93. detector.strip_tags = true
  94. guess = detector.detect(@html, @response.charset)
  95. page = Nokogiri::HTML(@html, nil, guess&.fetch(:encoding, nil))
  96. if meta_property(page, 'twitter:player')
  97. @card.type = :video
  98. @card.width = meta_property(page, 'twitter:player:width') || 0
  99. @card.height = meta_property(page, 'twitter:player:height') || 0
  100. @card.html = content_tag(:iframe, nil, src: meta_property(page, 'twitter:player'),
  101. width: @card.width,
  102. height: @card.height,
  103. allowtransparency: 'true',
  104. scrolling: 'no',
  105. frameborder: '0')
  106. else
  107. @card.type = :link
  108. @card.image_remote_url = meta_property(page, 'og:image') if meta_property(page, 'og:image')
  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. return if @card.title.blank? && @card.html.blank?
  113. @card.save_with_optional_image!
  114. end
  115. def meta_property(page, property)
  116. page.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || page.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  117. end
  118. def lock_options
  119. { redis: Redis.current, key: "fetch:#{@url}" }
  120. end
  121. end