process_poll_service.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # frozen_string_literal: true
  2. class ActivityPub::ProcessPollService < BaseService
  3. include JsonLdHelper
  4. def call(poll, json)
  5. @json = json
  6. return unless expected_type?
  7. previous_expires_at = poll.expires_at
  8. expires_at = begin
  9. if @json['closed'].is_a?(String)
  10. @json['closed']
  11. elsif !@json['closed'].nil? && !@json['closed'].is_a?(FalseClass)
  12. Time.now.utc
  13. else
  14. @json['endTime']
  15. end
  16. end
  17. items = begin
  18. if @json['anyOf'].is_a?(Array)
  19. @json['anyOf']
  20. else
  21. @json['oneOf']
  22. end
  23. end
  24. voters_count = @json['votersCount']
  25. latest_options = items.map { |item| item['name'].presence || item['content'] }.compact
  26. # If for some reasons the options were changed, it invalidates all previous
  27. # votes, so we need to remove them
  28. poll.votes.delete_all if latest_options != poll.options
  29. begin
  30. poll.update!(
  31. last_fetched_at: Time.now.utc,
  32. expires_at: expires_at,
  33. options: latest_options,
  34. cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 },
  35. voters_count: voters_count
  36. )
  37. rescue ActiveRecord::StaleObjectError
  38. poll.reload
  39. retry
  40. end
  41. # If the poll had no expiration date set but now has, and people have voted,
  42. # schedule a notification.
  43. if previous_expires_at.nil? && poll.expires_at.present? && poll.votes.exists?
  44. PollExpirationNotifyWorker.perform_at(poll.expires_at + 5.minutes, poll.id)
  45. end
  46. end
  47. private
  48. def expected_type?
  49. equals_or_includes_any?(@json['type'], %w(Question))
  50. end
  51. end