forked from zammad/zammad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.coffee
1677 lines (1433 loc) · 63 KB
/
chat.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
do($ = window.jQuery, window) ->
scripts = document.getElementsByTagName('script')
# search for script to get protocol and hostname for ws connection
myScript = scripts[scripts.length - 1]
scriptProtocol = window.location.protocol.replace(':', '') # set default protocol
if myScript && myScript.src
scriptHost = myScript.src.match('.*://([^:/]*).*')[1]
scriptProtocol = myScript.src.match('(.*)://[^:/]*.*')[1]
# Define the plugin class
class Base
defaults:
debug: false
constructor: (options) ->
@options = $.extend {}, @defaults, options
@log = new Log(debug: @options.debug, logPrefix: @options.logPrefix || @logPrefix)
class Log
defaults:
debug: false
constructor: (options) ->
@options = $.extend {}, @defaults, options
debug: (items...) =>
return if [email protected]
@log('debug', items)
notice: (items...) =>
@log('notice', items)
error: (items...) =>
@log('error', items)
log: (level, items) =>
items.unshift('||')
items.unshift(level)
items.unshift(@options.logPrefix)
console.log.apply console, items
return if [email protected]
logString = ''
for item in items
logString += ' '
if typeof item is 'object'
logString += JSON.stringify(item)
else if item && item.toString
logString += item.toString()
else
logString += item
$('.js-chatLogDisplay').prepend('<div>' + logString + '</div>')
class Timeout extends Base
timeoutStartedAt: null
logPrefix: 'timeout'
defaults:
debug: false
timeout: 4
timeoutIntervallCheck: 0.5
constructor: (options) ->
super(options)
start: =>
@stop()
timeoutStartedAt = new Date
check = =>
timeLeft = new Date - new Date(timeoutStartedAt.getTime() + @options.timeout * 1000 * 60)
@log.debug "Timeout check for #{@options.timeout} minutes (left #{timeLeft/1000} sec.)"#, new Date
return if timeLeft < 0
@stop()
@options.callback()
@log.debug "Start timeout in #{@options.timeout} minutes"#, new Date
@intervallId = setInterval(check, @options.timeoutIntervallCheck * 1000 * 60)
stop: =>
return if !@intervallId
@log.debug "Stop timeout of #{@options.timeout} minutes"#, new Date
clearInterval(@intervallId)
class Io extends Base
logPrefix: 'io'
constructor: (options) ->
super(options)
set: (params) =>
for key, value of params
@options[key] = value
connect: =>
@log.debug "Connecting to #{@options.host}"
@ws = new window.WebSocket("#{@options.host}")
@ws.onopen = (e) =>
@log.debug 'onOpen', e
@options.onOpen(e)
@ping()
@ws.onmessage = (e) =>
pipes = JSON.parse(e.data)
@log.debug 'onMessage', e.data
for pipe in pipes
if pipe.event is 'pong'
@ping()
if @options.onMessage
@options.onMessage(pipes)
@ws.onclose = (e) =>
@log.debug 'close websocket connection', e
if @pingDelayId
clearTimeout(@pingDelayId)
if @manualClose
@log.debug 'manual close, onClose callback'
@manualClose = false
if @options.onClose
@options.onClose(e)
else
@log.debug 'error close, onError callback'
if @options.onError
@options.onError('Connection lost...')
@ws.onerror = (e) =>
@log.debug 'onError', e
if @options.onError
@options.onError(e)
close: =>
@log.debug 'close websocket manually'
@manualClose = true
@ws.close()
reconnect: =>
@log.debug 'reconnect'
@close()
@connect()
send: (event, data = {}) =>
@log.debug 'send', event, data
msg = JSON.stringify
event: event
data: data
@ws.send msg
ping: =>
localPing = =>
@send('ping')
@pingDelayId = setTimeout(localPing, 29000)
class ZammadChat extends Base
defaults:
chatId: undefined
show: true
target: $('body')
host: ''
debug: false
flat: false
lang: undefined
cssAutoload: true
cssUrl: undefined
fontSize: undefined
buttonClass: 'open-zammad-chat'
inactiveClass: 'is-inactive'
title: '<strong>Chat</strong> with us!'
scrollHint: 'Scroll down to see new messages'
idleTimeout: 6
idleTimeoutIntervallCheck: 0.5
inactiveTimeout: 8
inactiveTimeoutIntervallCheck: 0.5
waitingListTimeout: 4
waitingListTimeoutIntervallCheck: 0.5
# Callbacks
onReady: undefined
onCloseAnimationEnd: undefined
onError: undefined
onOpenAnimationEnd: undefined
onConnectionReestablished: undefined
onSessionClosed: undefined
onConnectionEstablished: undefined
onCssLoaded: undefined
logPrefix: 'chat'
_messageCount: 0
isOpen: false
blinkOnlineInterval: null
stopBlinOnlineStateTimeout: null
showTimeEveryXMinutes: 2
lastTimestamp: null
lastAddedType: null
inputDisabled: false
inputTimeout: null
isTyping: false
state: 'offline'
initialQueueDelay: 10000
translations:
# ZAMMAD_TRANSLATIONS_START
'cs':
'<strong>Chat</strong> with us!': '<strong>Chatujte</strong> s námi!'
'All colleagues are busy.': 'Všichni kolegové jsou vytíženi.'
'Chat closed by %s': '%s ukončil konverzaci'
'Compose your message…': 'Napište svou zprávu…'
'Connecting': 'Připojování'
'Connection lost': 'Připojení ztraceno'
'Connection re-established': 'Připojení obnoveno'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Srolujte dolů pro zobrazení nových zpráv'
'Send': 'Odeslat'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
'Start new conversation': 'Zahájit novou konverzaci'
'Today': 'Dnes'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
'You are on waiting list position <strong>%s</strong>.': 'Jste <strong>%s</strong>. v pořadí na čekací listině.'
'da':
'<strong>Chat</strong> with us!': '<strong>Chat</strong> med os!'
'All colleagues are busy.': 'Alle medarbejdere er optaget.'
'Chat closed by %s': 'Chat lukket af %s'
'Compose your message…': 'Skriv din besked…'
'Connecting': 'Forbinder'
'Connection lost': 'Forbindelse mistet'
'Connection re-established': 'Forbindelse genoprettet'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Scroll ned for at se nye beskeder'
'Send': 'Afsend'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
'Start new conversation': 'Start en ny samtale'
'Today': 'I dag'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
'You are on waiting list position <strong>%s</strong>.': 'Du er i kø som nummer <strong>%s</strong>.'
'de':
'<strong>Chat</strong> with us!': '<strong>Chatte</strong> mit uns!'
'All colleagues are busy.': 'Alle Kollegen sind beschäftigt.'
'Chat closed by %s': 'Chat von %s geschlossen'
'Compose your message…': 'Verfassen Sie Ihre Nachricht…'
'Connecting': 'Verbinde'
'Connection lost': 'Verbindung verloren'
'Connection re-established': 'Verbindung wieder aufgebaut'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Nach unten scrollen um neue Nachrichten zu sehen'
'Send': 'Senden'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Da Sie innerhalb der letzten %s Minuten nicht reagiert haben, wurde Ihre Unterhaltung geschlossen.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Da Sie innerhalb der letzten %s Minuten nicht reagiert haben, wurde Ihre Unterhaltung mit <strong>%s</strong> geschlossen.'
'Start new conversation': 'Neue Unterhaltung starten'
'Today': 'Heute'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Entschuldigung, es dauert länger als erwartet einen freien Platz zu bekommen. Versuchen Sie es später erneut oder senden Sie uns eine E-Mail. Vielen Dank!'
'You are on waiting list position <strong>%s</strong>.': 'Sie sind in der Warteliste auf Position <strong>%s</strong>.'
'es':
'<strong>Chat</strong> with us!': '<strong>Chatee</strong> con nosotros!'
'All colleagues are busy.': 'Todos los colegas están ocupados.'
'Chat closed by %s': 'Chat cerrado por %s'
'Compose your message…': 'Escribe tu mensaje…'
'Connecting': 'Conectando'
'Connection lost': 'Conexión perdida'
'Connection re-established': 'Conexión reestablecida'
'Offline': 'Desconectado'
'Online': 'En línea'
'Scroll down to see new messages': 'Desplace hacia abajo para ver nuevos mensajes'
'Send': 'Enviar'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Debido a que usted no ha respondido en los últimos %s minutos, su conversación se ha cerrado.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Debido a que usted no ha respondido en los últimos %s minutos, su conversación con <strong>%s</strong> se ha cerrado.'
'Start new conversation': 'Iniciar nueva conversación'
'Today': 'Hoy'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Lo sentimos, estamos tardando más de lo esperado para asignar un agente. Inténtelo de nuevo más tarde o envíenos un correo electrónico. ¡Gracias!'
'You are on waiting list position <strong>%s</strong>.': 'Usted está en la posición <strong>%s</strong> de la lista de espera.'
'fr':
'<strong>Chat</strong> with us!': '<strong>Chattez</strong> avec nous !'
'All colleagues are busy.': 'Tous les agents sont occupés.'
'Chat closed by %s': 'Chat fermé par %s'
'Compose your message…': 'Ecrivez votre message…'
'Connecting': 'Connexion'
'Connection lost': 'Connexion perdue'
'Connection re-established': 'Connexion ré-établie'
'Offline': 'Hors-ligne'
'Online': 'En ligne'
'Scroll down to see new messages': 'Défiler vers le bas pour voir les nouveaux messages'
'Send': 'Envoyer'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
'Start new conversation': 'Démarrer une nouvelle conversation'
'Today': 'Aujourd\'hui'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
'You are on waiting list position <strong>%s</strong>.': 'Vous êtes actuellement en position <strong>%s</strong> dans la file d\'attente.'
'hr':
'<strong>Chat</strong> with us!': '<strong>Čavrljajte</strong> sa nama!'
'All colleagues are busy.': 'Svi kolege su zauzeti.'
'Chat closed by %s': '%s zatvara chat'
'Compose your message…': 'Sastavite poruku…'
'Connecting': 'Povezivanje'
'Connection lost': 'Veza prekinuta'
'Connection re-established': 'Veza je ponovno uspostavljena'
'Offline': 'Odsutan'
'Online': 'Dostupan(a)'
'Scroll down to see new messages': 'Pomaknite se prema dolje da biste vidjeli nove poruke'
'Send': 'Šalji'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Budući da niste odgovorili u posljednjih %s minuta, Vaš je razgovor zatvoren.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Budući da niste odgovorili u posljednjih %s minuta, Vaš je razgovor s <strong>%</strong>s zatvoren.'
'Start new conversation': 'Započni novi razgovor'
'Today': 'Danas'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Oprostite, proces traje duže nego što se očekivalo da biste dobili slobodan termin. Molimo, pokušajte ponovno kasnije ili nam pošaljite e-mail. Hvala!'
'You are on waiting list position <strong>%s</strong>.': 'Nalazite se u redu čekanja na poziciji <strong>%s</strong>.'
'hu':
'<strong>Chat</strong> with us!': '<strong>Csevegjen</strong> velünk!'
'All colleagues are busy.': 'Minden munkatársunk foglalt.'
'Chat closed by %s': 'A csevegés %s által lezárva'
'Compose your message…': 'Fogalmazza meg üzenetét…'
'Connecting': 'Csatlakozás'
'Connection lost': 'A kapcsolat megszakadt'
'Connection re-established': 'A kapcsolat helyreállt'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Görgessen lefelé az új üzenetek megtekintéséhez'
'Send': 'Küldés'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Mivel az elmúlt %s percben nem válaszolt, a beszélgetése lezárásra került.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Mivel az elmúlt %s percben nem válaszolt, <strong>%s</strong> munkatársunkkal folytatott beszélgetését lezártuk.'
'Start new conversation': 'Új beszélgetés indítása'
'Today': 'Ma'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Sajnáljuk, hogy a vártnál hosszabb ideig tart a helyfoglalás. Kérjük, próbálja meg később újra, vagy küldjön nekünk egy e-mailt. Köszönjük!'
'You are on waiting list position <strong>%s</strong>.': 'Ön a várólistán a <strong>%s</strong> helyen szerepel.'
'it':
'<strong>Chat</strong> with us!': '<strong>Chatta</strong> con noi!'
'All colleagues are busy.': 'Tutti i colleghi sono occupati.'
'Chat closed by %s': 'Chat chiusa da %s'
'Compose your message…': 'Scrivi il tuo messaggio…'
'Connecting': 'Connessione in corso'
'Connection lost': 'Connessione persa'
'Connection re-established': 'Connessione ristabilita'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Scorri verso il basso per vedere i nuovi messaggi'
'Send': 'Invia'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
'Start new conversation': 'Avvia una nuova chat'
'Today': 'Oggi'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
'You are on waiting list position <strong>%s</strong>.': 'Sei alla posizione <strong>%s</strong> della lista di attesa.'
'nl':
'<strong>Chat</strong> with us!': '<strong>Chat</strong> met ons!'
'All colleagues are busy.': 'Alle collega\'s zijn bezet.'
'Chat closed by %s': 'Chat gesloten door %s'
'Compose your message…': 'Stel je bericht op…'
'Connecting': 'Verbinden'
'Connection lost': 'Verbinding verbroken'
'Connection re-established': 'Verbinding hersteld'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Scroll naar beneden om nieuwe tickets te bekijken'
'Send': 'Verstuur'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'De chat is afgesloten omdat je de laatste %s minuten niet hebt gereageerd.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Je chat met <strong>%s</strong> is afgesloten omdat je niet hebt gereageerd in de laatste %s minuten.'
'Start new conversation': 'Nieuw gesprek starten'
'Today': 'Vandaag'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Het spijt ons, het duurt langer dan verwacht om een chat te starten. Probeer het later nog eens of stuur ons een e-mail. Bedankt!'
'You are on waiting list position <strong>%s</strong>.': 'U bevindt zich op wachtlijstpositie <strong>%s</strong>.'
'pl':
'<strong>Chat</strong> with us!': '<strong>Czatuj</strong> z nami!'
'All colleagues are busy.': 'Wszyscy agenci są zajęci.'
'Chat closed by %s': 'Chat zamknięty przez %s'
'Compose your message…': 'Skomponuj swoją wiadomość…'
'Connecting': 'Łączenie'
'Connection lost': 'Utracono połączenie'
'Connection re-established': 'Ponowne nawiązanie połączenia'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Skroluj w dół, aby zobaczyć wiadomości'
'Send': 'Wyślij'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Ponieważ nie odpowiedziałeś w ciągu ostatnich %s minut, Twoja rozmowa została zamknięta.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Ponieważ nie odpowiedziałeś w ciągu ostatnich %s minut, Twoja rozmowa z <strong>%s</strong> została zamknięta.'
'Start new conversation': 'Rozpocznij nową rozmowę'
'Today': 'Dzisiaj'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Przepraszamy, znalezienie wolnego konsultanta zajmuje więcej czasu niż oczekiwano. Spróbuj ponownie później lub wyślij nam e-mail. Dziękujemy!'
'You are on waiting list position <strong>%s</strong>.': 'Jesteś na pozycji listy oczekujących <strong>%s</strong>.'
'pt-br':
'<strong>Chat</strong> with us!': '<strong>Converse</strong> conosco!'
'All colleagues are busy.': 'Nossos atendentes estão ocupados.'
'Chat closed by %s': 'Chat encerrado por %s'
'Compose your message…': 'Escreva sua mensagem…'
'Connecting': 'Conectando'
'Connection lost': 'Conexão perdida'
'Connection re-established': 'Conexão restabelecida'
'Offline': 'Desconectado'
'Online': 'Online'
'Scroll down to see new messages': 'Rolar para baixo para ver novas mensagems'
'Send': 'Enviar'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Como você não respondeu nos últimos %s minutos, sua conversa foi encerrada.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Como você não respondeu nos últimos %s minutos, sua conversa com <strong>%s</strong> foi encerrada.'
'Start new conversation': 'Iniciar uma nova conversa'
'Today': 'Hoje'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Lamentamos, está demorando mais do que o esperado para conseguir uma vaga. Tente novamente mais tarde ou envie-nos um e-mail. Obrigado!'
'You are on waiting list position <strong>%s</strong>.': 'Você está na posição <strong>%s</strong> da lista de espera.'
'ru':
'<strong>Chat</strong> with us!': '<strong>Напишите</strong> нам!'
'All colleagues are busy.': 'Все коллеги заняты.'
'Chat closed by %s': 'Чат закрыт %s'
'Compose your message…': 'Составьте сообщение…'
'Connecting': 'Подключение'
'Connection lost': 'Подключение потеряно'
'Connection re-established': 'Подключение восстановлено'
'Offline': 'Оффлайн'
'Online': 'В сети'
'Scroll down to see new messages': 'Прокрутите вниз, чтобы увидеть новые сообщения'
'Send': 'Отправить'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
'Start new conversation': 'Начать новую беседу'
'Today': 'Сегодня'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
'You are on waiting list position <strong>%s</strong>.': 'Вы находитесь в списке ожидания <strong>%s</strong>.'
'sr':
'<strong>Chat</strong> with us!': '<strong>Ћаскајте</strong> са нама!'
'All colleagues are busy.': 'Све колеге су заузете.'
'Chat closed by %s': 'Ћаскање затворено од стране %s'
'Compose your message…': 'Напишите поруку…'
'Connecting': 'Повезивање'
'Connection lost': 'Веза је изгубљена'
'Connection re-established': 'Веза је поново успостављена'
'Offline': 'Одсутан(а)'
'Online': 'Доступан(а)'
'Scroll down to see new messages': 'Скролујте на доле за нове поруке'
'Send': 'Пошаљи'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор је завршен.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор са <strong>%s</strong> је завршен.'
'Start new conversation': 'Започни нови разговор'
'Today': 'Данас'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Жао нам је, добијање празног термина траје дуже од очекиваног. Молимо покушајте поново касније или нам пошаљите имејл поруку. Хвала вам!'
'You are on waiting list position <strong>%s</strong>.': 'Ви сте тренутно <strong>%s.</strong> у реду за чекање.'
'sr-latn-rs':
'<strong>Chat</strong> with us!': '<strong>Ćaskajte</strong> sa nama!'
'All colleagues are busy.': 'Sve kolege su zauzete.'
'Chat closed by %s': 'Ćaskanje zatvoreno od strane %s'
'Compose your message…': 'Napišite poruku…'
'Connecting': 'Povezivanje'
'Connection lost': 'Veza je izgubljena'
'Connection re-established': 'Veza je ponovo uspostavljena'
'Offline': 'Odsutan(a)'
'Online': 'Dostupan(a)'
'Scroll down to see new messages': 'Skrolujte na dole za nove poruke'
'Send': 'Pošalji'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Pošto niste odgovorili u poslednjih %s minut(a), vaš razgovor je završen.'
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Pošto niste odgovorili u poslednjih %s minut(a), vaš razgovor sa <strong>%s</strong> je završen.'
'Start new conversation': 'Započni novi razgovor'
'Today': 'Danas'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Žao nam je, dobijanje praznog termina traje duže od očekivanog. Molimo pokušajte ponovo kasnije ili nam pošaljite imejl poruku. Hvala vam!'
'You are on waiting list position <strong>%s</strong>.': 'Vi ste trenutno <strong>%s.</strong> u redu za čekanje.'
'sv':
'<strong>Chat</strong> with us!': '<strong>Chatta</strong> med oss!'
'All colleagues are busy.': 'Alla kollegor är upptagna.'
'Chat closed by %s': 'Chatt stängd av %s'
'Compose your message…': 'Skriv ditt meddelande …'
'Connecting': 'Ansluter'
'Connection lost': 'Anslutningen försvann'
'Connection re-established': 'Anslutningen återupprättas'
'Offline': 'Offline'
'Online': 'Online'
'Scroll down to see new messages': 'Bläddra ner för att se nya meddelanden'
'Send': 'Skicka'
'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
'Start new conversation': 'Starta ny konversation'
'Today': 'Idag'
'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Det tar tyvärr längre tid än förväntat att få en ledig plats. Försök igen senare eller skicka ett mejl till oss. Tack!'
'You are on waiting list position <strong>%s</strong>.': 'Du är på väntelistan som position <strong>%s</strong>.'
# ZAMMAD_TRANSLATIONS_END
sessionId: undefined
scrolledToBottom: true
scrollSnapTolerance: 10
richTextFormatKey:
66: true # b
73: true # i
85: true # u
83: true # s
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
view: (name) =>
return (options) =>
if !options
options = {}
options.T = @T
options.background = @options.background
options.flat = @options.flat
options.fontSize = @options.fontSize
return window.zammadChatTemplates[name](options)
constructor: (options) ->
@options = $.extend {}, @defaults, options
super(@options)
# fullscreen
@isFullscreen = (window.matchMedia and window.matchMedia('(max-width: 768px)').matches)
@scrollRoot = $(@getScrollRoot())
# check prerequisites
if !$
@state = 'unsupported'
@log.notice 'Chat: no jquery found!'
return
if !window.WebSocket or !sessionStorage
@state = 'unsupported'
@log.notice 'Chat: Browser not supported!'
return
@state = 'unsupported'
@log.error 'Chat: need chatId as option!'
return
# detect language
@options.lang = $('html').attr('lang')
if @options.lang
if !@translations[@options.lang]
@log.debug "lang: No #{@options.lang} found, try first two letters"
@options.lang = @options.lang.replace(/-.+?$/, '') # replace "-xx" of xx-xx
@log.debug "lang: #{@options.lang}"
# detect host
@detectHost() if [email protected]
@loadCss()
@io = new Io(@options)
@io.set(
onOpen: @render
onClose: @onWebSocketClose
onMessage: @onWebSocketMessage
onError: @onError
)
@io.connect()
getScrollRoot: ->
return document.scrollingElement if 'scrollingElement' of document
html = document.documentElement
start = html.scrollTop
html.scrollTop = start + 1
end = html.scrollTop
html.scrollTop = start
return if end > start then html else document.body
render: =>
if !@el || !$('.zammad-chat').get(0)
@renderBase()
# disable open button
$(".#{ @options.buttonClass }").addClass @options.inactiveClass
@setAgentOnlineState 'online'
@log.debug 'widget rendered'
@startTimeoutObservers()
@idleTimeout.start()
# get current chat status
@sessionId = sessionStorage.getItem('sessionId')
@send 'chat_status_customer',
session_id: @sessionId
url: window.location.href
renderBase: ->
@el = $(@view('chat')(
title: @options.title,
scrollHint: @options.scrollHint
))
@options.target.append @el
@input = @el.find('.zammad-chat-input')
# start bindings
@el.find('.js-chat-open').on 'click', @open
@el.find('.js-chat-toggle').on 'click', @toggle
@el.find('.js-chat-status').on 'click', @stopPropagation
@el.find('.zammad-chat-controls').on 'submit', @onSubmit
@el.find('.zammad-chat-body').on 'scroll', @detectScrolledtoBottom
@el.find('.zammad-scroll-hint').on 'click', @onScrollHintClick
@input.on(
keydown: @checkForEnter
input: @onInput
)
@input.on('keydown', (e) =>
richtTextControl = false
if !e.altKey && !e.ctrlKey && e.metaKey
richtTextControl = true
else if !e.altKey && e.ctrlKey && !e.metaKey
richtTextControl = true
if richtTextControl && @richTextFormatKey[ e.keyCode ]
e.preventDefault()
if e.keyCode is 66
document.execCommand('bold')
return true
if e.keyCode is 73
document.execCommand('italic')
return true
if e.keyCode is 85
document.execCommand('underline')
return true
if e.keyCode is 83
document.execCommand('strikeThrough')
return true
)
@input.on('paste', (e) =>
e.stopPropagation()
e.preventDefault()
clipboardData
if e.clipboardData
clipboardData = e.clipboardData
else if window.clipboardData
clipboardData = window.clipboardData
else if e.originalEvent.clipboardData
clipboardData = e.originalEvent.clipboardData
else
throw 'No clipboardData support'
imageInserted = false
if clipboardData && clipboardData.items && clipboardData.items[0]
item = clipboardData.items[0]
if item.kind == 'file' && (item.type == 'image/png' || item.type == 'image/jpeg')
imageFile = item.getAsFile()
reader = new FileReader()
reader.onload = (e) =>
result = e.target.result
img = document.createElement('img')
img.src = result
insert = (dataUrl, width, height, isRetina) =>
# adapt image if we are on retina devices
if @isRetina()
width = width / 2
height = height / 2
result = dataUrl
img = "<img style=\"width: 100%; max-width: #{width}px;\" src=\"#{result}\">"
document.execCommand('insertHTML', false, img)
# resize if to big
@resizeImage(img.src, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
reader.readAsDataURL(imageFile)
imageInserted = true
return if imageInserted
# check existing + paste text for limit
text = undefined
docType = undefined
try
text = clipboardData.getData('text/html')
docType = 'html'
if !text || text.length is 0
docType = 'text'
text = clipboardData.getData('text/plain')
if !text || text.length is 0
docType = 'text2'
text = clipboardData.getData('text')
catch e
console.log('Sorry, can\'t insert markup because browser is not supporting it.')
docType = 'text3'
text = clipboardData.getData('text')
if docType is 'text' || docType is 'text2' || docType is 'text3'
text = '<div>' + text.replace(/\n/g, '</div><div>') + '</div>'
text = text.replace(/<div><\/div>/g, '<div><br></div>')
console.log('p', docType, text)
if docType is 'html'
sanitized = DOMPurify.sanitize(text)
@log.debug 'sanitized HTML clipboard', sanitized
html = $("<div>#{sanitized}</div>")
match = false
htmlTmp = text
regex = new RegExp('<(/w|w)\:[A-Za-z]')
if htmlTmp.match(regex)
match = true
htmlTmp = htmlTmp.replace(regex, '')
regex = new RegExp('<(/o|o)\:[A-Za-z]')
if htmlTmp.match(regex)
match = true
htmlTmp = htmlTmp.replace(regex, '')
if match
html = @wordFilter(html)
#html
html = $(html)
html.contents().each( ->
if @nodeType == 8
$(@).remove()
)
# remove tags, keep content
html.find('a, font, small, time, form, label').replaceWith( ->
$(@).contents()
)
# replace tags with generic div
# New type of the tag
replacementTag = 'div';
# Replace all x tags with the type of replacementTag
html.find('textarea').each( ->
outer = @outerHTML
# Replace opening tag
regex = new RegExp('<' + @tagName, 'i')
newTag = outer.replace(regex, '<' + replacementTag)
# Replace closing tag
regex = new RegExp('</' + @tagName, 'i')
newTag = newTag.replace(regex, '</' + replacementTag)
$(@).replaceWith(newTag)
)
# remove tags & content
html.find('font, img, svg, input, select, button, style, applet, embed, noframes, canvas, script, frame, iframe, meta, link, title, head, fieldset').remove()
@removeAttributes(html)
text = html.html()
# as fallback, insert html via pasteHtmlAtCaret (for IE 11 and lower)
if docType is 'text3'
@pasteHtmlAtCaret(text)
else
document.execCommand('insertHTML', false, text)
true
)
@input.on('drop', (e) =>
e.stopPropagation()
e.preventDefault()
dataTransfer
if window.dataTransfer # ie
dataTransfer = window.dataTransfer
else if e.originalEvent.dataTransfer # other browsers
dataTransfer = e.originalEvent.dataTransfer
else
throw 'No clipboardData support'
x = e.clientX
y = e.clientY
file = dataTransfer.files[0]
# look for images
if file.type.match('image.*')
reader = new FileReader()
reader.onload = (e) =>
result = e.target.result
img = document.createElement('img')
img.src = result
# Insert the image at the carat
insert = (dataUrl, width, height, isRetina) =>
# adapt image if we are on retina devices
if @isRetina()
width = width / 2
height = height / 2
result = dataUrl
img = $("<img style=\"width: 100%; max-width: #{width}px;\" src=\"#{result}\">")
img = img.get(0)
if document.caretPositionFromPoint
pos = document.caretPositionFromPoint(x, y)
range = document.createRange()
range.setStart(pos.offsetNode, pos.offset)
range.collapse()
range.insertNode(img)
else if document.caretRangeFromPoint
range = document.caretRangeFromPoint(x, y)
range.insertNode(img)
else
console.log('could not find carat')
# resize if to big
@resizeImage(img.src, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
reader.readAsDataURL(file)
)
$(window).on('beforeunload', =>
@onLeaveTemporary()
)
$(window).on('hashchange', =>
if @isOpen
if @sessionId
@send 'chat_session_notice',
session_id: @sessionId
message: window.location.href
return
@idleTimeout.start()
)
if @isFullscreen
@input.on
focus: @onFocus
focusout: @onFocusOut
stopPropagation: (event) ->
event.stopPropagation()
checkForEnter: (event) =>
if not @inputDisabled and not event.shiftKey and event.keyCode is 13
event.preventDefault()
@sendMessage()
send: (event, data = {}) =>
data.chat_id = @options.chatId
@io.send(event, data)
onWebSocketMessage: (pipes) =>
for pipe in pipes
@log.debug 'ws:onmessage', pipe
switch pipe.event
when 'chat_error'
@log.notice pipe.data
if pipe.data && pipe.data.state is 'chat_disabled'
@destroy(remove: true)
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
when 'chat_session_queue'
@onQueueScreen pipe.data
when 'chat_session_closed'
@onSessionClosed pipe.data
when 'chat_session_left'
@onSessionClosed pipe.data
when 'chat_session_notice'
@addStatus @T(pipe.data.message)
when 'chat_status_customer'
switch pipe.data.state
when 'online'
@sessionId = undefined
if [email protected] || @cssLoaded
@onReady()
else
@socketReady = true
when 'offline'
@onError 'Zammad Chat: No agent online'
when 'chat_disabled'
@onError 'Zammad Chat: Chat is disabled'
when 'no_seats_available'
@onError "Zammad Chat: Too many clients in queue. Clients in queue: #{pipe.data.queue}"
when 'reconnect'
@onReopenSession pipe.data
onReady: ->
@log.debug 'widget ready for use'
$(".#{ @options.buttonClass }").on('click', @open).removeClass(@options.inactiveClass)
@options.onReady?()
if @options.show
@show()
onError: (message) =>
@log.debug message
@addStatus(message)
$(".#{ @options.buttonClass }").hide()
if @isOpen
@disableInput()
@destroy(remove: false)
else
@destroy(remove: true)
@options.onError?(message)
onReopenSession: (data) =>
@log.debug 'old messages', data.session
@inactiveTimeout.start()
unfinishedMessage = sessionStorage.getItem 'unfinished_message'
# rerender chat history
if data.agent
@onConnectionEstablished(data)
for message in data.session
@renderMessage
message: message.content
id: message.id
from: if message.created_by_id then 'agent' else 'customer'
if unfinishedMessage
@input.html(unfinishedMessage)
# show wait list
if data.position
@onQueue data
@show()
@open()
@scrollToBottom()
if unfinishedMessage
@input.trigger('focus')
onInput: =>
# remove unread-state from messages
@el.find('.zammad-chat-message--unread')
.removeClass 'zammad-chat-message--unread'
sessionStorage.setItem 'unfinished_message', @input.html()
@onTyping()
onFocus: =>
$(window).scrollTop(10)
keyboardShown = $(window).scrollTop() > 0
$(window).scrollTop(0)
if keyboardShown
@log.notice 'virtual keyboard shown'
# on keyboard shown
# can't measure visible area height :(
onFocusOut: ->
# on keyboard hidden
onTyping: ->
# 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
@inactiveTimeout.start()
onSubmit: (event) =>
event.preventDefault()
@sendMessage()
sendMessage: ->
message = @input.html()
return if !message
@inactiveTimeout.start()
sessionStorage.removeItem 'unfinished_message'
messageElement = @view('message')
message: message
from: 'customer'
id: @_messageCount++
unreadClass: ''
@maybeAddTimestamp()
# add message before message typing loader
if @el.find('.zammad-chat-message--typing').get(0)
@lastAddedType = 'typing-placeholder'
@el.find('.zammad-chat-message--typing').before messageElement
else
@lastAddedType = 'message--customer'
@el.find('.zammad-chat-body').append messageElement
@input.html('')
@scrollToBottom()
# send message event
@send 'chat_session_message',
content: message
id: @_messageCount
session_id: @sessionId
receiveMessage: (data) =>
@inactiveTimeout.start()
# hide writing indicator
@onAgentTypingEnd()
@maybeAddTimestamp()
@renderMessage