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.

60 lines
1.5 KiB

  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. latest_options = items.map { |item| item['name'].presence || item['content'] }
  25. # If for some reasons the options were changed, it invalidates all previous
  26. # votes, so we need to remove them
  27. poll.votes.delete_all if latest_options != poll.options
  28. begin
  29. poll.update!(
  30. last_fetched_at: Time.now.utc,
  31. expires_at: expires_at,
  32. options: latest_options,
  33. cached_tallies: items.map { |item| item.dig('replies', 'totalItems') || 0 }
  34. )
  35. rescue ActiveRecord::StaleObjectError
  36. poll.reload
  37. retry
  38. end
  39. # If the poll had no expiration date set but now has, and people have voted,
  40. # schedule a notification.
  41. if previous_expires_at.nil? && poll.expires_at.present? && poll.votes.exists?
  42. PollExpirationNotifyWorker.perform_at(poll.expires_at + 5.minutes, poll.id)
  43. end
  44. end
  45. private
  46. def expected_type?
  47. equals_or_includes_any?(@json['type'], %w(Question))
  48. end
  49. end