poll_parser.rb 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # frozen_string_literal: true
  2. class ActivityPub::Parser::PollParser
  3. include JsonLdHelper
  4. def initialize(json)
  5. @json = json
  6. end
  7. def valid?
  8. equals_or_includes?(@json['type'], 'Question') && items.is_a?(Array)
  9. end
  10. # @param [Poll] previous_record
  11. def significantly_changes?(previous_record)
  12. options != previous_record.options ||
  13. multiple != previous_record.multiple
  14. end
  15. def options
  16. items.filter_map { |item| item['name'].presence || item['content'] }
  17. end
  18. def multiple
  19. @json['anyOf'].is_a?(Array)
  20. end
  21. def expires_at
  22. if @json['closed'].is_a?(String)
  23. @json['closed'].to_datetime
  24. elsif !@json['closed'].nil? && !@json['closed'].is_a?(FalseClass)
  25. Time.now.utc
  26. else
  27. @json['endTime']&.to_datetime
  28. end
  29. rescue ArgumentError
  30. nil
  31. end
  32. def voters_count
  33. @json['votersCount']
  34. end
  35. def cached_tallies
  36. items.map { |item| item.dig('replies', 'totalItems') || 0 }
  37. end
  38. private
  39. def items
  40. @json['anyOf'] || @json['oneOf']
  41. end
  42. end