chat_session_start.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. class Sessions::Event::ChatSessionStart < Sessions::Event::ChatBase
  2. =begin
  3. a agent start`s a new chat session
  4. payload
  5. {
  6. event: 'chat_session_start',
  7. data: {},
  8. }
  9. return is sent as message back to peer
  10. =end
  11. def run
  12. return super if super
  13. return if !permission_check('chat.agent', 'chat')
  14. # find first in waiting list
  15. chat_user = User.lookup(id: @session['id'])
  16. chat_ids = Chat.agent_active_chat_ids(chat_user)
  17. chat_session = if @payload['chat_id']
  18. Chat::Session.where(state: 'waiting', chat_id: @payload['chat_id']).order(created_at: :asc).first
  19. else
  20. Chat::Session.where(state: 'waiting', chat_id: chat_ids).order(created_at: :asc).first
  21. end
  22. if !chat_session
  23. return {
  24. event: 'chat_session_start',
  25. data: {
  26. state: 'failed',
  27. message: 'No session available.',
  28. },
  29. }
  30. end
  31. chat_session.user_id = chat_user.id
  32. chat_session.state = 'running'
  33. chat_session.preferences[:participants] = chat_session.add_recipient(@client_id)
  34. chat_session.save
  35. session_attributes = chat_session.attributes
  36. session_attributes['messages'] = []
  37. Chat::Message.where(chat_session_id: chat_session.id).order(created_at: :asc).each do |message|
  38. session_attributes['messages'].push message.attributes
  39. end
  40. # send chat_session_init to customer client
  41. if session_attributes['messages'].blank?
  42. user = chat_session.agent_user
  43. data = {
  44. event: 'chat_session_start',
  45. data: {
  46. state: 'ok',
  47. agent: user,
  48. session_id: chat_session.session_id,
  49. chat_id: chat_session.chat_id,
  50. },
  51. }
  52. chat_session.send_to_recipients(data, @client_id)
  53. end
  54. # send to agent
  55. data = {
  56. event: 'chat_session_start',
  57. data: {
  58. session: session_attributes,
  59. },
  60. }
  61. Sessions.send(@client_id, data)
  62. # send state update with sessions to agents
  63. Chat.broadcast_agent_state_update([chat_session.chat_id])
  64. # send position update to other waiting sessions
  65. Chat.broadcast_customer_state_update(chat_session.chat_id)
  66. nil
  67. end
  68. end