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.

38 lines
1.4 KiB

  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. URL_PATTERN = %r{https?://\S+}
  4. USER_AGENT = "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::VERSION}; +http://#{Rails.configuration.x.local_domain}/)"
  5. def call(status)
  6. # Get first http/https URL that isn't local
  7. url = status.text.match(URL_PATTERN).to_a.reject { |uri| TagManager.instance.local_url?(uri) }.first
  8. return if url.nil?
  9. response = http_client.get(url)
  10. return if response.code != 200 || response.mime_type != 'text/html'
  11. page = Nokogiri::HTML(response.to_s)
  12. card = PreviewCard.where(status: status).first_or_initialize(status: status, url: url)
  13. card.title = meta_property(page, 'og:title') || page.at_xpath('//title')&.content
  14. card.description = meta_property(page, 'og:description') || meta_property(page, 'description')
  15. card.image = URI.parse(Addressable::URI.parse(meta_property(page, 'og:image')).normalize.to_s) if meta_property(page, 'og:image')
  16. return if card.title.blank?
  17. card.save_with_optional_image!
  18. end
  19. private
  20. def http_client
  21. HTTP.headers(user_agent: USER_AGENT).timeout(:per_operation, write: 10, connect: 10, read: 10).follow
  22. end
  23. def meta_property(html, property)
  24. html.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || html.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  25. end
  26. end