chat.coffee 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. do($ = window.jQuery, window) ->
  2. scripts = document.getElementsByTagName('script')
  3. myScript = scripts[scripts.length - 1]
  4. scriptHost = myScript.src.match('.*://([^:/]*).*')[1]
  5. # Define the plugin class
  6. class Base
  7. defaults:
  8. debug: false
  9. constructor: (options) ->
  10. @options = $.extend {}, @defaults, options
  11. @log = new Log(debug: @options.debug, logPrefix: @options.logPrefix || @logPrefix)
  12. class Log
  13. defaults:
  14. debug: false
  15. constructor: (options) ->
  16. @options = $.extend {}, @defaults, options
  17. debug: (items...) =>
  18. return if !@options.debug
  19. @log('debug', items)
  20. notice: (items...) =>
  21. @log('notice', items)
  22. error: (items...) =>
  23. @log('error', items)
  24. log: (level, items) =>
  25. items.unshift('||')
  26. items.unshift(level)
  27. items.unshift(@options.logPrefix)
  28. console.log.apply console, items
  29. return if !@options.debug
  30. logString = ''
  31. for item in items
  32. logString += ' '
  33. if typeof item is 'object'
  34. logString += JSON.stringify(item)
  35. else if item && item.toString
  36. logString += item.toString()
  37. else
  38. logString += item
  39. $('.js-chatLogDisplay').prepend('<div>' + logString + '</div>')
  40. class Timeout extends Base
  41. timeoutStartedAt: null
  42. logPrefix: 'timeout'
  43. defaults:
  44. debug: false
  45. timeout: 4
  46. timeoutIntervallCheck: 0.5
  47. constructor: (options) ->
  48. super(options)
  49. start: =>
  50. @stop()
  51. timeoutStartedAt = new Date
  52. check = =>
  53. timeLeft = new Date - new Date(timeoutStartedAt.getTime() + @options.timeout * 1000 * 60)
  54. @log.debug "Timeout check for #{@options.timeout} minutes (left #{timeLeft/1000} sec.)"#, new Date
  55. return if timeLeft < 0
  56. @stop()
  57. @options.callback()
  58. @log.debug "Start timeout in #{@options.timeout} minutes"#, new Date
  59. @intervallId = setInterval(check, @options.timeoutIntervallCheck * 1000 * 60)
  60. stop: =>
  61. return if !@intervallId
  62. @log.debug "Stop timeout of #{@options.timeout} minutes"#, new Date
  63. clearInterval(@intervallId)
  64. class Io extends Base
  65. logPrefix: 'io'
  66. constructor: (options) ->
  67. super(options)
  68. set: (params) =>
  69. for key, value of params
  70. @options[key] = value
  71. connect: =>
  72. @log.debug "Connecting to #{@options.host}"
  73. @ws = new window.WebSocket("#{@options.host}")
  74. @ws.onopen = (e) =>
  75. @log.debug 'onOpen', e
  76. @options.onOpen(e)
  77. @ping()
  78. @ws.onmessage = (e) =>
  79. pipes = JSON.parse(e.data)
  80. @log.debug 'onMessage', e.data
  81. for pipe in pipes
  82. if pipe.event is 'pong'
  83. @ping()
  84. if @options.onMessage
  85. @options.onMessage(pipes)
  86. @ws.onclose = (e) =>
  87. @log.debug 'close websocket connection', e
  88. if @pingDelayId
  89. clearTimeout(@pingDelayId)
  90. if @manualClose
  91. @log.debug 'manual close, onClose callback'
  92. @manualClose = false
  93. if @options.onClose
  94. @options.onClose(e)
  95. else
  96. @log.debug 'error close, onError callback'
  97. if @options.onError
  98. @options.onError('Connection lost...')
  99. @ws.onerror = (e) =>
  100. @log.debug 'onError', e
  101. if @options.onError
  102. @options.onError(e)
  103. close: =>
  104. @log.debug 'close websocket manually'
  105. @manualClose = true
  106. @ws.close()
  107. reconnect: =>
  108. @log.debug 'reconnect'
  109. @close()
  110. @connect()
  111. send: (event, data = {}) =>
  112. @log.debug 'send', event, data
  113. msg = JSON.stringify
  114. event: event
  115. data: data
  116. @ws.send msg
  117. ping: =>
  118. localPing = =>
  119. @send('ping')
  120. @pingDelayId = setTimeout(localPing, 29000)
  121. class ZammadChat extends Base
  122. defaults:
  123. chatId: undefined
  124. show: true
  125. target: $('body')
  126. host: ''
  127. debug: false
  128. flat: false
  129. lang: undefined
  130. cssAutoload: true
  131. cssUrl: undefined
  132. fontSize: undefined
  133. buttonClass: 'open-zammad-chat'
  134. inactiveClass: 'is-inactive'
  135. title: '<strong>Chat</strong> with us!'
  136. idleTimeout: 6
  137. idleTimeoutIntervallCheck: 0.5
  138. inactiveTimeout: 8
  139. inactiveTimeoutIntervallCheck: 0.5
  140. waitingListTimeout: 4
  141. waitingListTimeoutIntervallCheck: 0.5
  142. logPrefix: 'chat'
  143. _messageCount: 0
  144. isOpen: false
  145. blinkOnlineInterval: null
  146. stopBlinOnlineStateTimeout: null
  147. showTimeEveryXMinutes: 2
  148. lastTimestamp: null
  149. lastAddedType: null
  150. inputTimeout: null
  151. isTyping: false
  152. state: 'offline'
  153. initialQueueDelay: 10000
  154. translations:
  155. de:
  156. '<strong>Chat</strong> with us!': '<strong>Chatte</strong> mit uns!'
  157. 'Online': 'Online'
  158. 'Online': 'Online'
  159. 'Offline': 'Offline'
  160. 'Connecting': 'Verbinden'
  161. 'Connection re-established': 'Verbindung wiederhergestellt'
  162. 'Today': 'Heute'
  163. 'Send': 'Senden'
  164. 'Compose your message...': 'Ihre Nachricht...'
  165. 'All colleagues are busy.': 'Alle Kollegen sind belegt.'
  166. 'You are on waiting list position <strong>%s</strong>.': 'Sie sind in der Warteliste an der Position <strong>%s</strong>.'
  167. 'Start new conversation': 'Neue Konversation starten'
  168. '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.'
  169. '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.'
  170. sessionId: undefined
  171. T: (string, items...) =>
  172. if @options.lang && @options.lang isnt 'en'
  173. if !@translations[@options.lang]
  174. @log.notice "Translation '#{@options.lang}' needed!"
  175. else
  176. translations = @translations[@options.lang]
  177. if !translations[string]
  178. @log.notice "Translation needed for '#{string}'"
  179. string = translations[string] || string
  180. if items
  181. for item in items
  182. string = string.replace(/%s/, item)
  183. string
  184. view: (name) =>
  185. return (options) =>
  186. if !options
  187. options = {}
  188. options.T = @T
  189. options.background = @options.background
  190. options.flat = @options.flat
  191. options.fontSize = @options.fontSize
  192. return window.zammadChatTemplates[name](options)
  193. constructor: (options) ->
  194. @options = $.extend {}, @defaults, options
  195. super(@options)
  196. # fullscreen
  197. @isFullscreen = (window.matchMedia and window.matchMedia('(max-width: 768px)').matches)
  198. @scrollRoot = $(@getScrollRoot())
  199. # check prerequisites
  200. if !$
  201. @state = 'unsupported'
  202. @log.notice 'Chat: no jquery found!'
  203. return
  204. if !window.WebSocket or !sessionStorage
  205. @state = 'unsupported'
  206. @log.notice 'Chat: Browser not supported!'
  207. return
  208. if !@options.chatId
  209. @state = 'unsupported'
  210. @log.error 'Chat: need chatId as option!'
  211. return
  212. # detect language
  213. if !@options.lang
  214. @options.lang = $('html').attr('lang')
  215. if @options.lang
  216. @options.lang = @options.lang.replace(/-.+?$/, '') # replace "-xx" of xx-xx
  217. @log.debug "lang: #{@options.lang}"
  218. # detect host
  219. @detectHost() if !@options.host
  220. @loadCss()
  221. @io = new Io(@options)
  222. @io.set(
  223. onOpen: @render
  224. onClose: @onWebSocketClose
  225. onMessage: @onWebSocketMessage
  226. onError: @onError
  227. )
  228. @io.connect()
  229. getScrollRoot: ->
  230. return document.scrollingElement if 'scrollingElement' of document
  231. html = document.documentElement
  232. start = html.scrollTop
  233. html.scrollTop = start + 1
  234. end = html.scrollTop
  235. html.scrollTop = start
  236. return if end > start then html else document.body
  237. render: =>
  238. if !@el || !$('.zammad-chat').get(0)
  239. @renderBase()
  240. # disable open button
  241. $(".#{ @options.buttonClass }").addClass @inactiveClass
  242. @setAgentOnlineState 'online'
  243. @log.debug 'widget rendered'
  244. @startTimeoutObservers()
  245. @idleTimeout.start()
  246. # get current chat status
  247. @sessionId = sessionStorage.getItem('sessionId')
  248. @send 'chat_status_customer',
  249. session_id: @sessionId
  250. url: window.location.href
  251. renderBase: ->
  252. @el = $(@view('chat')(
  253. title: @options.title
  254. ))
  255. @options.target.append @el
  256. @input = @el.find('.zammad-chat-input')
  257. # start bindings
  258. @el.find('.js-chat-open').click @open
  259. @el.find('.js-chat-toggle').click @toggle
  260. @el.find('.zammad-chat-controls').on 'submit', @onSubmit
  261. @input.on
  262. keydown: @checkForEnter
  263. input: @onInput
  264. $(window).on('beforeunload', =>
  265. @onLeaveTemporary()
  266. )
  267. $(window).bind('hashchange', =>
  268. if @isOpen
  269. if @sessionId
  270. @send 'chat_session_notice',
  271. session_id: @sessionId
  272. message: window.location.href
  273. return
  274. @idleTimeout.start()
  275. )
  276. if @isFullscreen
  277. @input.on
  278. focus: @onFocus
  279. focusout: @onFocusOut
  280. checkForEnter: (event) =>
  281. if not event.shiftKey and event.keyCode is 13
  282. event.preventDefault()
  283. @sendMessage()
  284. send: (event, data = {}) =>
  285. data.chat_id = @options.chatId
  286. @io.send(event, data)
  287. onWebSocketMessage: (pipes) =>
  288. for pipe in pipes
  289. @log.debug 'ws:onmessage', pipe
  290. switch pipe.event
  291. when 'chat_error'
  292. @log.notice pipe.data
  293. if pipe.data && pipe.data.state is 'chat_disabled'
  294. @destroy(remove: true)
  295. when 'chat_session_message'
  296. return if pipe.data.self_written
  297. @receiveMessage pipe.data
  298. when 'chat_session_typing'
  299. return if pipe.data.self_written
  300. @onAgentTypingStart()
  301. when 'chat_session_start'
  302. @onConnectionEstablished pipe.data
  303. when 'chat_session_queue'
  304. @onQueueScreen pipe.data
  305. when 'chat_session_closed'
  306. @onSessionClosed pipe.data
  307. when 'chat_session_left'
  308. @onSessionClosed pipe.data
  309. when 'chat_status_customer'
  310. switch pipe.data.state
  311. when 'online'
  312. @sessionId = undefined
  313. if !@options.cssAutoload || @cssLoaded
  314. @onReady()
  315. else
  316. @socketReady = true
  317. when 'offline'
  318. @onError 'Zammad Chat: No agent online'
  319. when 'chat_disabled'
  320. @onError 'Zammad Chat: Chat is disabled'
  321. when 'no_seats_available'
  322. @onError "Zammad Chat: Too many clients in queue. Clients in queue: #{pipe.data.queue}"
  323. when 'reconnect'
  324. @onReopenSession pipe.data
  325. onReady: ->
  326. @log.debug 'widget ready for use'
  327. $(".#{ @options.buttonClass }").click(@open).removeClass(@inactiveClass)
  328. if @options.show
  329. @show()
  330. onError: (message) =>
  331. @log.debug message
  332. @addStatus(message)
  333. $(".#{ @options.buttonClass }").hide()
  334. if @isOpen
  335. @disableInput()
  336. @destroy(remove: false)
  337. else
  338. @destroy(remove: true)
  339. onReopenSession: (data) =>
  340. @log.debug 'old messages', data.session
  341. @inactiveTimeout.start()
  342. unfinishedMessage = sessionStorage.getItem 'unfinished_message'
  343. # rerender chat history
  344. if data.agent
  345. @onConnectionEstablished(data)
  346. for message in data.session
  347. @renderMessage
  348. message: message.content
  349. id: message.id
  350. from: if message.created_by_id then 'agent' else 'customer'
  351. if unfinishedMessage
  352. @input.val unfinishedMessage
  353. # show wait list
  354. if data.position
  355. @onQueue data
  356. @show()
  357. @open()
  358. @scrollToBottom()
  359. if unfinishedMessage
  360. @input.focus()
  361. onInput: =>
  362. # remove unread-state from messages
  363. @el.find('.zammad-chat-message--unread')
  364. .removeClass 'zammad-chat-message--unread'
  365. sessionStorage.setItem 'unfinished_message', @input.val()
  366. @onTyping()
  367. onFocus: =>
  368. $(window).scrollTop(10)
  369. keyboardShown = $(window).scrollTop() > 0
  370. $(window).scrollTop(0)
  371. if keyboardShown
  372. @log.notice 'virtual keyboard shown'
  373. # on keyboard shown
  374. # can't measure visible area height :(
  375. onFocusOut: ->
  376. # on keyboard hidden
  377. onTyping: ->
  378. # send typing start event only every 1.5 seconds
  379. return if @isTyping && @isTyping > new Date(new Date().getTime() - 1500)
  380. @isTyping = new Date()
  381. @send 'chat_session_typing',
  382. session_id: @sessionId
  383. @inactiveTimeout.start()
  384. onSubmit: (event) =>
  385. event.preventDefault()
  386. @sendMessage()
  387. sendMessage: ->
  388. message = @input.val()
  389. return if !message
  390. @inactiveTimeout.start()
  391. sessionStorage.removeItem 'unfinished_message'
  392. messageElement = @view('message')
  393. message: message
  394. from: 'customer'
  395. id: @_messageCount++
  396. unreadClass: ''
  397. @maybeAddTimestamp()
  398. # add message before message typing loader
  399. if @el.find('.zammad-chat-message--typing').size()
  400. @lastAddedType = 'typing-placeholder'
  401. @el.find('.zammad-chat-message--typing').before messageElement
  402. else
  403. @lastAddedType = 'message--customer'
  404. @el.find('.zammad-chat-body').append messageElement
  405. @input.val('')
  406. @scrollToBottom()
  407. # send message event
  408. @send 'chat_session_message',
  409. content: message
  410. id: @_messageCount
  411. session_id: @sessionId
  412. receiveMessage: (data) =>
  413. @inactiveTimeout.start()
  414. # hide writing indicator
  415. @onAgentTypingEnd()
  416. @maybeAddTimestamp()
  417. @renderMessage
  418. message: data.message.content
  419. id: data.id
  420. from: 'agent'
  421. renderMessage: (data) =>
  422. @lastAddedType = "message--#{ data.from }"
  423. data.unreadClass = if document.hidden then ' zammad-chat-message--unread' else ''
  424. @el.find('.zammad-chat-body').append @view('message')(data)
  425. @scrollToBottom()
  426. open: =>
  427. if @isOpen
  428. @log.debug 'widget already open, block'
  429. return
  430. @isOpen = true
  431. @log.debug 'open widget'
  432. if !@sessionId
  433. @showLoader()
  434. @el.addClass('zammad-chat-is-open')
  435. if !@inputInitialized
  436. @inputInitialized = true
  437. @input.autoGrow
  438. extraLine: false
  439. remainerHeight = @el.height() - @el.find('.zammad-chat-header').outerHeight()
  440. @el.css 'bottom', -remainerHeight
  441. if !@sessionId
  442. @el.animate { bottom: 0 }, 500, @onOpenAnimationEnd
  443. @send('chat_session_init'
  444. url: window.location.href
  445. )
  446. else
  447. @el.css 'bottom', 0
  448. @onOpenAnimationEnd()
  449. onOpenAnimationEnd: =>
  450. @idleTimeout.stop()
  451. if @isFullscreen
  452. @disableScrollOnRoot()
  453. sessionClose: =>
  454. # send close
  455. @send 'chat_session_close',
  456. session_id: @sessionId
  457. # stop timer
  458. @inactiveTimeout.stop()
  459. @waitingListTimeout.stop()
  460. # delete input store
  461. sessionStorage.removeItem 'unfinished_message'
  462. # stop delay of initial queue position
  463. if @onInitialQueueDelayId
  464. clearTimeout(@onInitialQueueDelayId)
  465. @setSessionId undefined
  466. toggle: (event) =>
  467. if @isOpen
  468. @close(event)
  469. else
  470. @open(event)
  471. close: (event) =>
  472. if !@isOpen
  473. @log.debug 'can\'t close widget, it\'s not open'
  474. return
  475. if @initDelayId
  476. clearTimeout(@initDelayId)
  477. if !@sessionId
  478. @log.debug 'can\'t close widget without sessionId'
  479. return
  480. @log.debug 'close widget'
  481. event.stopPropagation() if event
  482. @sessionClose()
  483. if @isFullscreen
  484. @enableScrollOnRoot()
  485. # close window
  486. remainerHeight = @el.height() - @el.find('.zammad-chat-header').outerHeight()
  487. @el.animate { bottom: -remainerHeight }, 500, @onCloseAnimationEnd
  488. onCloseAnimationEnd: =>
  489. @el.css 'bottom', ''
  490. @el.removeClass('zammad-chat-is-open')
  491. @showLoader()
  492. @el.find('.zammad-chat-welcome').removeClass('zammad-chat-is-hidden')
  493. @el.find('.zammad-chat-agent').addClass('zammad-chat-is-hidden')
  494. @el.find('.zammad-chat-agent-status').addClass('zammad-chat-is-hidden')
  495. @isOpen = false
  496. @io.reconnect()
  497. onWebSocketClose: =>
  498. return if @isOpen
  499. if @el
  500. @el.removeClass('zammad-chat-is-shown')
  501. @el.removeClass('zammad-chat-is-loaded')
  502. show: ->
  503. return if @state is 'offline'
  504. @el.addClass('zammad-chat-is-loaded')
  505. @el.addClass('zammad-chat-is-shown')
  506. disableInput: ->
  507. @input.prop('disabled', true)
  508. @el.find('.zammad-chat-send').prop('disabled', true)
  509. enableInput: ->
  510. @input.prop('disabled', false)
  511. @el.find('.zammad-chat-send').prop('disabled', false)
  512. hideModal: ->
  513. @el.find('.zammad-chat-modal').html ''
  514. onQueueScreen: (data) =>
  515. @setSessionId data.session_id
  516. # delay initial queue position, show connecting first
  517. show = =>
  518. @onQueue data
  519. @waitingListTimeout.start()
  520. if @initialQueueDelay && !@onInitialQueueDelayId
  521. @onInitialQueueDelayId = setTimeout(show, @initialQueueDelay)
  522. return
  523. # stop delay of initial queue position
  524. if @onInitialQueueDelayId
  525. clearTimeout(@onInitialQueueDelayId)
  526. # show queue position
  527. show()
  528. onQueue: (data) =>
  529. @log.notice 'onQueue', data.position
  530. @inQueue = true
  531. @el.find('.zammad-chat-modal').html @view('waiting')
  532. position: data.position
  533. onAgentTypingStart: =>
  534. if @stopTypingId
  535. clearTimeout(@stopTypingId)
  536. @stopTypingId = setTimeout(@onAgentTypingEnd, 3000)
  537. # never display two typing indicators
  538. return if @el.find('.zammad-chat-message--typing').size()
  539. @maybeAddTimestamp()
  540. @el.find('.zammad-chat-body').append @view('typingIndicator')()
  541. # only if typing indicator is shown
  542. return if !@isVisible(@el.find('.zammad-chat-message--typing'), true)
  543. @scrollToBottom()
  544. onAgentTypingEnd: =>
  545. @el.find('.zammad-chat-message--typing').remove()
  546. onLeaveTemporary: =>
  547. return if !@sessionId
  548. @send 'chat_session_leave_temporary',
  549. session_id: @sessionId
  550. maybeAddTimestamp: ->
  551. timestamp = Date.now()
  552. if !@lastTimestamp or (timestamp - @lastTimestamp) > @showTimeEveryXMinutes * 60000
  553. label = @T('Today')
  554. time = new Date().toTimeString().substr 0,5
  555. if @lastAddedType is 'timestamp'
  556. # update last time
  557. @updateLastTimestamp label, time
  558. @lastTimestamp = timestamp
  559. else
  560. # add new timestamp
  561. @el.find('.zammad-chat-body').append @view('timestamp')
  562. label: label
  563. time: time
  564. @lastTimestamp = timestamp
  565. @lastAddedType = 'timestamp'
  566. @scrollToBottom()
  567. updateLastTimestamp: (label, time) ->
  568. return if !@el
  569. @el.find('.zammad-chat-body')
  570. .find('.zammad-chat-timestamp')
  571. .last()
  572. .replaceWith @view('timestamp')
  573. label: label
  574. time: time
  575. addStatus: (status) ->
  576. return if !@el
  577. @maybeAddTimestamp()
  578. @el.find('.zammad-chat-body').append @view('status')
  579. status: status
  580. @scrollToBottom()
  581. scrollToBottom: ->
  582. @el.find('.zammad-chat-body').scrollTop($('.zammad-chat-body').prop('scrollHeight'))
  583. destroy: (params = {}) =>
  584. @log.debug 'destroy widget', params
  585. @setAgentOnlineState 'offline'
  586. if params.remove && @el
  587. @el.remove()
  588. # stop all timer
  589. if @waitingListTimeout
  590. @waitingListTimeout.stop()
  591. if @inactiveTimeout
  592. @inactiveTimeout.stop()
  593. if @idleTimeout
  594. @idleTimeout.stop()
  595. # stop ws connection
  596. @io.close()
  597. reconnect: =>
  598. # set status to connecting
  599. @log.notice 'reconnecting'
  600. @disableInput()
  601. @lastAddedType = 'status'
  602. @setAgentOnlineState 'connecting'
  603. @addStatus @T('Connection lost')
  604. onConnectionReestablished: =>
  605. # set status back to online
  606. @lastAddedType = 'status'
  607. @setAgentOnlineState 'online'
  608. @addStatus @T('Connection re-established')
  609. onSessionClosed: (data) ->
  610. @addStatus @T('Chat closed by %s', data.realname)
  611. @disableInput()
  612. @setAgentOnlineState 'offline'
  613. @inactiveTimeout.stop()
  614. setSessionId: (id) =>
  615. @sessionId = id
  616. if id is undefined
  617. sessionStorage.removeItem 'sessionId'
  618. else
  619. sessionStorage.setItem 'sessionId', id
  620. onConnectionEstablished: (data) =>
  621. # stop delay of initial queue position
  622. if @onInitialQueueDelayId
  623. clearTimeout @onInitialQueueDelayId
  624. @inQueue = false
  625. if data.agent
  626. @agent = data.agent
  627. if data.session_id
  628. @setSessionId data.session_id
  629. # empty old messages
  630. @el.find('.zammad-chat-body').html('')
  631. @el.find('.zammad-chat-agent').html @view('agent')
  632. agent: @agent
  633. @enableInput()
  634. @hideModal()
  635. @el.find('.zammad-chat-welcome').addClass('zammad-chat-is-hidden')
  636. @el.find('.zammad-chat-agent').removeClass('zammad-chat-is-hidden')
  637. @el.find('.zammad-chat-agent-status').removeClass('zammad-chat-is-hidden')
  638. @input.focus() if not @isFullscreen
  639. @setAgentOnlineState 'online'
  640. @waitingListTimeout.stop()
  641. @idleTimeout.stop()
  642. @inactiveTimeout.start()
  643. showCustomerTimeout: ->
  644. @el.find('.zammad-chat-modal').html @view('customer_timeout')
  645. agent: @agent.name
  646. delay: @options.inactiveTimeout
  647. reload = ->
  648. location.reload()
  649. @el.find('.js-restart').click reload
  650. @sessionClose()
  651. showWaitingListTimeout: ->
  652. @el.find('.zammad-chat-modal').html @view('waiting_list_timeout')
  653. delay: @options.watingListTimeout
  654. reload = ->
  655. location.reload()
  656. @el.find('.js-restart').click reload
  657. @sessionClose()
  658. showLoader: ->
  659. @el.find('.zammad-chat-modal').html @view('loader')()
  660. setAgentOnlineState: (state) =>
  661. @state = state
  662. return if !@el
  663. capitalizedState = state.charAt(0).toUpperCase() + state.slice(1)
  664. @el
  665. .find('.zammad-chat-agent-status')
  666. .attr('data-status', state)
  667. .text @T(capitalizedState)
  668. detectHost: ->
  669. protocol = 'ws://'
  670. if window.location.protocol is 'https:'
  671. protocol = 'wss://'
  672. @options.host = "#{ protocol }#{ scriptHost }/ws"
  673. loadCss: ->
  674. return if !@options.cssAutoload
  675. url = @options.cssUrl
  676. if !url
  677. url = @options.host
  678. .replace(/^wss/i, 'https')
  679. .replace(/^ws/i, 'http')
  680. .replace(/\/ws/i, '')
  681. url += '/assets/chat/chat.css'
  682. @log.debug "load css from '#{url}'"
  683. styles = "@import url('#{url}');"
  684. newSS = document.createElement('link')
  685. newSS.onload = @onCssLoaded
  686. newSS.rel = 'stylesheet'
  687. newSS.href = 'data:text/css,' + escape(styles)
  688. document.getElementsByTagName('head')[0].appendChild(newSS)
  689. onCssLoaded: =>
  690. if @socketReady
  691. @onReady()
  692. else
  693. @cssLoaded = true
  694. startTimeoutObservers: =>
  695. @idleTimeout = new Timeout(
  696. logPrefix: 'idleTimeout'
  697. debug: @options.debug
  698. timeout: @options.idleTimeout
  699. timeoutIntervallCheck: @options.idleTimeoutIntervallCheck
  700. callback: =>
  701. @log.debug 'Idle timeout reached, hide widget', new Date
  702. @destroy(remove: true)
  703. )
  704. @inactiveTimeout = new Timeout(
  705. logPrefix: 'inactiveTimeout'
  706. debug: @options.debug
  707. timeout: @options.inactiveTimeout
  708. timeoutIntervallCheck: @options.inactiveTimeoutIntervallCheck
  709. callback: =>
  710. @log.debug 'Inactive timeout reached, show timeout screen.', new Date
  711. @showCustomerTimeout()
  712. @destroy(remove: false)
  713. )
  714. @waitingListTimeout = new Timeout(
  715. logPrefix: 'waitingListTimeout'
  716. debug: @options.debug
  717. timeout: @options.waitingListTimeout
  718. timeoutIntervallCheck: @options.waitingListTimeoutIntervallCheck
  719. callback: =>
  720. @log.debug 'Waiting list timeout reached, show timeout screen.', new Date
  721. @showWaitingListTimeout()
  722. @destroy(remove: false)
  723. )
  724. disableScrollOnRoot: ->
  725. @rootScrollOffset = @scrollRoot.scrollTop()
  726. @scrollRoot.css
  727. overflow: 'hidden'
  728. position: 'fixed'
  729. enableScrollOnRoot: ->
  730. @scrollRoot.scrollTop @rootScrollOffset
  731. @scrollRoot.css
  732. overflow: ''
  733. position: ''
  734. # based on https://github.com/customd/jquery-visible/blob/master/jquery.visible.js
  735. # to have not dependency, port to coffeescript
  736. isVisible: (el, partial, hidden, direction) ->
  737. return if el.length < 1
  738. $w = $(window)
  739. $t = if el.length > 1 then el.eq(0) else el
  740. t = $t.get(0)
  741. vpWidth = $w.width()
  742. vpHeight = $w.height()
  743. direction = if direction then direction else 'both'
  744. clientSize = if hidden is true then t.offsetWidth * t.offsetHeight else true
  745. if typeof t.getBoundingClientRect is 'function'
  746. # Use this native browser method, if available.
  747. rec = t.getBoundingClientRect()
  748. tViz = rec.top >= 0 && rec.top < vpHeight
  749. bViz = rec.bottom > 0 && rec.bottom <= vpHeight
  750. lViz = rec.left >= 0 && rec.left < vpWidth
  751. rViz = rec.right > 0 && rec.right <= vpWidth
  752. vVisible = if partial then tViz || bViz else tViz && bViz
  753. hVisible = if partial then lViz || rViz else lViz && rViz
  754. if direction is 'both'
  755. return clientSize && vVisible && hVisible
  756. else if direction is 'vertical'
  757. return clientSize && vVisible
  758. else if direction is 'horizontal'
  759. return clientSize && hVisible
  760. else
  761. viewTop = $w.scrollTop()
  762. viewBottom = viewTop + vpHeight
  763. viewLeft = $w.scrollLeft()
  764. viewRight = viewLeft + vpWidth
  765. offset = $t.offset()
  766. _top = offset.top
  767. _bottom = _top + $t.height()
  768. _left = offset.left
  769. _right = _left + $t.width()
  770. compareTop = if partial is true then _bottom else _top
  771. compareBottom = if partial is true then _top else _bottom
  772. compareLeft = if partial is true then _right else _left
  773. compareRight = if partial is true then _left else _right
  774. if direction is 'both'
  775. return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft))
  776. else if direction is 'vertical'
  777. return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop))
  778. else if direction is 'horizontal'
  779. return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft))
  780. window.ZammadChat = ZammadChat