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.

51 lines
1.2 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRemotePollService < BaseService
  3. include JsonLdHelper
  4. def call(poll, on_behalf_of = nil)
  5. @json = fetch_resource(poll.status.uri, true, on_behalf_of)
  6. return unless supported_context? && expected_type?
  7. expires_at = begin
  8. if @json['closed'].is_a?(String)
  9. @json['closed']
  10. elsif !@json['closed'].nil? && !@object['closed'].is_a?(FalseClass)
  11. Time.now.utc
  12. else
  13. @json['endTime']
  14. end
  15. end
  16. items = begin
  17. if @json['anyOf'].is_a?(Array)
  18. @json['anyOf']
  19. else
  20. @json['oneOf']
  21. end
  22. end
  23. latest_options = items.map { |item| item['name'].presence || item['content'] }
  24. # If for some reasons the options were changed, it invalidates all previous
  25. # votes, so we need to remove them
  26. poll.votes.delete_all if latest_options != poll.options
  27. poll.update!(
  28. expires_at: expires_at,
  29. options: latest_options,
  30. cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 }
  31. )
  32. end
  33. private
  34. def supported_context?
  35. super(@json)
  36. end
  37. def expected_type?
  38. equals_or_includes_any?(@json['type'], %w(Question))
  39. end
  40. end