push_messages.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module PushMessages
  3. def self.enabled?
  4. return true if Thread.current[:push_messages].instance_of?(Array)
  5. false
  6. end
  7. def self.init
  8. return true if enabled?
  9. Thread.current[:push_messages] = []
  10. end
  11. def self.send(data) # rubocop:disable Zammad/ForbidDefSend
  12. if !PushMessages.enabled?
  13. Sessions.broadcast(
  14. data[:message],
  15. data[:type],
  16. data[:current_user_id],
  17. )
  18. return true
  19. end
  20. message = { type: 'broadcast', data: data }
  21. Thread.current[:push_messages].push message
  22. end
  23. def self.send_to(user_id, data)
  24. if !PushMessages.enabled?
  25. Sessions.send_to(user_id, data)
  26. return true
  27. end
  28. message = { type: 'send_to', user_id: user_id, data: data }
  29. Thread.current[:push_messages].push message
  30. end
  31. def self.finish
  32. return false if !enabled?
  33. Thread.current[:push_messages].each do |message|
  34. if message[:type] == 'send_to'
  35. Sessions.send_to(message[:user_id], message[:data])
  36. else
  37. Sessions.broadcast(
  38. message[:data][:message],
  39. message[:data][:type],
  40. message[:data][:current_user_id],
  41. )
  42. end
  43. end
  44. Thread.current[:push_messages] = nil
  45. true
  46. end
  47. end