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.
 
 
 
 

34 lines
1.1 KiB

  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. def call(status)
  4. # Get first URL
  5. url = URI.extract(status.text).reject { |uri| (uri =~ /\Ahttps?:\/\//).nil? }.first
  6. return if url.nil?
  7. response = http_client.get(url)
  8. return if response.code != 200
  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. card.save_with_optional_image!
  15. end
  16. private
  17. def http_client
  18. HTTP.timeout(:per_operation, write: 10, connect: 10, read: 10).follow
  19. end
  20. def meta_property(html, property)
  21. html.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || html.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  22. end
  23. end