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.

82 lines
1.8 KiB

  1. # frozen_string_literal: true
  2. class VoteService < BaseService
  3. include Authorization
  4. include Payloadable
  5. def call(account, poll, choices)
  6. authorize_with account, poll, :vote?
  7. @account = account
  8. @poll = poll
  9. @choices = choices
  10. @votes = []
  11. already_voted = true
  12. RedisLock.acquire(lock_options) do |lock|
  13. if lock.acquired?
  14. already_voted = @poll.votes.where(account: @account).exists?
  15. ApplicationRecord.transaction do
  16. @choices.each do |choice|
  17. @votes << @poll.votes.create!(account: @account, choice: Integer(choice))
  18. end
  19. end
  20. else
  21. raise Mastodon::RaceConditionError
  22. end
  23. end
  24. increment_voters_count! unless already_voted
  25. ActivityTracker.increment('activity:interactions')
  26. if @poll.account.local?
  27. distribute_poll!
  28. else
  29. deliver_votes!
  30. queue_final_poll_check!
  31. end
  32. end
  33. private
  34. def distribute_poll!
  35. return if @poll.hide_totals?
  36. ActivityPub::DistributePollUpdateWorker.perform_in(3.minutes, @poll.status.id)
  37. end
  38. def queue_final_poll_check!
  39. return unless @poll.expires?
  40. PollExpirationNotifyWorker.perform_at(@poll.expires_at + 5.minutes, @poll.id)
  41. end
  42. def deliver_votes!
  43. @votes.each do |vote|
  44. ActivityPub::DeliveryWorker.perform_async(
  45. build_json(vote),
  46. @account.id,
  47. @poll.account.inbox_url
  48. )
  49. end
  50. end
  51. def build_json(vote)
  52. Oj.dump(serialize_payload(vote, ActivityPub::VoteSerializer))
  53. end
  54. def increment_voters_count!
  55. unless @poll.voters_count.nil?
  56. @poll.voters_count = @poll.voters_count + 1
  57. @poll.save
  58. end
  59. rescue ActiveRecord::StaleObjectError
  60. @poll.reload
  61. retry
  62. end
  63. def lock_options
  64. { redis: Redis.current, key: "vote:#{@poll.id}:#{@account.id}" }
  65. end
  66. end