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

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