broadcast.rb 1.8 KB

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