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

74 lines
2.6 KiB

  1. # frozen_string_literal: true
  2. class FetchLinkCardService < BaseService
  3. include HttpHelper
  4. URL_PATTERN = %r{https?://\S+}
  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. url = Addressable::URI.parse(url).normalize.to_s
  10. card = PreviewCard.where(status: status).first_or_initialize(status: status, url: url)
  11. attempt_opengraph(card, url) unless attempt_oembed(card, url)
  12. end
  13. private
  14. def attempt_oembed(card, url)
  15. response = OEmbed::Providers.get(url)
  16. card.type = response.type
  17. card.title = response.respond_to?(:title) ? response.title : ''
  18. card.author_name = response.respond_to?(:author_name) ? response.author_name : ''
  19. card.author_url = response.respond_to?(:author_url) ? response.author_url : ''
  20. card.provider_name = response.respond_to?(:provider_name) ? response.provider_name : ''
  21. card.provider_url = response.respond_to?(:provider_url) ? response.provider_url : ''
  22. card.width = 0
  23. card.height = 0
  24. case card.type
  25. when 'link'
  26. card.image = URI.parse(response.thumbnail_url) if response.respond_to?(:thumbnail_url)
  27. when 'photo'
  28. card.url = response.url
  29. card.width = response.width.presence || 0
  30. card.height = response.height.presence || 0
  31. when 'video'
  32. card.width = response.width.presence || 0
  33. card.height = response.height.presence || 0
  34. card.html = Formatter.instance.sanitize(response.html, Sanitize::Config::MASTODON_OEMBED)
  35. when 'rich'
  36. # Most providers rely on <script> tags, which is a no-no
  37. return false
  38. end
  39. card.save_with_optional_image!
  40. rescue OEmbed::NotFound
  41. false
  42. end
  43. def attempt_opengraph(card, url)
  44. response = http_client.get(url)
  45. return if response.code != 200 || response.mime_type != 'text/html'
  46. page = Nokogiri::HTML(response.to_s)
  47. card.type = :link
  48. card.title = meta_property(page, 'og:title') || page.at_xpath('//title')&.content
  49. card.description = meta_property(page, 'og:description') || meta_property(page, 'description')
  50. card.image = URI.parse(Addressable::URI.parse(meta_property(page, 'og:image')).normalize.to_s) if meta_property(page, 'og:image')
  51. return if card.title.blank?
  52. card.save_with_optional_image!
  53. end
  54. def meta_property(html, property)
  55. html.at_xpath("//meta[@property=\"#{property}\"]")&.attribute('content')&.value || html.at_xpath("//meta[@name=\"#{property}\"]")&.attribute('content')&.value
  56. end
  57. end