闭社主体 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.

37 lines
1.3 KiB

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