vote_service.rb 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # frozen_string_literal: true
  2. class VoteService < BaseService
  3. include Authorization
  4. def call(account, poll, choices)
  5. authorize_with account, poll, :vote?
  6. @account = account
  7. @poll = poll
  8. @choices = choices
  9. @votes = []
  10. return if @poll.expired?
  11. ApplicationRecord.transaction do
  12. @choices.each do |choice|
  13. @votes << @poll.votes.create!(account: @account, choice: choice)
  14. end
  15. end
  16. if @poll.account.local?
  17. distribute_poll!
  18. else
  19. deliver_votes!
  20. queue_final_poll_check!
  21. end
  22. end
  23. private
  24. def distribute_poll!
  25. return if @poll.hide_totals?
  26. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, @poll.status.id)
  27. end
  28. def queue_final_poll_check!
  29. return unless @poll.expires?
  30. PollExpirationNotifyWorker.perform_at(@poll.expires_at + 5.minutes, @poll.id)
  31. end
  32. def deliver_votes!
  33. @votes.each do |vote|
  34. ActivityPub::DeliveryWorker.perform_async(
  35. build_json(vote),
  36. @account.id,
  37. @poll.account.inbox_url
  38. )
  39. end
  40. end
  41. def build_json(vote)
  42. ActiveModelSerializers::SerializableResource.new(
  43. vote,
  44. serializer: ActivityPub::VoteSerializer,
  45. adapter: ActivityPub::Adapter
  46. ).to_json
  47. end
  48. end