trabajo-afectivo/lib/sessions/event/chat_session_start.rb

59 lines
1.5 KiB
Ruby
Raw Normal View History

class Sessions::Event::ChatSessionStart < Sessions::Event::ChatBase
2015-11-10 14:01:04 +00:00
def run
2015-11-10 14:01:04 +00:00
# find first in waiting list
chat_session = Chat::Session.where(state: 'waiting').order('created_at ASC').first
if !chat_session
return {
event: 'chat_session_start',
data: {
state: 'failed',
message: 'No session available.',
},
}
end
chat_session.user_id = @session['id']
2015-11-10 14:01:04 +00:00
chat_session.state = 'running'
chat_session.preferences[:participants] = chat_session.add_recipient(@client_id)
2015-11-10 14:01:04 +00:00
chat_session.save
# send chat_session_init to client
chat_user = User.find(chat_session.user_id)
url = nil
if chat_user.image && chat_user.image != 'none'
url = "/api/v1/users/image/#{chat_user.image}"
end
2015-11-10 14:01:04 +00:00
user = {
name: chat_user.fullname,
avatar: url,
2015-11-10 14:01:04 +00:00
}
data = {
event: 'chat_session_start',
data: {
state: 'ok',
agent: user,
session_id: chat_session.session_id,
},
}
chat_session.send_to_recipients(data)
2015-11-10 14:01:04 +00:00
# send position update to other waiting sessions
position = 0
Chat::Session.where(state: 'waiting').order('created_at ASC').each {|local_chat_session|
position += 1
data = {
event: 'chat_session_queue',
data: {
state: 'queue',
position: position,
session_id: local_chat_session.session_id,
},
}
local_chat_session.send_to_recipients(data)
2015-11-10 14:01:04 +00:00
}
nil
2015-11-10 14:01:04 +00:00
end
end