chat_session_start.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. class Sessions::Event::ChatSessionStart < Sessions::Event::ChatBase
  2. def run
  3. return super if super
  4. return if !permission_check('chat.agent', 'chat')
  5. # find first in waiting list
  6. chat_session = Chat::Session.where(state: 'waiting').order('created_at ASC').first
  7. if !chat_session
  8. return {
  9. event: 'chat_session_start',
  10. data: {
  11. state: 'failed',
  12. message: 'No session available.',
  13. },
  14. }
  15. end
  16. chat_session.user_id = @session['id']
  17. chat_session.state = 'running'
  18. chat_session.preferences[:participants] = chat_session.add_recipient(@client_id)
  19. chat_session.save
  20. # send chat_session_init to client
  21. chat_user = User.lookup(id: chat_session.user_id)
  22. url = nil
  23. if chat_user.image && chat_user.image != 'none'
  24. url = "#{Setting.get('http_type')}://#{Setting.get('fqdn')}/api/v1/users/image/#{chat_user.image}"
  25. end
  26. user = {
  27. name: chat_user.fullname,
  28. avatar: url,
  29. }
  30. data = {
  31. event: 'chat_session_start',
  32. data: {
  33. state: 'ok',
  34. agent: user,
  35. session_id: chat_session.session_id,
  36. chat_id: chat_session.chat_id,
  37. },
  38. }
  39. # send to customer
  40. chat_session.send_to_recipients(data, @client_id)
  41. # send to agent
  42. data = {
  43. event: 'chat_session_start',
  44. data: {
  45. session: chat_session.attributes,
  46. },
  47. }
  48. Sessions.send(@client_id, data)
  49. # send state update with sessions to agents
  50. Chat.broadcast_agent_state_update
  51. # send position update to other waiting sessions
  52. Chat.broadcast_customer_state_update
  53. nil
  54. end
  55. end