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.
 
 
 
 

149 lines
5.3 KiB

  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. URL_PATTERN = %r{
  4. ( # $1 URL
  5. (https?:\/\/)? # $2 Protocol (optional)
  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 != 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. @card.type = response.type
  59. @card.title = response.respond_to?(:title) ? response.title : ''
  60. @card.author_name = response.respond_to?(:author_name) ? response.author_name : ''
  61. @card.author_url = response.respond_to?(:author_url) ? response.author_url : ''
  62. @card.provider_name = response.respond_to?(:provider_name) ? response.provider_name : ''
  63. @card.provider_url = response.respond_to?(:provider_url) ? response.provider_url : ''
  64. @card.width = 0
  65. @card.height = 0
  66. case @card.type
  67. when 'link'
  68. @card.image = URI.parse(response.thumbnail_url) if response.respond_to?(:thumbnail_url)
  69. when 'photo'
  70. @card.url = response.url
  71. @card.width = response.width.presence || 0
  72. @card.height = response.height.presence || 0
  73. when 'video'
  74. @card.width = response.width.presence || 0
  75. @card.height = response.height.presence || 0
  76. @card.html = Formatter.instance.sanitize(response.html, Sanitize::Config::MASTODON_OEMBED)
  77. when 'rich'
  78. # Most providers rely on <script> tags, which is a no-no
  79. return false
  80. end
  81. @card.save_with_optional_image!
  82. rescue OEmbed::NotFound
  83. false
  84. end
  85. def attempt_opengraph
  86. response = Request.new(:get, @url).perform
  87. return if response.code != 200 || response.mime_type != 'text/html'
  88. html = response.to_s
  89. detector = CharlockHolmes::EncodingDetector.new
  90. detector.strip_tags = true
  91. guess = detector.detect(html, response.charset)
  92. page = Nokogiri::HTML(html, nil, guess&.fetch(:encoding))
  93. if meta_property(page, 'twitter:player')
  94. @card.type = :video
  95. @card.width = meta_property(page, 'twitter:player:width') || 0
  96. @card.height = meta_property(page, 'twitter:player:height') || 0
  97. @card.html = content_tag(:iframe, nil, src: meta_property(page, 'twitter:player'),
  98. width: @card.width,
  99. height: @card.height,
  100. allowtransparency: 'true',
  101. scrolling: 'no',
  102. frameborder: '0')
  103. else
  104. @card.type = :link
  105. @card.image_remote_url = meta_property(page, 'og:image') if meta_property(page, 'og:image')
  106. end
  107. @card.title = meta_property(page, 'og:title').presence || page.at_xpath('//title')&.content || ''
  108. @card.description = meta_property(page, 'og:description').presence || meta_property(page, 'description') || ''
  109. return if @card.title.blank? && @card.html.blank?
  110. @card.save_with_optional_image!
  111. end
  112. def meta_property(html, property)
  113. html.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || html.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  114. end
  115. def lock_options
  116. { redis: Redis.current, key: "fetch:#{@url}" }
  117. end
  118. end