chat.coffee 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731
  1. do($ = window.jQuery, window) ->
  2. scripts = document.getElementsByTagName('script')
  3. # search for script to get protocol and hostname for ws connection
  4. myScript = scripts[scripts.length - 1]
  5. scriptProtocol = window.location.protocol.replace(':', '') # set default protocol
  6. if myScript && myScript.src
  7. scriptHost = myScript.src.match('.*://([^:/]*).*')[1]
  8. scriptProtocol = myScript.src.match('(.*)://[^:/]*.*')[1]
  9. # Define the plugin class
  10. class Base
  11. defaults:
  12. debug: false
  13. constructor: (options) ->
  14. @options = $.extend {}, @defaults, options
  15. @log = new Log(debug: @options.debug, logPrefix: @options.logPrefix || @logPrefix)
  16. class Log
  17. defaults:
  18. debug: false
  19. constructor: (options) ->
  20. @options = $.extend {}, @defaults, options
  21. debug: (items...) =>
  22. return if !@options.debug
  23. @log('debug', items)
  24. notice: (items...) =>
  25. @log('notice', items)
  26. error: (items...) =>
  27. @log('error', items)
  28. log: (level, items) =>
  29. items.unshift('||')
  30. items.unshift(level)
  31. items.unshift(@options.logPrefix)
  32. console.log.apply console, items
  33. return if !@options.debug
  34. logString = ''
  35. for item in items
  36. logString += ' '
  37. if typeof item is 'object'
  38. logString += JSON.stringify(item)
  39. else if item && item.toString
  40. logString += item.toString()
  41. else
  42. logString += item
  43. $('.js-chatLogDisplay').prepend('<div>' + logString + '</div>')
  44. class Timeout extends Base
  45. timeoutStartedAt: null
  46. logPrefix: 'timeout'
  47. defaults:
  48. debug: false
  49. timeout: 4
  50. timeoutIntervallCheck: 0.5
  51. constructor: (options) ->
  52. super(options)
  53. start: =>
  54. @stop()
  55. timeoutStartedAt = new Date
  56. check = =>
  57. timeLeft = new Date - new Date(timeoutStartedAt.getTime() + @options.timeout * 1000 * 60)
  58. @log.debug "Timeout check for #{@options.timeout} minutes (left #{timeLeft/1000} sec.)"#, new Date
  59. return if timeLeft < 0
  60. @stop()
  61. @options.callback()
  62. @log.debug "Start timeout in #{@options.timeout} minutes"#, new Date
  63. @intervallId = setInterval(check, @options.timeoutIntervallCheck * 1000 * 60)
  64. stop: =>
  65. return if !@intervallId
  66. @log.debug "Stop timeout of #{@options.timeout} minutes"#, new Date
  67. clearInterval(@intervallId)
  68. class Io extends Base
  69. logPrefix: 'io'
  70. constructor: (options) ->
  71. super(options)
  72. set: (params) =>
  73. for key, value of params
  74. @options[key] = value
  75. connect: =>
  76. @log.debug "Connecting to #{@options.host}"
  77. @ws = new window.WebSocket("#{@options.host}")
  78. @ws.onopen = (e) =>
  79. @log.debug 'onOpen', e
  80. @options.onOpen(e)
  81. @ping()
  82. @ws.onmessage = (e) =>
  83. pipes = JSON.parse(e.data)
  84. @log.debug 'onMessage', e.data
  85. for pipe in pipes
  86. if pipe.event is 'pong'
  87. @ping()
  88. if @options.onMessage
  89. @options.onMessage(pipes)
  90. @ws.onclose = (e) =>
  91. @log.debug 'close websocket connection', e
  92. if @pingDelayId
  93. clearTimeout(@pingDelayId)
  94. if @manualClose
  95. @log.debug 'manual close, onClose callback'
  96. @manualClose = false
  97. if @options.onClose
  98. @options.onClose(e)
  99. else
  100. @log.debug 'error close, onError callback'
  101. if @options.onError
  102. @options.onError('Connection lost...')
  103. @ws.onerror = (e) =>
  104. @log.debug 'onError', e
  105. if @options.onError
  106. @options.onError(e)
  107. close: =>
  108. @log.debug 'close websocket manually'
  109. @manualClose = true
  110. @ws.close()
  111. reconnect: =>
  112. @log.debug 'reconnect'
  113. @close()
  114. @connect()
  115. send: (event, data = {}) =>
  116. @log.debug 'send', event, data
  117. msg = JSON.stringify
  118. event: event
  119. data: data
  120. @ws.send msg
  121. ping: =>
  122. localPing = =>
  123. @send('ping')
  124. @pingDelayId = setTimeout(localPing, 29000)
  125. class ZammadChat extends Base
  126. defaults:
  127. chatId: undefined
  128. show: true
  129. target: $('body')
  130. host: ''
  131. debug: false
  132. flat: false
  133. lang: undefined
  134. cssAutoload: true
  135. cssUrl: undefined
  136. fontSize: undefined
  137. buttonClass: 'open-zammad-chat'
  138. inactiveClass: 'is-inactive'
  139. title: '<strong>Chat</strong> with us!'
  140. scrollHint: 'Scroll down to see new messages'
  141. idleTimeout: 6
  142. idleTimeoutIntervallCheck: 0.5
  143. inactiveTimeout: 8
  144. inactiveTimeoutIntervallCheck: 0.5
  145. waitingListTimeout: 4
  146. waitingListTimeoutIntervallCheck: 0.5
  147. # Callbacks
  148. onReady: undefined
  149. onCloseAnimationEnd: undefined
  150. onError: undefined
  151. onOpenAnimationEnd: undefined
  152. onConnectionReestablished: undefined
  153. onSessionClosed: undefined
  154. onConnectionEstablished: undefined
  155. onCssLoaded: undefined
  156. logPrefix: 'chat'
  157. _messageCount: 0
  158. isOpen: false
  159. blinkOnlineInterval: null
  160. stopBlinOnlineStateTimeout: null
  161. showTimeEveryXMinutes: 2
  162. lastTimestamp: null
  163. lastAddedType: null
  164. inputDisabled: false
  165. inputTimeout: null
  166. isTyping: false
  167. state: 'offline'
  168. initialQueueDelay: 10000
  169. translations:
  170. # ZAMMAD_TRANSLATIONS_START
  171. 'cs':
  172. '<strong>Chat</strong> with us!': '<strong>Chatujte</strong> s námi!'
  173. 'All colleagues are busy.': 'Všichni kolegové jsou vytíženi.'
  174. 'Chat closed by %s': '%s ukončil konverzaci'
  175. 'Compose your message…': 'Napište svou zprávu…'
  176. 'Connecting': 'Připojování'
  177. 'Connection lost': 'Připojení ztraceno'
  178. 'Connection re-established': 'Připojení obnoveno'
  179. 'Offline': 'Offline'
  180. 'Online': 'Online'
  181. 'Scroll down to see new messages': 'Srolujte dolů pro zobrazení nových zpráv'
  182. 'Send': 'Odeslat'
  183. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Jelikož jste nereagovali v posledních %s minutách, vaše konverzace byla uzavřena.'
  184. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Jelikož jste nereagovali v posledních %s minutách, vaše konverzace s <strong>%s</strong> byla uzavřena.'
  185. 'Start new conversation': 'Zahájit novou konverzaci'
  186. 'Today': 'Dnes'
  187. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Omlouváme se, že musíte čekat déle, než je vhodné pro získání slotu. Prosím, zkuste to později, případně nám napište e-mail. Děkujeme!'
  188. 'You are on waiting list position <strong>%s</strong>.': 'Jste <strong>%s</strong>. v pořadí na čekací listině.'
  189. 'da':
  190. '<strong>Chat</strong> with us!': '<strong>Chat</strong> med os!'
  191. 'All colleagues are busy.': 'Alle medarbejdere er optaget.'
  192. 'Chat closed by %s': 'Chat lukket af %s'
  193. 'Compose your message…': 'Skriv din besked…'
  194. 'Connecting': 'Forbinder'
  195. 'Connection lost': 'Forbindelse mistet'
  196. 'Connection re-established': 'Forbindelse genoprettet'
  197. 'Offline': 'Offline'
  198. 'Online': 'Online'
  199. 'Scroll down to see new messages': 'Scroll ned for at se nye beskeder'
  200. 'Send': 'Afsend'
  201. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
  202. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
  203. 'Start new conversation': 'Start en ny samtale'
  204. 'Today': 'I dag'
  205. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
  206. 'You are on waiting list position <strong>%s</strong>.': 'Du er i kø som nummer <strong>%s</strong>.'
  207. 'de':
  208. '<strong>Chat</strong> with us!': '<strong>Chatte</strong> mit uns!'
  209. 'All colleagues are busy.': 'Alle Kollegen sind beschäftigt.'
  210. 'Chat closed by %s': 'Chat von %s geschlossen'
  211. 'Compose your message…': 'Verfassen Sie Ihre Nachricht…'
  212. 'Connecting': 'Verbinde'
  213. 'Connection lost': 'Verbindung verloren'
  214. 'Connection re-established': 'Verbindung wieder aufgebaut'
  215. 'Offline': 'Offline'
  216. 'Online': 'Online'
  217. 'Scroll down to see new messages': 'Nach unten scrollen um neue Nachrichten zu sehen'
  218. 'Send': 'Senden'
  219. '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.'
  220. '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.'
  221. 'Start new conversation': 'Neue Unterhaltung starten'
  222. 'Today': 'Heute'
  223. '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!'
  224. 'You are on waiting list position <strong>%s</strong>.': 'Sie sind in der Warteliste auf Position <strong>%s</strong>.'
  225. 'es':
  226. '<strong>Chat</strong> with us!': '<strong>Chatee</strong> con nosotros!'
  227. 'All colleagues are busy.': 'Todos los colegas están ocupados.'
  228. 'Chat closed by %s': 'Chat cerrado por %s'
  229. 'Compose your message…': 'Escribe tu mensaje…'
  230. 'Connecting': 'Conectando'
  231. 'Connection lost': 'Conexión perdida'
  232. 'Connection re-established': 'Conexión reestablecida'
  233. 'Offline': 'Desconectado'
  234. 'Online': 'En línea'
  235. 'Scroll down to see new messages': 'Desplace hacia abajo para ver nuevos mensajes'
  236. 'Send': 'Enviar'
  237. '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.'
  238. '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.'
  239. 'Start new conversation': 'Iniciar nueva conversación'
  240. 'Today': 'Hoy'
  241. '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!'
  242. 'You are on waiting list position <strong>%s</strong>.': 'Usted está en la posición <strong>%s</strong> de la lista de espera.'
  243. 'fr':
  244. '<strong>Chat</strong> with us!': '<strong>Chattez</strong> avec nous !'
  245. 'All colleagues are busy.': 'Tous les agents sont occupés.'
  246. 'Chat closed by %s': 'Chat fermé par %s'
  247. 'Compose your message…': 'Écrivez votre message…'
  248. 'Connecting': 'Connexion'
  249. 'Connection lost': 'Connexion perdue'
  250. 'Connection re-established': 'Connexion ré-établie'
  251. 'Offline': 'Hors-ligne'
  252. 'Online': 'En ligne'
  253. 'Scroll down to see new messages': 'Défiler vers le bas pour voir les nouveaux messages'
  254. 'Send': 'Envoyer'
  255. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Sans réponse de votre part depuis %s minutes, votre conservation a été fermée.'
  256. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Sans réponse de votre part depuis %s minutes, votre conversation avec <strong>%s</strong> a été fermée.'
  257. 'Start new conversation': 'Démarrer une nouvelle conversation'
  258. 'Today': 'Aujourd\'hui'
  259. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Nous sommes désolés, trouver un agent disponible prend plus de temps que prévu. Réessayez plus tard ou envoyez-nous un mail. Merci !'
  260. 'You are on waiting list position <strong>%s</strong>.': 'Vous êtes actuellement en position <strong>%s</strong> dans la file d\'attente.'
  261. 'hr':
  262. '<strong>Chat</strong> with us!': '<strong>Čavrljajte</strong> sa nama!'
  263. 'All colleagues are busy.': 'Svi kolege su zauzeti.'
  264. 'Chat closed by %s': '%s zatvara chat'
  265. 'Compose your message…': 'Sastavite poruku…'
  266. 'Connecting': 'Povezivanje'
  267. 'Connection lost': 'Veza prekinuta'
  268. 'Connection re-established': 'Veza je ponovno uspostavljena'
  269. 'Offline': 'Odsutan'
  270. 'Online': 'Dostupan(a)'
  271. 'Scroll down to see new messages': 'Pomaknite se prema dolje da biste vidjeli nove poruke'
  272. 'Send': 'Šalji'
  273. '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.'
  274. '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.'
  275. 'Start new conversation': 'Započni novi razgovor'
  276. 'Today': 'Danas'
  277. '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!'
  278. 'You are on waiting list position <strong>%s</strong>.': 'Nalazite se u redu čekanja na poziciji <strong>%s</strong>.'
  279. 'hu':
  280. '<strong>Chat</strong> with us!': '<strong>Csevegjen</strong> velünk!'
  281. 'All colleagues are busy.': 'Minden munkatársunk foglalt.'
  282. 'Chat closed by %s': 'A csevegés %s által lezárva'
  283. 'Compose your message…': 'Fogalmazza meg üzenetét…'
  284. 'Connecting': 'Csatlakozás'
  285. 'Connection lost': 'A kapcsolat megszakadt'
  286. 'Connection re-established': 'A kapcsolat helyreállt'
  287. 'Offline': 'Offline'
  288. 'Online': 'Online'
  289. 'Scroll down to see new messages': 'Görgessen lefelé az új üzenetek megtekintéséhez'
  290. 'Send': 'Küldés'
  291. '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.'
  292. '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.'
  293. 'Start new conversation': 'Új beszélgetés indítása'
  294. 'Today': 'Ma'
  295. '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!'
  296. 'You are on waiting list position <strong>%s</strong>.': 'Ön a várólistán a <strong>%s</strong> helyen szerepel.'
  297. 'it':
  298. '<strong>Chat</strong> with us!': '<strong>Chatta</strong> con noi!'
  299. 'All colleagues are busy.': 'Tutti i colleghi sono occupati.'
  300. 'Chat closed by %s': 'Chat chiusa da %s'
  301. 'Compose your message…': 'Scrivi il tuo messaggio…'
  302. 'Connecting': 'Connessione in corso'
  303. 'Connection lost': 'Connessione persa'
  304. 'Connection re-established': 'Connessione ristabilita'
  305. 'Offline': 'Offline'
  306. 'Online': 'Online'
  307. 'Scroll down to see new messages': 'Scorri verso il basso per vedere i nuovi messaggi'
  308. 'Send': 'Invia'
  309. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Dato che non hai risposto negli ultimi %s minuti, la conversazione è stata chiusa.'
  310. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Dato che non hai risposto negli ultimi %s minuti, la conversazione con <strong>%s</strong> è stata chiusa.'
  311. 'Start new conversation': 'Avvia una nuova chat'
  312. 'Today': 'Oggi'
  313. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Siamo spiacenti, ci vuole più tempo del previsto per ottenere uno spazio libero. Riprova più tardi o inviaci un\'e-mail. Grazie!'
  314. 'You are on waiting list position <strong>%s</strong>.': 'Sei alla posizione <strong>%s</strong> della lista di attesa.'
  315. 'lt':
  316. '<strong>Chat</strong> with us!': '<strong>Kalbėkitės</strong> su mumis!'
  317. 'All colleagues are busy.': 'Visi kolegos užimti.'
  318. 'Chat closed by %s': '%s uždarė pokalbį'
  319. 'Compose your message…': 'Rašykite žinutę…'
  320. 'Connecting': 'Jungiamasi'
  321. 'Connection lost': 'Dingo ryšys'
  322. 'Connection re-established': 'Ryšys atnaujintas'
  323. 'Offline': 'Atsijungęs'
  324. 'Online': 'Prisijungęs'
  325. 'Scroll down to see new messages': 'Naujos žinutės žemiau'
  326. 'Send': 'Siųsti'
  327. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Jūsų pokalbis buvo uždarytas, nes nieko neatsakėte per %s minučių.'
  328. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Jūsų pokalbis su <strong>%s</strong> buvo uždarytas, nes nieko neatsakėte per %s minučių.'
  329. 'Start new conversation': 'Pradėti naują pokalbį'
  330. 'Today': 'Šiandien'
  331. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Atsiprašome, kad tenka laukti atskymo. Bandykite vėliau arba rašykite el. paštu. Ačiū!'
  332. 'You are on waiting list position <strong>%s</strong>.': 'Esate <strong>%s</strong> eilėje.'
  333. 'nl':
  334. '<strong>Chat</strong> with us!': '<strong>Chat</strong> met ons!'
  335. 'All colleagues are busy.': 'Alle collega\'s zijn bezet.'
  336. 'Chat closed by %s': 'Chat gesloten door %s'
  337. 'Compose your message…': 'Stel je bericht op…'
  338. 'Connecting': 'Verbinden'
  339. 'Connection lost': 'Verbinding verbroken'
  340. 'Connection re-established': 'Verbinding hersteld'
  341. 'Offline': 'Offline'
  342. 'Online': 'Online'
  343. 'Scroll down to see new messages': 'Scroll naar beneden om nieuwe tickets te bekijken'
  344. 'Send': 'Verstuur'
  345. '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.'
  346. '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.'
  347. 'Start new conversation': 'Nieuw gesprek starten'
  348. 'Today': 'Vandaag'
  349. '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!'
  350. 'You are on waiting list position <strong>%s</strong>.': 'Je bevindt zich op wachtlijstpositie <strong>%s</strong>.'
  351. 'pl':
  352. '<strong>Chat</strong> with us!': '<strong>Czatuj</strong> z nami!'
  353. 'All colleagues are busy.': 'Wszyscy agenci są zajęci.'
  354. 'Chat closed by %s': 'Chat zamknięty przez %s'
  355. 'Compose your message…': 'Skomponuj swoją wiadomość…'
  356. 'Connecting': 'Łączenie'
  357. 'Connection lost': 'Utracono połączenie'
  358. 'Connection re-established': 'Ponowne nawiązanie połączenia'
  359. 'Offline': 'Offline'
  360. 'Online': 'Online'
  361. 'Scroll down to see new messages': 'Skroluj w dół, aby zobaczyć wiadomości'
  362. 'Send': 'Wyślij'
  363. '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.'
  364. '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.'
  365. 'Start new conversation': 'Rozpocznij nową rozmowę'
  366. 'Today': 'Dzisiaj'
  367. '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!'
  368. 'You are on waiting list position <strong>%s</strong>.': 'Jesteś na pozycji listy oczekujących <strong>%s</strong>.'
  369. 'pt-br':
  370. '<strong>Chat</strong> with us!': '<strong>Converse</strong> conosco!'
  371. 'All colleagues are busy.': 'Nossos atendentes estão ocupados.'
  372. 'Chat closed by %s': 'Chat encerrado por %s'
  373. 'Compose your message…': 'Escreva sua mensagem…'
  374. 'Connecting': 'Conectando'
  375. 'Connection lost': 'Conexão perdida'
  376. 'Connection re-established': 'Conexão restabelecida'
  377. 'Offline': 'Desconectado'
  378. 'Online': 'Online'
  379. 'Scroll down to see new messages': 'Rolar para baixo para ver novas mensagems'
  380. 'Send': 'Enviar'
  381. '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.'
  382. '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.'
  383. 'Start new conversation': 'Iniciar uma nova conversa'
  384. 'Today': 'Hoje'
  385. '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!'
  386. 'You are on waiting list position <strong>%s</strong>.': 'Você está na posição <strong>%s</strong> da lista de espera.'
  387. 'ro':
  388. '<strong>Chat</strong> with us!': '<strong>Comunică</strong> cu noi!'
  389. 'All colleagues are busy.': 'Toți colegii sunt ocupați momentan.'
  390. 'Chat closed by %s': 'Chat închis de către %s'
  391. 'Compose your message…': 'Compune-ți mesajul…'
  392. 'Connecting': 'Se conectează'
  393. 'Connection lost': 'Conexiune pierdută'
  394. 'Connection re-established': 'Conexiune restabilită'
  395. 'Offline': 'Offline'
  396. 'Online': 'Online'
  397. 'Scroll down to see new messages': 'Derulați în jos pentru a vedea mesajele noi'
  398. 'Send': 'Trimite'
  399. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Deoarece nu ai răspuns în ultimele %s minute, conversația ta a fost închisă.'
  400. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Deoarece nu ai răspuns în ultimele %s minute, conversația ta cu <strong>%s</strong> a fost închisă.'
  401. 'Start new conversation': 'Începe o conversație nouă'
  402. 'Today': 'Azi'
  403. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Ne pare rău, durează mai mult decât ne așteptam să obținem un loc. Te rugăm să încerci din nou mai târziu sau să ne trimiți un email. Mulțumim!'
  404. 'You are on waiting list position <strong>%s</strong>.': 'Aveți poziția <strong>%s</strong> în lista de așteptare.'
  405. 'ru':
  406. '<strong>Chat</strong> with us!': '<strong>Напишите</strong> нам!'
  407. 'All colleagues are busy.': 'Все коллеги заняты.'
  408. 'Chat closed by %s': 'Чат закрыт %s'
  409. 'Compose your message…': 'Составьте сообщение…'
  410. 'Connecting': 'Подключение'
  411. 'Connection lost': 'Подключение потеряно'
  412. 'Connection re-established': 'Подключение восстановлено'
  413. 'Offline': 'Оффлайн'
  414. 'Online': 'В сети'
  415. 'Scroll down to see new messages': 'Прокрутите вниз, чтобы увидеть новые сообщения'
  416. 'Send': 'Отправить'
  417. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Поскольку Вы не ответили в течение последних %s минут, Ваш разговор был закрыт.'
  418. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Поскольку Вы не ответили в течение последних %s минут, Ваш разговор с <strong>%s</strong> был закрыт.'
  419. 'Start new conversation': 'Начать новый разговор'
  420. 'Today': 'Сегодня'
  421. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Извините, получение свободного слота занимает больше времени, чем ожидалось. Пожалуйста, повторите попытку позже или отправьте нам электронное письмо. Благодарим Вас!'
  422. 'You are on waiting list position <strong>%s</strong>.': 'Вы находитесь в списке ожидания <strong>%s</strong>.'
  423. 'sr':
  424. '<strong>Chat</strong> with us!': '<strong>Ћаскајте</strong> са нама!'
  425. 'All colleagues are busy.': 'Све колеге су заузете.'
  426. 'Chat closed by %s': 'Ћаскање затворено од стране %s'
  427. 'Compose your message…': 'Напишите поруку…'
  428. 'Connecting': 'Повезивање'
  429. 'Connection lost': 'Веза је изгубљена'
  430. 'Connection re-established': 'Веза је поново успостављена'
  431. 'Offline': 'Одсутан(а)'
  432. 'Online': 'Доступан(а)'
  433. 'Scroll down to see new messages': 'Скролујте на доле за нове поруке'
  434. 'Send': 'Пошаљи'
  435. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор је завршен.'
  436. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор са <strong>%s</strong> је завршен.'
  437. 'Start new conversation': 'Започни нови разговор'
  438. 'Today': 'Данас'
  439. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Жао нам је, добијање празног термина траје дуже од очекиваног. Молимо покушајте поново касније или нам пошаљите имејл поруку. Хвала вам!'
  440. 'You are on waiting list position <strong>%s</strong>.': 'Ви сте тренутно <strong>%s.</strong> у реду за чекање.'
  441. 'sr-latn-rs':
  442. '<strong>Chat</strong> with us!': '<strong>Ćaskajte</strong> sa nama!'
  443. 'All colleagues are busy.': 'Sve kolege su zauzete.'
  444. 'Chat closed by %s': 'Ćaskanje zatvoreno od strane %s'
  445. 'Compose your message…': 'Napišite poruku…'
  446. 'Connecting': 'Povezivanje'
  447. 'Connection lost': 'Veza je izgubljena'
  448. 'Connection re-established': 'Veza je ponovo uspostavljena'
  449. 'Offline': 'Odsutan(a)'
  450. 'Online': 'Dostupan(a)'
  451. 'Scroll down to see new messages': 'Skrolujte na dole za nove poruke'
  452. 'Send': 'Pošalji'
  453. '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.'
  454. '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.'
  455. 'Start new conversation': 'Započni novi razgovor'
  456. 'Today': 'Danas'
  457. '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!'
  458. 'You are on waiting list position <strong>%s</strong>.': 'Vi ste trenutno <strong>%s.</strong> u redu za čekanje.'
  459. 'sv':
  460. '<strong>Chat</strong> with us!': '<strong>Chatta</strong> med oss!'
  461. 'All colleagues are busy.': 'Alla kollegor är upptagna.'
  462. 'Chat closed by %s': 'Chatt stängd av %s'
  463. 'Compose your message…': 'Skriv ditt meddelande …'
  464. 'Connecting': 'Ansluter'
  465. 'Connection lost': 'Anslutningen försvann'
  466. 'Connection re-established': 'Anslutningen återupprättas'
  467. 'Offline': 'Offline'
  468. 'Online': 'Online'
  469. 'Scroll down to see new messages': 'Bläddra ner för att se nya meddelanden'
  470. 'Send': 'Skicka'
  471. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Din chatt avslutades då du inte svarade inom %s minuter.'
  472. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Chatten stängdes eftersom du inte svarat inom %s minuter i din konversation med <strong>%s</strong>.'
  473. 'Start new conversation': 'Starta ny konversation'
  474. 'Today': 'Idag'
  475. '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!'
  476. 'You are on waiting list position <strong>%s</strong>.': 'Du är på väntelistan som position <strong>%s</strong>.'
  477. 'zh-cn':
  478. '<strong>Chat</strong> with us!': '发起<strong>即时对话</strong>!'
  479. 'All colleagues are busy.': '所有同事都很忙。'
  480. 'Chat closed by %s': '对话已被 %s 关闭'
  481. 'Compose your message…': '编辑您的信息…'
  482. 'Connecting': '连接中'
  483. 'Connection lost': '连接丢失'
  484. 'Connection re-established': '正在重新建立连接'
  485. 'Offline': '离线'
  486. 'Online': '在线'
  487. 'Scroll down to see new messages': '向下滚动以查看新消息'
  488. 'Send': '发送'
  489. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': '"由于您超过 %s 分钟没有任何回复'
  490. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': '"由于您超过 %s 分钟没有回复'
  491. 'Start new conversation': '开始新的会话'
  492. 'Today': '今天'
  493. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
  494. 'You are on waiting list position <strong>%s</strong>.': '您目前的等候位置是第 <strong>%s</strong> 位.'
  495. # ZAMMAD_TRANSLATIONS_END
  496. sessionId: undefined
  497. scrolledToBottom: true
  498. scrollSnapTolerance: 10
  499. richTextFormatKey:
  500. 66: true # b
  501. 73: true # i
  502. 85: true # u
  503. 83: true # s
  504. T: (string, items...) =>
  505. if @options.lang && @options.lang isnt 'en'
  506. if !@translations[@options.lang]
  507. @log.notice "Translation '#{@options.lang}' needed!"
  508. else
  509. translations = @translations[@options.lang]
  510. if !translations[string]
  511. @log.notice "Translation needed for '#{string}'"
  512. string = translations[string] || string
  513. if items
  514. for item in items
  515. string = string.replace(/%s/, item)
  516. string
  517. view: (name) =>
  518. return (options) =>
  519. if !options
  520. options = {}
  521. options.T = @T
  522. options.background = @options.background
  523. options.flat = @options.flat
  524. options.fontSize = @options.fontSize
  525. return window.zammadChatTemplates[name](options)
  526. constructor: (options) ->
  527. @options = $.extend {}, @defaults, options
  528. super(@options)
  529. # fullscreen
  530. @isFullscreen = (window.matchMedia and window.matchMedia('(max-width: 768px)').matches)
  531. @scrollRoot = $(@getScrollRoot())
  532. # check prerequisites
  533. if !$
  534. @state = 'unsupported'
  535. @log.notice 'Chat: no jquery found!'
  536. return
  537. if !window.WebSocket or !sessionStorage
  538. @state = 'unsupported'
  539. @log.notice 'Chat: Browser not supported!'
  540. return
  541. if !@options.chatId
  542. @state = 'unsupported'
  543. @log.error 'Chat: need chatId as option!'
  544. return
  545. # detect language
  546. if !@options.lang
  547. @options.lang = $('html').attr('lang')
  548. if @options.lang
  549. if !@translations[@options.lang]
  550. @log.debug "lang: No #{@options.lang} found, try first two letters"
  551. @options.lang = @options.lang.replace(/-.+?$/, '') # replace "-xx" of xx-xx
  552. @log.debug "lang: #{@options.lang}"
  553. # detect host
  554. @detectHost() if !@options.host
  555. @loadCss()
  556. @io = new Io(@options)
  557. @io.set(
  558. onOpen: @render
  559. onClose: @onWebSocketClose
  560. onMessage: @onWebSocketMessage
  561. onError: @onError
  562. )
  563. @io.connect()
  564. getScrollRoot: ->
  565. return document.scrollingElement if 'scrollingElement' of document
  566. html = document.documentElement
  567. start = html.scrollTop
  568. html.scrollTop = start + 1
  569. end = html.scrollTop
  570. html.scrollTop = start
  571. return if end > start then html else document.body
  572. render: =>
  573. if !@el || !$('.zammad-chat').get(0)
  574. @renderBase()
  575. # disable open button
  576. $(".#{ @options.buttonClass }").addClass @options.inactiveClass
  577. @setAgentOnlineState 'online'
  578. @log.debug 'widget rendered'
  579. @startTimeoutObservers()
  580. @idleTimeout.start()
  581. # get current chat status
  582. @sessionId = sessionStorage.getItem('sessionId')
  583. @send 'chat_status_customer',
  584. session_id: @sessionId
  585. url: window.location.href
  586. renderBase: ->
  587. @el = $(@view('chat')(
  588. title: @options.title,
  589. scrollHint: @options.scrollHint
  590. ))
  591. @options.target.append @el
  592. @input = @el.find('.zammad-chat-input')
  593. # start bindings
  594. @el.find('.js-chat-open').on 'click', @open
  595. @el.find('.js-chat-toggle').on 'click', @toggle
  596. @el.find('.js-chat-status').on 'click', @stopPropagation
  597. @el.find('.zammad-chat-controls').on 'submit', @onSubmit
  598. @el.find('.zammad-chat-body').on 'scroll', @detectScrolledtoBottom
  599. @el.find('.zammad-scroll-hint').on 'click', @onScrollHintClick
  600. @input.on(
  601. keydown: @checkForEnter
  602. input: @onInput
  603. )
  604. @input.on('keydown', (e) =>
  605. richtTextControl = false
  606. if !e.altKey && !e.ctrlKey && e.metaKey
  607. richtTextControl = true
  608. else if !e.altKey && e.ctrlKey && !e.metaKey
  609. richtTextControl = true
  610. if richtTextControl && @richTextFormatKey[ e.keyCode ]
  611. e.preventDefault()
  612. if e.keyCode is 66
  613. document.execCommand('bold')
  614. return true
  615. if e.keyCode is 73
  616. document.execCommand('italic')
  617. return true
  618. if e.keyCode is 85
  619. document.execCommand('underline')
  620. return true
  621. if e.keyCode is 83
  622. document.execCommand('strikeThrough')
  623. return true
  624. )
  625. @input.on('paste', (e) =>
  626. e.stopPropagation()
  627. e.preventDefault()
  628. clipboardData
  629. if e.clipboardData
  630. clipboardData = e.clipboardData
  631. else if window.clipboardData
  632. clipboardData = window.clipboardData
  633. else if e.originalEvent.clipboardData
  634. clipboardData = e.originalEvent.clipboardData
  635. else
  636. throw 'No clipboardData support'
  637. imageInserted = false
  638. if clipboardData && clipboardData.items && clipboardData.items[0]
  639. item = clipboardData.items[0]
  640. if item.kind == 'file' && (item.type == 'image/png' || item.type == 'image/jpeg')
  641. imageFile = item.getAsFile()
  642. reader = new FileReader()
  643. reader.onload = (e) =>
  644. result = e.target.result
  645. img = document.createElement('img')
  646. img.src = result
  647. insert = (dataUrl, width, height, isRetina) =>
  648. # adapt image if we are on retina devices
  649. if @isRetina()
  650. width = width / 2
  651. height = height / 2
  652. result = dataUrl
  653. img = "<img style=\"width: 100%; max-width: #{width}px;\" src=\"#{result}\">"
  654. document.execCommand('insertHTML', false, img)
  655. # resize if to big
  656. @resizeImage(img.src, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
  657. reader.readAsDataURL(imageFile)
  658. imageInserted = true
  659. return if imageInserted
  660. # check existing + paste text for limit
  661. text = undefined
  662. docType = undefined
  663. try
  664. text = clipboardData.getData('text/html')
  665. docType = 'html'
  666. if !text || text.length is 0
  667. docType = 'text'
  668. text = clipboardData.getData('text/plain')
  669. if !text || text.length is 0
  670. docType = 'text2'
  671. text = clipboardData.getData('text')
  672. catch e
  673. console.log('Sorry, can\'t insert markup because browser is not supporting it.')
  674. docType = 'text3'
  675. text = clipboardData.getData('text')
  676. if docType is 'text' || docType is 'text2' || docType is 'text3'
  677. text = '<div>' + text.replace(/\n/g, '</div><div>') + '</div>'
  678. text = text.replace(/<div><\/div>/g, '<div><br></div>')
  679. console.log('p', docType, text)
  680. if docType is 'html'
  681. sanitized = DOMPurify.sanitize(text)
  682. @log.debug 'sanitized HTML clipboard', sanitized
  683. html = $("<div>#{sanitized}</div>")
  684. match = false
  685. htmlTmp = text
  686. regex = new RegExp('<(/w|w)\:[A-Za-z]')
  687. if htmlTmp.match(regex)
  688. match = true
  689. htmlTmp = htmlTmp.replace(regex, '')
  690. regex = new RegExp('<(/o|o)\:[A-Za-z]')
  691. if htmlTmp.match(regex)
  692. match = true
  693. htmlTmp = htmlTmp.replace(regex, '')
  694. if match
  695. html = @wordFilter(html)
  696. #html
  697. html = $(html)
  698. html.contents().each( ->
  699. if @nodeType == 8
  700. $(@).remove()
  701. )
  702. # remove tags, keep content
  703. html.find('a, font, small, time, form, label').replaceWith( ->
  704. $(@).contents()
  705. )
  706. # replace tags with generic div
  707. # New type of the tag
  708. replacementTag = 'div';
  709. # Replace all x tags with the type of replacementTag
  710. html.find('textarea').each( ->
  711. outer = @outerHTML
  712. # Replace opening tag
  713. regex = new RegExp('<' + @tagName, 'i')
  714. newTag = outer.replace(regex, '<' + replacementTag)
  715. # Replace closing tag
  716. regex = new RegExp('</' + @tagName, 'i')
  717. newTag = newTag.replace(regex, '</' + replacementTag)
  718. $(@).replaceWith(newTag)
  719. )
  720. # remove tags & content
  721. html.find('font, img, svg, input, select, button, style, applet, embed, noframes, canvas, script, frame, iframe, meta, link, title, head, fieldset').remove()
  722. @removeAttributes(html)
  723. text = html.html()
  724. # as fallback, insert html via pasteHtmlAtCaret (for IE 11 and lower)
  725. if docType is 'text3'
  726. @pasteHtmlAtCaret(text)
  727. else
  728. document.execCommand('insertHTML', false, text)
  729. true
  730. )
  731. @input.on('drop', (e) =>
  732. e.stopPropagation()
  733. e.preventDefault()
  734. dataTransfer
  735. if window.dataTransfer # ie
  736. dataTransfer = window.dataTransfer
  737. else if e.originalEvent.dataTransfer # other browsers
  738. dataTransfer = e.originalEvent.dataTransfer
  739. else
  740. throw 'No clipboardData support'
  741. x = e.clientX
  742. y = e.clientY
  743. file = dataTransfer.files[0]
  744. # look for images
  745. if file.type.match('image.*')
  746. reader = new FileReader()
  747. reader.onload = (e) =>
  748. result = e.target.result
  749. img = document.createElement('img')
  750. img.src = result
  751. # Insert the image at the carat
  752. insert = (dataUrl, width, height, isRetina) =>
  753. # adapt image if we are on retina devices
  754. if @isRetina()
  755. width = width / 2
  756. height = height / 2
  757. result = dataUrl
  758. img = $("<img style=\"width: 100%; max-width: #{width}px;\" src=\"#{result}\">")
  759. img = img.get(0)
  760. if document.caretPositionFromPoint
  761. pos = document.caretPositionFromPoint(x, y)
  762. range = document.createRange()
  763. range.setStart(pos.offsetNode, pos.offset)
  764. range.collapse()
  765. range.insertNode(img)
  766. else if document.caretRangeFromPoint
  767. range = document.caretRangeFromPoint(x, y)
  768. range.insertNode(img)
  769. else
  770. console.log('could not find carat')
  771. # resize if to big
  772. @resizeImage(img.src, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
  773. reader.readAsDataURL(file)
  774. )
  775. $(window).on('beforeunload', =>
  776. @onLeaveTemporary()
  777. )
  778. $(window).on('hashchange', =>
  779. if @isOpen
  780. if @sessionId
  781. @send 'chat_session_notice',
  782. session_id: @sessionId
  783. message: window.location.href
  784. return
  785. @idleTimeout.start()
  786. )
  787. if @isFullscreen
  788. @input.on
  789. focus: @onFocus
  790. focusout: @onFocusOut
  791. stopPropagation: (event) ->
  792. event.stopPropagation()
  793. checkForEnter: (event) =>
  794. if not @inputDisabled and not event.shiftKey and event.keyCode is 13
  795. event.preventDefault()
  796. @sendMessage()
  797. send: (event, data = {}) =>
  798. data.chat_id = @options.chatId
  799. @io.send(event, data)
  800. onWebSocketMessage: (pipes) =>
  801. for pipe in pipes
  802. @log.debug 'ws:onmessage', pipe
  803. switch pipe.event
  804. when 'chat_error'
  805. @log.notice pipe.data
  806. if pipe.data && pipe.data.state is 'chat_disabled'
  807. @destroy(remove: true)
  808. when 'chat_session_message'
  809. return if pipe.data.self_written
  810. @receiveMessage pipe.data
  811. when 'chat_session_typing'
  812. return if pipe.data.self_written
  813. @onAgentTypingStart()
  814. when 'chat_session_start'
  815. @onConnectionEstablished pipe.data
  816. when 'chat_session_queue'
  817. @onQueueScreen pipe.data
  818. when 'chat_session_closed'
  819. @onSessionClosed pipe.data
  820. when 'chat_session_left'
  821. @onSessionClosed pipe.data
  822. when 'chat_session_notice'
  823. @addStatus @T(pipe.data.message)
  824. when 'chat_status_customer'
  825. switch pipe.data.state
  826. when 'online'
  827. @sessionId = undefined
  828. if !@options.cssAutoload || @cssLoaded
  829. @onReady()
  830. else
  831. @socketReady = true
  832. when 'offline'
  833. @onError 'Zammad Chat: No agent online'
  834. when 'chat_disabled'
  835. @onError 'Zammad Chat: Chat is disabled'
  836. when 'no_seats_available'
  837. @onError "Zammad Chat: Too many clients in queue. Clients in queue: #{pipe.data.queue}"
  838. when 'reconnect'
  839. @onReopenSession pipe.data
  840. onReady: ->
  841. @log.debug 'widget ready for use'
  842. $(".#{ @options.buttonClass }").on('click', @open).removeClass(@options.inactiveClass)
  843. @options.onReady?()
  844. if @options.show
  845. @show()
  846. onError: (message) =>
  847. @log.debug message
  848. @addStatus(message)
  849. $(".#{ @options.buttonClass }").hide()
  850. if @isOpen
  851. @disableInput()
  852. @destroy(remove: false)
  853. else
  854. @destroy(remove: true)
  855. @options.onError?(message)
  856. onReopenSession: (data) =>
  857. @log.debug 'old messages', data.session
  858. @inactiveTimeout.start()
  859. unfinishedMessage = sessionStorage.getItem 'unfinished_message'
  860. # rerender chat history
  861. if data.agent
  862. @onConnectionEstablished(data)
  863. for message in data.session
  864. @renderMessage
  865. message: message.content
  866. id: message.id
  867. from: if message.created_by_id then 'agent' else 'customer'
  868. if unfinishedMessage
  869. @input.html(unfinishedMessage)
  870. # show wait list
  871. if data.position
  872. @onQueue data
  873. @show()
  874. @open()
  875. @scrollToBottom()
  876. if unfinishedMessage
  877. @input.trigger('focus')
  878. onInput: =>
  879. # remove unread-state from messages
  880. @el.find('.zammad-chat-message--unread')
  881. .removeClass 'zammad-chat-message--unread'
  882. sessionStorage.setItem 'unfinished_message', @input.html()
  883. @onTyping()
  884. onFocus: =>
  885. $(window).scrollTop(10)
  886. keyboardShown = $(window).scrollTop() > 0
  887. $(window).scrollTop(0)
  888. if keyboardShown
  889. @log.notice 'virtual keyboard shown'
  890. # on keyboard shown
  891. # can't measure visible area height :(
  892. onFocusOut: ->
  893. # on keyboard hidden
  894. onTyping: ->
  895. # send typing start event only every 1.5 seconds
  896. return if @isTyping && @isTyping > new Date(new Date().getTime() - 1500)
  897. @isTyping = new Date()
  898. @send 'chat_session_typing',
  899. session_id: @sessionId
  900. @inactiveTimeout.start()
  901. onSubmit: (event) =>
  902. event.preventDefault()
  903. @sendMessage()
  904. sendMessage: ->
  905. message = @input.html()
  906. return if !message
  907. @inactiveTimeout.start()
  908. sessionStorage.removeItem 'unfinished_message'
  909. messageElement = @view('message')
  910. message: message
  911. from: 'customer'
  912. id: @_messageCount++
  913. unreadClass: ''
  914. @maybeAddTimestamp()
  915. # add message before message typing loader
  916. if @el.find('.zammad-chat-message--typing').get(0)
  917. @lastAddedType = 'typing-placeholder'
  918. @el.find('.zammad-chat-message--typing').before messageElement
  919. else
  920. @lastAddedType = 'message--customer'
  921. @el.find('.zammad-chat-body').append messageElement
  922. @input.html('')
  923. @scrollToBottom()
  924. # send message event
  925. @send 'chat_session_message',
  926. content: message
  927. id: @_messageCount
  928. session_id: @sessionId
  929. receiveMessage: (data) =>
  930. @inactiveTimeout.start()
  931. # hide writing indicator
  932. @onAgentTypingEnd()
  933. @maybeAddTimestamp()
  934. @renderMessage
  935. message: data.message.content
  936. id: data.id
  937. from: 'agent'
  938. @scrollToBottom showHint: true
  939. renderMessage: (data) =>
  940. @lastAddedType = "message--#{ data.from }"
  941. data.unreadClass = if document.hidden then ' zammad-chat-message--unread' else ''
  942. @el.find('.zammad-chat-body').append @view('message')(data)
  943. open: =>
  944. if @isOpen
  945. @log.debug 'widget already open, block'
  946. return
  947. @isOpen = true
  948. @log.debug 'open widget'
  949. @show()
  950. if !@sessionId
  951. @showLoader()
  952. @el.addClass('zammad-chat-is-open')
  953. remainerHeight = @el.height() - @el.find('.zammad-chat-header').outerHeight()
  954. @el.css 'bottom', -remainerHeight
  955. if !@sessionId
  956. @el.animate { bottom: 0 }, 500, @onOpenAnimationEnd
  957. @send('chat_session_init'
  958. url: window.location.href
  959. )
  960. else
  961. @el.css 'bottom', 0
  962. @onOpenAnimationEnd()
  963. onOpenAnimationEnd: =>
  964. @idleTimeout.stop()
  965. if @isFullscreen
  966. @disableScrollOnRoot()
  967. @options.onOpenAnimationEnd?()
  968. sessionClose: =>
  969. # send close
  970. @send 'chat_session_close',
  971. session_id: @sessionId
  972. # stop timer
  973. @inactiveTimeout.stop()
  974. @waitingListTimeout.stop()
  975. # delete input store
  976. sessionStorage.removeItem 'unfinished_message'
  977. # stop delay of initial queue position
  978. if @onInitialQueueDelayId
  979. clearTimeout(@onInitialQueueDelayId)
  980. @setSessionId undefined
  981. toggle: (event) =>
  982. if @isOpen
  983. @close(event)
  984. else
  985. @open(event)
  986. close: (event) =>
  987. if !@isOpen
  988. @log.debug 'can\'t close widget, it\'s not open'
  989. return
  990. if @initDelayId
  991. clearTimeout(@initDelayId)
  992. if @sessionId
  993. @log.debug 'session close before widget close'
  994. @sessionClose()
  995. @log.debug 'close widget'
  996. event.stopPropagation() if event
  997. if @isFullscreen
  998. @enableScrollOnRoot()
  999. # close window
  1000. remainerHeight = @el.height() - @el.find('.zammad-chat-header').outerHeight()
  1001. @el.animate { bottom: -remainerHeight }, 500, @onCloseAnimationEnd
  1002. onCloseAnimationEnd: =>
  1003. @el.css 'bottom', ''
  1004. @el.removeClass('zammad-chat-is-open')
  1005. @showLoader()
  1006. @el.find('.zammad-chat-welcome').removeClass('zammad-chat-is-hidden')
  1007. @el.find('.zammad-chat-agent').addClass('zammad-chat-is-hidden')
  1008. @el.find('.zammad-chat-agent-status').addClass('zammad-chat-is-hidden')
  1009. @isOpen = false
  1010. @options.onCloseAnimationEnd?()
  1011. @io.reconnect()
  1012. onWebSocketClose: =>
  1013. return if @isOpen
  1014. if @el
  1015. @el.removeClass('zammad-chat-is-shown')
  1016. @el.removeClass('zammad-chat-is-loaded')
  1017. show: ->
  1018. return if @state is 'offline'
  1019. @el.addClass('zammad-chat-is-loaded')
  1020. @el.addClass('zammad-chat-is-shown')
  1021. disableInput: ->
  1022. @inputDisabled = true
  1023. @input.prop('contenteditable', false)
  1024. @el.find('.zammad-chat-send').prop('disabled', true)
  1025. @io.close()
  1026. enableInput: ->
  1027. @inputDisabled = false
  1028. @input.prop('contenteditable', true)
  1029. @el.find('.zammad-chat-send').prop('disabled', false)
  1030. hideModal: ->
  1031. @el.find('.zammad-chat-modal').html ''
  1032. onQueueScreen: (data) =>
  1033. @setSessionId data.session_id
  1034. # delay initial queue position, show connecting first
  1035. show = =>
  1036. @onQueue data
  1037. @waitingListTimeout.start()
  1038. if @initialQueueDelay && !@onInitialQueueDelayId
  1039. @onInitialQueueDelayId = setTimeout(show, @initialQueueDelay)
  1040. return
  1041. # stop delay of initial queue position
  1042. if @onInitialQueueDelayId
  1043. clearTimeout(@onInitialQueueDelayId)
  1044. # show queue position
  1045. show()
  1046. onQueue: (data) =>
  1047. @log.notice 'onQueue', data.position
  1048. @inQueue = true
  1049. @el.find('.zammad-chat-modal').html @view('waiting')
  1050. position: data.position
  1051. onAgentTypingStart: =>
  1052. if @stopTypingId
  1053. clearTimeout(@stopTypingId)
  1054. @stopTypingId = setTimeout(@onAgentTypingEnd, 3000)
  1055. # never display two typing indicators
  1056. return if @el.find('.zammad-chat-message--typing').get(0)
  1057. @maybeAddTimestamp()
  1058. @el.find('.zammad-chat-body').append @view('typingIndicator')()
  1059. # only if typing indicator is shown
  1060. return if !@isVisible(@el.find('.zammad-chat-message--typing'), true)
  1061. @scrollToBottom()
  1062. onAgentTypingEnd: =>
  1063. @el.find('.zammad-chat-message--typing').remove()
  1064. onLeaveTemporary: =>
  1065. return if !@sessionId
  1066. @send 'chat_session_leave_temporary',
  1067. session_id: @sessionId
  1068. maybeAddTimestamp: ->
  1069. timestamp = Date.now()
  1070. if !@lastTimestamp or (timestamp - @lastTimestamp) > @showTimeEveryXMinutes * 60000
  1071. label = @T('Today')
  1072. time = new Date().toTimeString().substr 0,5
  1073. if @lastAddedType is 'timestamp'
  1074. # update last time
  1075. @updateLastTimestamp label, time
  1076. @lastTimestamp = timestamp
  1077. else
  1078. # add new timestamp
  1079. @el.find('.zammad-chat-body').append @view('timestamp')
  1080. label: label
  1081. time: time
  1082. @lastTimestamp = timestamp
  1083. @lastAddedType = 'timestamp'
  1084. @scrollToBottom()
  1085. updateLastTimestamp: (label, time) ->
  1086. return if !@el
  1087. @el.find('.zammad-chat-body')
  1088. .find('.zammad-chat-timestamp')
  1089. .last()
  1090. .replaceWith @view('timestamp')
  1091. label: label
  1092. time: time
  1093. addStatus: (status) ->
  1094. return if !@el
  1095. @maybeAddTimestamp()
  1096. @el.find('.zammad-chat-body').append @view('status')
  1097. status: status
  1098. @scrollToBottom()
  1099. detectScrolledtoBottom: =>
  1100. scrollBottom = @el.find('.zammad-chat-body').scrollTop() + @el.find('.zammad-chat-body').outerHeight()
  1101. @scrolledToBottom = Math.abs(scrollBottom - @el.find('.zammad-chat-body').prop('scrollHeight')) <= @scrollSnapTolerance
  1102. @el.find('.zammad-scroll-hint').addClass('is-hidden') if @scrolledToBottom
  1103. showScrollHint: ->
  1104. @el.find('.zammad-scroll-hint').removeClass('is-hidden')
  1105. # compensate scroll
  1106. @el.find('.zammad-chat-body').scrollTop(@el.find('.zammad-chat-body').scrollTop() + @el.find('.zammad-scroll-hint').outerHeight())
  1107. onScrollHintClick: =>
  1108. # animate scroll
  1109. @el.find('.zammad-chat-body').animate({scrollTop: @el.find('.zammad-chat-body').prop('scrollHeight')}, 300)
  1110. scrollToBottom: ({ showHint } = { showHint: false }) ->
  1111. if @scrolledToBottom
  1112. @el.find('.zammad-chat-body').scrollTop($('.zammad-chat-body').prop('scrollHeight'))
  1113. else if showHint
  1114. @showScrollHint()
  1115. destroy: (params = {}) =>
  1116. @log.debug 'destroy widget', params
  1117. @setAgentOnlineState 'offline'
  1118. if params.remove && @el
  1119. @el.remove()
  1120. # Remove button, because it can no longer be used.
  1121. $(".#{ @options.buttonClass }").hide()
  1122. # stop all timer
  1123. if @waitingListTimeout
  1124. @waitingListTimeout.stop()
  1125. if @inactiveTimeout
  1126. @inactiveTimeout.stop()
  1127. if @idleTimeout
  1128. @idleTimeout.stop()
  1129. # stop ws connection
  1130. @io.close()
  1131. reconnect: =>
  1132. # set status to connecting
  1133. @log.notice 'reconnecting'
  1134. @disableInput()
  1135. @lastAddedType = 'status'
  1136. @setAgentOnlineState 'connecting'
  1137. @addStatus @T('Connection lost')
  1138. onConnectionReestablished: =>
  1139. # set status back to online
  1140. @lastAddedType = 'status'
  1141. @setAgentOnlineState 'online'
  1142. @addStatus @T('Connection re-established')
  1143. @options.onConnectionReestablished?()
  1144. onSessionClosed: (data) ->
  1145. @addStatus @T('Chat closed by %s', data.realname)
  1146. @disableInput()
  1147. @setAgentOnlineState 'offline'
  1148. @inactiveTimeout.stop()
  1149. @options.onSessionClosed?(data)
  1150. setSessionId: (id) =>
  1151. @sessionId = id
  1152. if id is undefined
  1153. sessionStorage.removeItem 'sessionId'
  1154. else
  1155. sessionStorage.setItem 'sessionId', id
  1156. onConnectionEstablished: (data) =>
  1157. # stop delay of initial queue position
  1158. if @onInitialQueueDelayId
  1159. clearTimeout @onInitialQueueDelayId
  1160. @inQueue = false
  1161. if data.agent
  1162. @agent = data.agent
  1163. if data.session_id
  1164. @setSessionId data.session_id
  1165. # empty old messages
  1166. @el.find('.zammad-chat-body').html('')
  1167. @el.find('.zammad-chat-agent').html @view('agent')
  1168. agent: @agent
  1169. @enableInput()
  1170. @hideModal()
  1171. @el.find('.zammad-chat-welcome').addClass('zammad-chat-is-hidden')
  1172. @el.find('.zammad-chat-agent').removeClass('zammad-chat-is-hidden')
  1173. @el.find('.zammad-chat-agent-status').removeClass('zammad-chat-is-hidden')
  1174. @input.trigger('focus') if not @isFullscreen
  1175. @setAgentOnlineState 'online'
  1176. @waitingListTimeout.stop()
  1177. @idleTimeout.stop()
  1178. @inactiveTimeout.start()
  1179. @options.onConnectionEstablished?(data)
  1180. showCustomerTimeout: ->
  1181. @el.find('.zammad-chat-modal').html @view('customer_timeout')
  1182. agent: @agent.name
  1183. delay: @options.inactiveTimeout
  1184. reload = ->
  1185. location.reload()
  1186. @el.find('.js-restart').on 'click', reload
  1187. @sessionClose()
  1188. showWaitingListTimeout: ->
  1189. @el.find('.zammad-chat-modal').html @view('waiting_list_timeout')
  1190. delay: @options.watingListTimeout
  1191. reload = ->
  1192. location.reload()
  1193. @el.find('.js-restart').on 'click', reload
  1194. @sessionClose()
  1195. showLoader: ->
  1196. @el.find('.zammad-chat-modal').html @view('loader')()
  1197. setAgentOnlineState: (state) =>
  1198. @state = state
  1199. return if !@el
  1200. capitalizedState = state.charAt(0).toUpperCase() + state.slice(1)
  1201. @el
  1202. .find('.zammad-chat-agent-status')
  1203. .attr('data-status', state)
  1204. .text @T(capitalizedState) # @T('Online') @T('Offline')
  1205. detectHost: ->
  1206. protocol = 'ws://'
  1207. if scriptProtocol is 'https'
  1208. protocol = 'wss://'
  1209. @options.host = "#{ protocol }#{ scriptHost }/ws"
  1210. loadCss: ->
  1211. return if !@options.cssAutoload
  1212. url = @options.cssUrl
  1213. if !url
  1214. url = @options.host
  1215. .replace(/^wss/i, 'https')
  1216. .replace(/^ws/i, 'http')
  1217. .replace(/\/ws$/i, '') # WebSocket may run on example.com/ws path
  1218. url += '/assets/chat/chat.css'
  1219. @log.debug "load css from '#{url}'"
  1220. styles = "@import url('#{url}');"
  1221. newSS = document.createElement('link')
  1222. newSS.onload = @onCssLoaded
  1223. newSS.rel = 'stylesheet'
  1224. newSS.href = 'data:text/css,' + escape(styles)
  1225. document.getElementsByTagName('head')[0].appendChild(newSS)
  1226. onCssLoaded: =>
  1227. @cssLoaded = true
  1228. if @socketReady
  1229. @onReady()
  1230. @options.onCssLoaded?()
  1231. startTimeoutObservers: =>
  1232. @idleTimeout = new Timeout(
  1233. logPrefix: 'idleTimeout'
  1234. debug: @options.debug
  1235. timeout: @options.idleTimeout
  1236. timeoutIntervallCheck: @options.idleTimeoutIntervallCheck
  1237. callback: =>
  1238. @log.debug 'Idle timeout reached, hide widget', new Date
  1239. @destroy(remove: true)
  1240. )
  1241. @inactiveTimeout = new Timeout(
  1242. logPrefix: 'inactiveTimeout'
  1243. debug: @options.debug
  1244. timeout: @options.inactiveTimeout
  1245. timeoutIntervallCheck: @options.inactiveTimeoutIntervallCheck
  1246. callback: =>
  1247. @log.debug 'Inactive timeout reached, show timeout screen.', new Date
  1248. @showCustomerTimeout()
  1249. @destroy(remove: false)
  1250. )
  1251. @waitingListTimeout = new Timeout(
  1252. logPrefix: 'waitingListTimeout'
  1253. debug: @options.debug
  1254. timeout: @options.waitingListTimeout
  1255. timeoutIntervallCheck: @options.waitingListTimeoutIntervallCheck
  1256. callback: =>
  1257. @log.debug 'Waiting list timeout reached, show timeout screen.', new Date
  1258. @showWaitingListTimeout()
  1259. @destroy(remove: false)
  1260. )
  1261. disableScrollOnRoot: ->
  1262. @rootScrollOffset = @scrollRoot.scrollTop()
  1263. @scrollRoot.css
  1264. overflow: 'hidden'
  1265. position: 'fixed'
  1266. enableScrollOnRoot: ->
  1267. @scrollRoot.scrollTop @rootScrollOffset
  1268. @scrollRoot.css
  1269. overflow: ''
  1270. position: ''
  1271. # based on https://github.com/customd/jquery-visible/blob/master/jquery.visible.js
  1272. # to have not dependency, port to coffeescript
  1273. isVisible: (el, partial, hidden, direction) ->
  1274. return if el.length < 1
  1275. $w = $(window)
  1276. $t = if el.length > 1 then el.eq(0) else el
  1277. t = $t.get(0)
  1278. vpWidth = $w.width()
  1279. vpHeight = $w.height()
  1280. direction = if direction then direction else 'both'
  1281. clientSize = if hidden is true then t.offsetWidth * t.offsetHeight else true
  1282. if typeof t.getBoundingClientRect is 'function'
  1283. # Use this native browser method, if available.
  1284. rec = t.getBoundingClientRect()
  1285. tViz = rec.top >= 0 && rec.top < vpHeight
  1286. bViz = rec.bottom > 0 && rec.bottom <= vpHeight
  1287. lViz = rec.left >= 0 && rec.left < vpWidth
  1288. rViz = rec.right > 0 && rec.right <= vpWidth
  1289. vVisible = if partial then tViz || bViz else tViz && bViz
  1290. hVisible = if partial then lViz || rViz else lViz && rViz
  1291. if direction is 'both'
  1292. return clientSize && vVisible && hVisible
  1293. else if direction is 'vertical'
  1294. return clientSize && vVisible
  1295. else if direction is 'horizontal'
  1296. return clientSize && hVisible
  1297. else
  1298. viewTop = $w.scrollTop()
  1299. viewBottom = viewTop + vpHeight
  1300. viewLeft = $w.scrollLeft()
  1301. viewRight = viewLeft + vpWidth
  1302. offset = $t.offset()
  1303. _top = offset.top
  1304. _bottom = _top + $t.height()
  1305. _left = offset.left
  1306. _right = _left + $t.width()
  1307. compareTop = if partial is true then _bottom else _top
  1308. compareBottom = if partial is true then _top else _bottom
  1309. compareLeft = if partial is true then _right else _left
  1310. compareRight = if partial is true then _left else _right
  1311. if direction is 'both'
  1312. return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft))
  1313. else if direction is 'vertical'
  1314. return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop))
  1315. else if direction is 'horizontal'
  1316. return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft))
  1317. isRetina: ->
  1318. if window.matchMedia
  1319. mq = window.matchMedia('only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)')
  1320. return (mq && mq.matches || (window.devicePixelRatio > 1))
  1321. false
  1322. resizeImage: (dataURL, x = 'auto', y = 'auto', sizeFactor = 1, type, quallity, callback, force = true) ->
  1323. # load image from data url
  1324. imageObject = new Image()
  1325. imageObject.onload = ->
  1326. imageWidth = imageObject.width
  1327. imageHeight = imageObject.height
  1328. console.log('ImageService', 'current size', imageWidth, imageHeight)
  1329. if y is 'auto' && x is 'auto'
  1330. x = imageWidth
  1331. y = imageHeight
  1332. # get auto dimensions
  1333. if y is 'auto'
  1334. factor = imageWidth / x
  1335. y = imageHeight / factor
  1336. if x is 'auto'
  1337. factor = imageWidth / y
  1338. x = imageHeight / factor
  1339. # check if resize is needed
  1340. resize = false
  1341. if x < imageWidth || y < imageHeight
  1342. resize = true
  1343. x = x * sizeFactor
  1344. y = y * sizeFactor
  1345. else
  1346. x = imageWidth
  1347. y = imageHeight
  1348. # create canvas and set dimensions
  1349. canvas = document.createElement('canvas')
  1350. canvas.width = x
  1351. canvas.height = y
  1352. # draw image on canvas and set image dimensions
  1353. context = canvas.getContext('2d')
  1354. context.drawImage(imageObject, 0, 0, x, y)
  1355. # set quallity based on image size
  1356. if quallity == 'auto'
  1357. if x < 200 && y < 200
  1358. quallity = 1
  1359. else if x < 400 && y < 400
  1360. quallity = 0.9
  1361. else if x < 600 && y < 600
  1362. quallity = 0.8
  1363. else if x < 900 && y < 900
  1364. quallity = 0.7
  1365. else
  1366. quallity = 0.6
  1367. # execute callback with resized image
  1368. newDataUrl = canvas.toDataURL(type, quallity)
  1369. if resize
  1370. console.log('ImageService', 'resize', x/sizeFactor, y/sizeFactor, quallity, (newDataUrl.length * 0.75)/1024/1024, 'in mb')
  1371. callback(newDataUrl, x/sizeFactor, y/sizeFactor, true)
  1372. return
  1373. console.log('ImageService', 'no resize', x, y, quallity, (newDataUrl.length * 0.75)/1024/1024, 'in mb')
  1374. callback(newDataUrl, x, y, false)
  1375. # load image from data url
  1376. imageObject.src = dataURL
  1377. # taken from https://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div/6691294#6691294
  1378. pasteHtmlAtCaret: (html) ->
  1379. sel = undefined
  1380. range = undefined
  1381. if window.getSelection
  1382. sel = window.getSelection()
  1383. if sel.getRangeAt && sel.rangeCount
  1384. range = sel.getRangeAt(0)
  1385. range.deleteContents()
  1386. el = document.createElement('div')
  1387. el.innerHTML = html
  1388. frag = document.createDocumentFragment(node, lastNode)
  1389. while node = el.firstChild
  1390. lastNode = frag.appendChild(node)
  1391. range.insertNode(frag)
  1392. if lastNode
  1393. range = range.cloneRange()
  1394. range.setStartAfter(lastNode)
  1395. range.collapse(true)
  1396. sel.removeAllRanges()
  1397. sel.addRange(range)
  1398. else if document.selection && document.selection.type != 'Control'
  1399. document.selection.createRange().pasteHTML(html)
  1400. # (C) sbrin - https://github.com/sbrin
  1401. # https://gist.github.com/sbrin/6801034
  1402. wordFilter: (editor) ->
  1403. content = editor.html()
  1404. # Word comments like conditional comments etc
  1405. content = content.replace(/<!--[\s\S]+?-->/gi, '')
  1406. # Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
  1407. # MS Office namespaced tags, and a few other tags
  1408. content = content.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '')
  1409. # Convert <s> into <strike> for line-though
  1410. content = content.replace(/<(\/?)s>/gi, '<$1strike>')
  1411. # Replace nbsp entites to char since it's easier to handle
  1412. # content = content.replace(/&nbsp;/gi, "\u00a0")
  1413. content = content.replace(/&nbsp;/gi, ' ')
  1414. # Convert <span style="mso-spacerun:yes">___</span> to string of alternating
  1415. # breaking/non-breaking spaces of same length
  1416. #content = content.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, (str, spaces) ->
  1417. # return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ''
  1418. #)
  1419. editor.html(content)
  1420. # Parse out list indent level for lists
  1421. $('p', editor).each( ->
  1422. str = $(@).attr('style')
  1423. matches = /mso-list:\w+ \w+([0-9]+)/.exec(str)
  1424. if matches
  1425. $(@).data('_listLevel', parseInt(matches[1], 10))
  1426. )
  1427. # Parse Lists
  1428. last_level = 0
  1429. pnt = null
  1430. $('p', editor).each(->
  1431. cur_level = $(@).data('_listLevel')
  1432. if cur_level != undefined
  1433. txt = $(@).text()
  1434. list_tag = '<ul></ul>'
  1435. if (/^\s*\w+\./.test(txt))
  1436. matches = /([0-9])\./.exec(txt)
  1437. if matches
  1438. start = parseInt(matches[1], 10)
  1439. list_tag = start>1 ? '<ol start="' + start + '"></ol>' : '<ol></ol>'
  1440. else
  1441. list_tag = '<ol></ol>'
  1442. if cur_level > last_level
  1443. if last_level == 0
  1444. $(@).before(list_tag)
  1445. pnt = $(@).prev()
  1446. else
  1447. pnt = $(list_tag).appendTo(pnt)
  1448. if cur_level < last_level
  1449. for i in [i..last_level-cur_level]
  1450. pnt = pnt.parent()
  1451. $('span:first', @).remove()
  1452. pnt.append('<li>' + $(@).html() + '</li>')
  1453. $(@).remove()
  1454. last_level = cur_level
  1455. else
  1456. last_level = 0
  1457. )
  1458. $('[style]', editor).removeAttr('style')
  1459. $('[align]', editor).removeAttr('align')
  1460. $('span', editor).replaceWith(->
  1461. $(@).contents()
  1462. )
  1463. $('span:empty', editor).remove()
  1464. $("[class^='Mso']", editor).removeAttr('class')
  1465. $('p:empty', editor).remove()
  1466. editor
  1467. removeAttribute: (element) ->
  1468. return if !element
  1469. $element = $(element)
  1470. for att in element.attributes
  1471. if att && att.name
  1472. element.removeAttribute(att.name)
  1473. #$element.removeAttr(att.name)
  1474. $element.removeAttr('style')
  1475. .removeAttr('class')
  1476. .removeAttr('lang')
  1477. .removeAttr('type')
  1478. .removeAttr('align')
  1479. .removeAttr('id')
  1480. .removeAttr('wrap')
  1481. .removeAttr('title')
  1482. removeAttributes: (html, parent = true) =>
  1483. if parent
  1484. html.each((index, element) => @removeAttribute(element) )
  1485. html.find('*').each((index, element) => @removeAttribute(element) )
  1486. html
  1487. window.ZammadChat = ZammadChat