trabajo-afectivo/public/assets/chat/chat.coffee

645 lines
18 KiB
CoffeeScript
Raw Normal View History

2015-10-15 09:14:19 +00:00
do($ = window.jQuery, window) ->
scripts = document.getElementsByTagName('script')
myScript = scripts[scripts.length - 1]
2015-11-25 09:35:57 +00:00
scriptHost = myScript.src.match('.*://([^:/]*).*')[1]
2015-10-15 09:14:19 +00:00
# Define the plugin class
class ZammadChat
defaults:
chatId: undefined
2015-11-13 14:15:44 +00:00
show: true
2015-10-15 09:14:19 +00:00
target: $('body')
host: ''
2015-11-13 14:15:44 +00:00
debug: false
2015-11-24 12:04:31 +00:00
flat: false
2015-11-25 23:40:52 +00:00
lang: undefined
cssAutoload: true
cssUrl: undefined
2015-11-16 10:46:42 +00:00
fontSize: undefined
buttonClass: 'open-zammad-chat'
inactiveClass: 'is-inactive'
2015-11-17 00:43:36 +00:00
title: '<strong>Chat</strong> with us!'
2015-12-01 18:44:31 +00:00
idleTimeout: 4
2015-11-25 23:40:52 +00:00
inactiveTimeout: 20
2015-10-15 09:14:19 +00:00
_messageCount: 0
2015-11-13 14:15:44 +00:00
isOpen: true
2015-10-15 09:14:19 +00:00
blinkOnlineInterval: null
stopBlinOnlineStateTimeout: null
showTimeEveryXMinutes: 1
lastTimestamp: null
lastAddedType: null
inputTimeout: null
isTyping: false
state: 'offline'
initialQueueDelay: 10000
wsReconnectEnable: true
translations:
de:
'<strong>Chat</strong> with us!': '<strong>Chat</strong> mit uns!'
'Online': 'Online'
'Online': 'Online'
'Offline': 'Offline'
'Connecting': 'Verbinden'
'Connection re-established': 'Verbindung wiederhergestellt'
'Today': 'Heute'
'Send': 'Senden'
'Compose your message...': 'Ihre Nachricht...'
'All colleges are busy.': 'Alle Kollegen sind belegt.'
'You are on waiting list position <strong>%s</strong>.': 'Sie sind in der Warteliste an der Position <strong>%s</strong>.'
'Start new conversation': 'Neue Konversation starten'
2015-11-25 23:40:52 +00:00
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> got closed.': 'Da Sie in den letzten %s Minuten nichts geschrieben haben wurde Ihre Konversation mit <strong>%s</strong> geschlossen.'
'Since you didn\'t respond in the last %s minutes your conversation got closed.': 'Da Sie in den letzten %s Minuten nichts geschrieben haben wurde Ihre Konversation geschlossen.'
2015-11-12 10:44:37 +00:00
sessionId: undefined
T: (string, items...) =>
if @options.lang && @options.lang isnt 'en'
if !@translations[@options.lang]
@log 'notice', "Translation '#{@options.lang}' needed!"
else
translations = @translations[@options.lang]
if !translations[string]
@log 'notice', "Translation needed for '#{string}'"
string = translations[string] || string
if items
for item in items
string = string.replace(/%s/, item)
string
log: (level, string...) =>
2015-11-13 14:15:44 +00:00
return if !@options.debug && level is 'debug'
2015-11-13 10:13:02 +00:00
string.unshift(level)
console.log.apply console, string
2015-10-15 09:14:19 +00:00
view: (name) =>
return (options) =>
if !options
options = {}
options.T = @T
options.background = @options.background
options.flat = @options.flat
2015-11-16 10:46:42 +00:00
options.fontSize = @options.fontSize
return window.zammadChatTemplates[name](options)
2015-10-15 09:14:19 +00:00
constructor: (options) ->
@options = $.extend {}, @defaults, options
2015-11-13 14:15:44 +00:00
# check prerequisites
2015-11-25 23:40:52 +00:00
if !$
@state = 'unsupported'
@log 'notice', 'Chat: no jquery found!'
return
2015-11-13 14:15:44 +00:00
if !window.WebSocket or !sessionStorage
@state = 'unsupported'
2015-11-13 14:15:44 +00:00
@log 'notice', 'Chat: Browser not supported!'
return
if !@options.chatId
2015-11-25 09:35:57 +00:00
@state = 'unsupported'
@log 'error', 'Chat: need chatId as option!'
2015-11-25 09:35:57 +00:00
return
# detect language
if !@options.lang
@options.lang = $('html').attr('lang')
if @options.lang
@options.lang = @options.lang.replace(/-.+?$/, '') # replace "-xx" of xx-xx
@log 'debug', "lang: #{@options.lang}"
2015-11-17 00:43:36 +00:00
@el = $(@view('chat')(
title: @options.title
))
2015-10-15 09:14:19 +00:00
@options.target.append @el
@input = @el.find('.zammad-chat-input')
# disable open button
$(".#{ @options.buttonClass }").addClass @inactiveClass
@el.find('.js-chat-open').click @open
2015-11-11 10:44:10 +00:00
@el.find('.js-chat-close').click @close
2015-10-15 09:14:19 +00:00
@el.find('.zammad-chat-controls').on 'submit', @onSubmit
@input.on
2015-10-15 09:14:19 +00:00
keydown: @checkForEnter
input: @onInput
@wsConnect()
2015-10-15 15:07:18 +00:00
@loadCss()
2015-10-15 09:14:19 +00:00
checkForEnter: (event) =>
if not event.shiftKey and event.keyCode is 13
event.preventDefault()
@sendMessage()
2015-11-25 09:35:57 +00:00
send: (event, data = {}) =>
data.chat_id = @options.chatId
@log 'debug', 'ws:send', event, data
pipe = JSON.stringify
2015-11-10 14:01:04 +00:00
event: event
data: data
@ws.send pipe
onWebSocketMessage: (e) =>
2015-11-10 14:01:04 +00:00
pipes = JSON.parse( e.data )
for pipe in pipes
@log 'debug', 'ws:onmessage', pipe
2015-11-10 14:01:04 +00:00
switch pipe.event
2015-11-25 09:35:57 +00:00
when 'chat_error'
2015-11-25 23:40:52 +00:00
@log 'notice', pipe.data
if pipe.data && pipe.data.state is 'chat_disabled'
@wsClose()
2015-11-10 14:01:04 +00:00
when 'chat_session_message'
return if pipe.data.self_written
@receiveMessage pipe.data
when 'chat_session_typing'
return if pipe.data.self_written
@onAgentTypingStart()
when 'chat_session_start'
@onConnectionEstablished pipe.data
2015-11-12 10:44:37 +00:00
when 'chat_session_queue'
2015-11-12 15:16:01 +00:00
@onQueueScreen pipe.data
when 'chat_session_closed'
@onSessionClosed pipe.data
when 'chat_session_left'
@onSessionClosed pipe.data
2015-11-11 10:24:19 +00:00
when 'chat_status_customer'
2015-11-10 14:01:04 +00:00
switch pipe.data.state
when 'online'
@sessionId = undefined
2015-11-10 14:01:04 +00:00
@onReady()
@log 'debug', 'Zammad Chat: ready'
2015-11-10 14:01:04 +00:00
when 'offline'
@onError 'Zammad Chat: No agent online'
@state = 'off'
@hide()
@wsClose()
2015-11-10 14:01:04 +00:00
when 'chat_disabled'
@onError 'Zammad Chat: Chat is disabled'
@state = 'off'
@hide()
@wsClose()
2015-11-10 14:01:04 +00:00
when 'no_seats_available'
2015-11-25 09:35:57 +00:00
@onError "Zammad Chat: Too many clients in queue. Clients in queue: #{pipe.data.queue}"
@state = 'off'
@hide()
@wsClose()
when 'reconnect'
@log 'debug', 'old messages', pipe.data.session
2015-11-12 15:16:01 +00:00
@reopenSession pipe.data
onReady: =>
$(".#{ @options.buttonClass }").click(@open).removeClass(@inactiveClass)
2015-11-11 09:48:54 +00:00
if @options.show
@show()
onError: (message) =>
@log 'debug', message
$(".#{ @options.buttonClass }").hide()
2015-11-12 15:16:01 +00:00
reopenSession: (data) =>
2015-11-25 23:40:52 +00:00
@inactiveTimeoutStart()
2015-11-12 14:05:43 +00:00
unfinishedMessage = sessionStorage.getItem 'unfinished_message'
2015-11-12 15:16:01 +00:00
2015-11-13 14:15:44 +00:00
# rerender chat history
if data.agent
@onConnectionEstablished(data)
2015-11-12 15:16:01 +00:00
2015-11-13 14:15:44 +00:00
for message in data.session
@renderMessage
message: message.content
id: message.id
from: if message.created_by_id then 'agent' else 'customer'
2015-11-13 14:15:44 +00:00
if unfinishedMessage
@input.val unfinishedMessage
# show wait list
if data.position
@onQueue data
@show()
@open()
@scrollToBottom()
2015-11-12 14:05:43 +00:00
if unfinishedMessage
@input.focus()
2015-10-15 09:14:19 +00:00
onInput: =>
# remove unread-state from messages
@el.find('.zammad-chat-message--unread')
.removeClass 'zammad-chat-message--unread'
sessionStorage.setItem 'unfinished_message', @input.val()
2015-11-25 14:08:55 +00:00
@onTyping()
2015-10-15 09:14:19 +00:00
2015-11-25 14:08:55 +00:00
onTyping: ->
2015-10-15 09:14:19 +00:00
2015-11-25 14:08:55 +00:00
# send typing start event only every 1.5 seconds
return if @isTyping && @isTyping > new Date(new Date().getTime() - 1500)
@isTyping = new Date()
@send 'chat_session_typing',
session_id: @sessionId
2015-11-25 23:40:52 +00:00
@inactiveTimeoutStart()
2015-10-15 09:14:19 +00:00
onSubmit: (event) =>
event.preventDefault()
@sendMessage()
sendMessage: ->
message = @input.val()
return if !message
2015-10-15 09:14:19 +00:00
2015-11-25 23:40:52 +00:00
@inactiveTimeoutStart()
sessionStorage.removeItem 'unfinished_message'
messageElement = @view('message')
message: message
from: 'customer'
id: @_messageCount++
2015-11-26 09:52:10 +00:00
unreadClass: ''
2015-10-15 09:14:19 +00:00
@maybeAddTimestamp()
2015-10-15 09:14:19 +00:00
# add message before message typing loader
if @el.find('.zammad-chat-message--typing').size()
@lastAddedType = 'typing-placeholder'
2015-11-11 10:24:19 +00:00
@el.find('.zammad-chat-message--typing').before messageElement
else
@lastAddedType = 'message--customer'
@el.find('.zammad-chat-body').append messageElement
2015-10-15 09:14:19 +00:00
2015-11-12 14:05:43 +00:00
@input.val('')
@scrollToBottom()
2015-10-15 09:14:19 +00:00
# send message event
2015-11-10 14:01:04 +00:00
@send 'chat_session_message',
content: message
id: @_messageCount
2015-11-12 10:44:37 +00:00
session_id: @sessionId
receiveMessage: (data) =>
2015-11-25 23:40:52 +00:00
@inactiveTimeoutStart()
2015-10-15 09:14:19 +00:00
# hide writing indicator
@onAgentTypingEnd()
@maybeAddTimestamp()
@renderMessage
2015-11-10 14:01:04 +00:00
message: data.message.content
id: data.id
2015-10-15 09:26:56 +00:00
from: 'agent'
renderMessage: (data) =>
@lastAddedType = "message--#{ data.from }"
2015-11-26 09:52:10 +00:00
data.unreadClass = if document.hidden then ' zammad-chat-message--unread' else ''
@el.find('.zammad-chat-body').append @view('message')(data)
2015-10-15 09:14:19 +00:00
@scrollToBottom()
open: =>
if @isOpen
@show()
2015-10-15 09:14:19 +00:00
if !@sessionId
@showLoader()
2015-11-25 13:47:02 +00:00
@el.addClass('zammad-chat-is-open')
if !@sessionId
@el.animate { bottom: 0 }, 500, @onOpenAnimationEnd
else
@el.css 'bottom', 0
@onOpenAnimationEnd()
2015-10-15 09:14:19 +00:00
@isOpen = true
2015-11-11 10:44:10 +00:00
if !@sessionId
2015-11-25 23:40:52 +00:00
@sessionInit()
2015-10-15 09:14:19 +00:00
2015-11-25 23:40:52 +00:00
onOpenAnimationEnd: =>
@idleTimeoutStop()
2015-11-11 10:44:10 +00:00
close: (event) =>
return @state if @state is 'off' or @state is 'unsupported'
2015-11-11 10:44:10 +00:00
event.stopPropagation() if event
# only close if session_id exists
return if !@sessionId
2015-11-25 23:40:52 +00:00
# send close
@send 'chat_session_close',
session_id: @sessionId
# stop timer
@inactiveTimeoutStop()
# delete input store
sessionStorage.removeItem 'unfinished_message'
# stop delay of initial queue position
if @onInitialQueueDelayId
clearTimeout(@onInitialQueueDelayId)
2015-11-25 23:40:52 +00:00
if event
@closeWindow()
@setSessionId undefined
closeWindow: =>
2015-11-25 13:47:02 +00:00
@el.removeClass('zammad-chat-is-open')
2015-10-15 09:14:19 +00:00
remainerHeight = @el.height() - @el.find('.zammad-chat-header').outerHeight()
2015-10-15 13:28:30 +00:00
@el.animate { bottom: -remainerHeight }, 500, @onCloseAnimationEnd
2015-10-15 09:14:19 +00:00
onCloseAnimationEnd: =>
@el.removeClass('zammad-chat-is-visible')
2015-10-15 09:14:19 +00:00
@disconnect()
@isOpen = false
# restart connection
@onWebSocketOpen()
2015-10-15 09:14:19 +00:00
hide: ->
2015-11-25 13:47:02 +00:00
@el.removeClass('zammad-chat-is-shown')
2015-10-15 09:14:19 +00:00
show: ->
return @state if @state is 'off' or @state is 'unsupported'
2015-11-25 13:47:02 +00:00
@el.addClass('zammad-chat-is-shown')
2015-10-15 09:14:19 +00:00
if !@inputInitialized
@inputInitialized = true
@input.autoGrow
extraLine: false
remainerHeight = @el.height() - @el.find('.zammad-chat-header').outerHeight()
@el.css 'bottom', -remainerHeight
disableInput: ->
2015-11-12 14:05:43 +00:00
@input.prop('disabled', true)
@el.find('.zammad-chat-send').prop('disabled', true)
enableInput: ->
2015-11-12 14:05:43 +00:00
@input.prop('disabled', false)
@el.find('.zammad-chat-send').prop('disabled', false)
onQueueScreen: (data) =>
@setSessionId data.session_id
# delay initial queue position, show connecting first
show = =>
2015-11-12 14:21:04 +00:00
@onQueue data
if @initialQueueDelay && !@onInitialQueueDelayId
@onInitialQueueDelayId = setTimeout(show, @initialQueueDelay)
return
# stop delay of initial queue position
if @onInitialQueueDelayId
clearTimeout(@onInitialQueueDelayId)
# show queue position
show()
2015-11-12 14:20:07 +00:00
onQueue: (data) =>
@log 'notice', 'onQueue', data.position
@inQueue = true
@el.find('.zammad-chat-body').html @view('waiting')
position: data.position
2015-10-15 09:14:19 +00:00
onAgentTypingStart: =>
2015-11-11 10:24:19 +00:00
if @stopTypingId
clearTimeout(@stopTypingId)
@stopTypingId = setTimeout(@onAgentTypingEnd, 3000)
# never display two typing indicators
2015-10-15 09:14:19 +00:00
return if @el.find('.zammad-chat-message--typing').size()
@maybeAddTimestamp()
@el.find('.zammad-chat-body').append @view('typingIndicator')()
@scrollToBottom()
onAgentTypingEnd: =>
@el.find('.zammad-chat-message--typing').remove()
maybeAddTimestamp: ->
timestamp = Date.now()
2015-10-15 09:26:56 +00:00
if !@lastTimestamp or (timestamp - @lastTimestamp) > @showTimeEveryXMinutes * 60000
2015-10-15 09:14:19 +00:00
label = @T('Today')
time = new Date().toTimeString().substr 0,5
if @lastAddedType is 'timestamp'
# update last time
@updateLastTimestamp label, time
@lastTimestamp = timestamp
else
# add new timestamp
@el.find('.zammad-chat-body').append @view('timestamp')
label: label
time: time
2015-10-15 09:14:19 +00:00
@lastTimestamp = timestamp
@lastAddedType = 'timestamp'
@scrollToBottom()
2015-10-15 09:14:19 +00:00
updateLastTimestamp: (label, time) ->
@el.find('.zammad-chat-body')
.find('.zammad-chat-timestamp')
2015-10-15 09:14:19 +00:00
.last()
.replaceWith @view('timestamp')
2015-10-15 09:14:19 +00:00
label: label
time: time
addStatus: (status) ->
@maybeAddTimestamp()
2015-10-15 09:26:56 +00:00
@el.find('.zammad-chat-body').append @view('status')
status: status
@scrollToBottom()
2015-10-15 09:14:19 +00:00
scrollToBottom: ->
@el.find('.zammad-chat-body').scrollTop($('.zammad-chat-body').prop('scrollHeight'))
2015-11-25 23:40:52 +00:00
sessionInit: ->
2015-11-10 14:01:04 +00:00
@send('chat_session_init')
2015-10-15 09:14:19 +00:00
detectHost: ->
2015-11-25 09:35:57 +00:00
protocol = 'ws://'
if window.location.protocol is 'https:'
protocol = 'wss://'
@options.host = "#{ protocol }#{ scriptHost }/ws"
wsConnect: =>
@detectHost() if !@options.host
2015-11-25 12:18:56 +00:00
@log 'debug', "Connecting to #{@options.host}"
2015-11-25 09:35:57 +00:00
@ws = new window.WebSocket("#{@options.host}")
@ws.onopen = @onWebSocketOpen
@ws.onmessage = @onWebSocketMessage
@ws.onclose = (e) =>
@log 'debug', 'close websocket connection'
if @wsReconnectEnable
@reconnect()
@ws.onerror = (e) =>
@log 'debug', 'ws:onerror', e
wsClose: =>
@wsReconnectEnable = false
@ws.close()
wsReconnect: =>
if @reconnectDelayId
clearTimeout(@reconnectDelayId)
@reconnectDelayId = setTimeout(@wsConnect, 5000)
onWebSocketOpen: =>
2015-11-25 23:40:52 +00:00
@idleTimeoutStart()
@sessionId = sessionStorage.getItem('sessionId')
@log 'debug', 'ws connected'
@send 'chat_status_customer',
session_id: @sessionId
@setAgentOnlineState 'online'
2015-10-15 09:14:19 +00:00
reconnect: =>
# set status to connecting
@log 'notice', 'reconnecting'
@disableInput()
2015-10-15 09:14:19 +00:00
@lastAddedType = 'status'
@setAgentOnlineState 'connecting'
2015-10-15 09:14:19 +00:00
@addStatus @T('Connection lost')
@wsReconnect()
2015-10-15 09:14:19 +00:00
onConnectionReestablished: =>
# set status back to online
@lastAddedType = 'status'
@setAgentOnlineState 'online'
2015-10-15 09:14:19 +00:00
@addStatus @T('Connection re-established')
onSessionClosed: (data) ->
@addStatus @T('Chat closed by %s', data.realname)
@disableInput()
2015-11-25 09:35:57 +00:00
@setAgentOnlineState 'offline'
2015-11-25 23:40:52 +00:00
@inactiveTimeoutStop()
2015-10-15 09:14:19 +00:00
disconnect: ->
@showLoader()
@el.find('.zammad-chat-welcome').removeClass('zammad-chat-is-hidden')
@el.find('.zammad-chat-agent').addClass('zammad-chat-is-hidden')
@el.find('.zammad-chat-agent-status').addClass('zammad-chat-is-hidden')
2015-11-12 14:05:43 +00:00
setSessionId: (id) =>
@sessionId = id
if id is undefined
sessionStorage.removeItem 'sessionId'
else
sessionStorage.setItem 'sessionId', id
2015-11-12 14:05:43 +00:00
onConnectionEstablished: (data) =>
# stop delay of initial queue position
if @onInitialQueueDelayId
2015-11-12 14:05:43 +00:00
clearTimeout @onInitialQueueDelayId
@inQueue = false
2015-11-12 15:16:01 +00:00
if data.agent
@agent = data.agent
if data.session_id
@setSessionId data.session_id
@el.find('.zammad-chat-agent').html @view('agent')
agent: @agent
@enableInput()
@el.find('.zammad-chat-body').empty()
@el.find('.zammad-chat-welcome').addClass('zammad-chat-is-hidden')
@el.find('.zammad-chat-agent').removeClass('zammad-chat-is-hidden')
@el.find('.zammad-chat-agent-status').removeClass('zammad-chat-is-hidden')
2015-11-12 14:05:43 +00:00
@input.focus()
2015-11-25 09:35:57 +00:00
@setAgentOnlineState 'online'
showTimeout: ->
@el.find('.zammad-chat-body').html @view('timeout')
agent: @agent.name
2015-11-25 23:40:52 +00:00
delay: @options.inactiveTimeout
@close()
reload = ->
location.reload()
@el.find('.js-restart').click reload
showLoader: ->
@el.find('.zammad-chat-body').html @view('loader')()
2015-10-15 09:14:19 +00:00
setAgentOnlineState: (state) =>
@state = state
capitalizedState = state.charAt(0).toUpperCase() + state.slice(1)
2015-10-15 09:14:19 +00:00
@el
.find('.zammad-chat-agent-status')
.attr('data-status', state)
.text @T(capitalizedState)
2015-10-15 09:14:19 +00:00
loadCss: ->
return if !@options.cssAutoload
url = @options.cssUrl
if !url
url = @options.host
.replace(/^wss/i, 'https')
.replace(/^ws/i, 'http')
.replace(/\/ws/i, '')
url += '/assets/chat/chat.css'
@log 'debug', "load css from '#{url}'"
styles = "@import url('#{url}');"
newSS = document.createElement('link')
newSS.rel = 'stylesheet'
newSS.href = 'data:text/css,' + escape(styles)
document.getElementsByTagName('head')[0].appendChild(newSS)
2015-11-25 23:40:52 +00:00
inactiveTimeoutStart: =>
@inactiveTimeoutStop()
delay = =>
2015-12-01 18:44:31 +00:00
@log 'debug', "Inactive timeout of #{@options.inactiveTimeout} minutes, show timeout screen.", new Date
2015-11-25 23:40:52 +00:00
@state = 'off'
@setAgentOnlineState 'offline'
@showTimeout()
@wsClose()
2015-12-01 18:44:31 +00:00
@log 'debug', "Start inactive timeout in #{@options.inactiveTimeout} minutes", new Date
2015-11-25 23:40:52 +00:00
@inactiveTimeoutStopDelayId = setTimeout(delay, @options.inactiveTimeout * 1000 * 60)
inactiveTimeoutStop: =>
return if !@inactiveTimeoutStopDelayId
2015-12-01 18:44:31 +00:00
@log 'debug', "Stop inactive timeout of #{@options.inactiveTimeout} minutes at", new Date
2015-11-25 23:40:52 +00:00
clearTimeout(@inactiveTimeoutStopDelayId)
idleTimeoutStart: =>
@idleTimeoutStop()
delay = =>
2015-12-01 18:44:31 +00:00
@log 'debug', "Idle timeout of #{@options.idleTimeout} minutes, hide widget", new Date
2015-11-25 23:40:52 +00:00
@state = 'off'
@hide()
@wsClose()
2015-12-01 18:44:31 +00:00
@log 'debug', "Start idle timeout in #{@options.idleTimeout} minutes", new Date
2015-11-25 23:40:52 +00:00
@idleTimeoutStopDelayId = setTimeout(delay, @options.idleTimeout * 1000 * 60)
idleTimeoutStop: =>
return if !@idleTimeoutStopDelayId
2015-12-01 18:44:31 +00:00
@log 'debug', "Stop idle timeout of #{@options.idleTimeout} minutes at", new Date
2015-11-25 23:40:52 +00:00
clearTimeout(@idleTimeoutStopDelayId)
window.ZammadChat = ZammadChat