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.

35 lines
1.2 KiB

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