broadcast.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Sessions::Event::Broadcast < Sessions::Event::Base
  3. =begin
  4. Event module to broadcast messages to all client connections.
  5. To execute this manually, just paste the following into the browser console
  6. App.WebSocket.send({event:'broadcast', recipient: { user_id: [1,2,3]}, data: {some: 'key'}})
  7. =end
  8. def run
  9. # list all current clients
  10. client_list = Sessions.list
  11. client_list.each do |local_client_id, local_client|
  12. if local_client_id == @client_id
  13. log 'info', 'do not send broadcast to itself'
  14. next
  15. end
  16. # broadcast to recipient list
  17. if @payload['recipient']
  18. if @payload['recipient'].class != Hash && @payload['recipient'].class != ActiveSupport::HashWithIndifferentAccess && @payload['recipient'].class != ActionController::Parameters
  19. log 'error', "recipient attribute isn't a hash (#{@payload['recipient'].class}) '#{@payload['recipient'].inspect}'"
  20. elsif !@payload['recipient'].key?('user_id')
  21. log 'error', "need recipient.user_id attribute '#{@payload['recipient'].inspect}'"
  22. elsif @payload['recipient']['user_id'].class != Array
  23. log 'error', "recipient.user_id attribute isn't an array '#{@payload['recipient']['user_id'].inspect}'"
  24. else
  25. @payload['recipient']['user_id'].each do |user_id|
  26. next if local_client[:user]['id'].to_i != user_id.to_i
  27. log 'info', "send broadcast from (#{@client_id}) to (user_id=#{user_id})", local_client_id
  28. websocket_send(local_client_id, @payload['data'])
  29. end
  30. end
  31. # broadcast every client
  32. else
  33. log 'info', "send broadcast from (#{@client_id})", local_client_id
  34. websocket_send(local_client_id, @payload['data'])
  35. end
  36. end
  37. false
  38. end
  39. end