This repository has been archived by the owner on Jun 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 75
/
client.js
485 lines (412 loc) · 13.8 KB
/
client.js
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
var converter = new showdown.Converter();
converter.setOption('openLinksInNewWindow', true);
var Botkit = {
config: {
ws_url: (location.protocol === 'https:' ? 'wss' : 'ws') + '://' + location.host,
reconnect_timeout: 3000,
max_reconnect: 5
},
options: {
sound: false,
use_sockets: true
},
reconnect_count: 0,
guid: null,
current_user: null,
on: function(event, handler) {
this.message_window.addEventListener(event, function(evt) {
handler(evt.detail);
});
},
trigger: function(event, details) {
var event = new CustomEvent(event, {
detail: details
});
this.message_window.dispatchEvent(event);
},
request: function(url, body) {
var that = this;
return new Promise(function(resolve, reject) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
var response = xmlhttp.responseText;
var message = null;
try {
message = JSON.parse(response);
} catch (err) {
reject(err);
return;
}
resolve(message);
} else {
reject(new Error('status_' + xmlhttp.status));
}
}
};
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(body));
});
},
send: function(text, e) {
var that = this;
if (e) e.preventDefault();
if (!text) {
return;
}
var message = {
type: 'outgoing',
text: text
};
this.clearReplies();
that.renderMessage(message);
that.deliverMessage({
type: 'message',
text: text,
user: this.guid,
channel: this.options.use_sockets ? 'socket' : 'webhook'
});
this.input.value = '';
this.trigger('sent', message);
return false;
},
deliverMessage: function(message) {
if (this.options.use_sockets) {
this.socket.send(JSON.stringify(message));
} else {
this.webhook(message);
}
},
getHistory: function(guid) {
var that = this;
if (that.guid) {
that.request('/botkit/history', {
user: that.guid
}).then(function(history) {
if (history.success) {
that.trigger('history_loaded', history.history);
} else {
that.trigger('history_error', new Error(history.error));
}
}).catch(function(err) {
that.trigger('history_error', err);
});
}
},
webhook: function(message) {
var that = this;
that.request('/botkit/receive', message).then(function(message) {
that.trigger(message.type, message);
}).catch(function(err) {
that.trigger('webhook_error', err);
});
},
connect: function(user) {
var that = this;
if (user && user.id) {
Botkit.setCookie('botkit_guid', user.id, 1);
user.timezone_offset = new Date().getTimezoneOffset();
that.current_user = user;
console.log('CONNECT WITH USER', user);
}
// connect to the chat server!
if (that.options.use_sockets) {
that.connectWebsocket(that.config.ws_url);
} else {
that.connectWebhook();
}
},
connectWebhook: function() {
var that = this;
if (Botkit.getCookie('botkit_guid')) {
that.guid = Botkit.getCookie('botkit_guid');
connectEvent = 'welcome_back';
} else {
that.guid = that.generate_guid();
Botkit.setCookie('botkit_guid', that.guid, 1);
}
that.getHistory();
// connect immediately
that.trigger('connected', {});
that.webhook({
type: connectEvent,
user: that.guid,
channel: 'webhook',
});
},
connectWebsocket: function(ws_url) {
var that = this;
// Create WebSocket connection.
that.socket = new WebSocket(ws_url);
var connectEvent = 'hello';
if (Botkit.getCookie('botkit_guid')) {
that.guid = Botkit.getCookie('botkit_guid');
connectEvent = 'welcome_back';
} else {
that.guid = that.generate_guid();
Botkit.setCookie('botkit_guid', that.guid, 1);
}
that.getHistory();
// Connection opened
that.socket.addEventListener('open', function(event) {
console.log('CONNECTED TO SOCKET');
that.reconnect_count = 0;
that.trigger('connected', event);
that.deliverMessage({
type: connectEvent,
user: that.guid,
channel: 'socket',
user_profile: that.current_user ? that.current_user : null,
});
});
that.socket.addEventListener('error', function(event) {
console.error('ERROR', event);
});
that.socket.addEventListener('close', function(event) {
console.log('SOCKET CLOSED!');
that.trigger('disconnected', event);
if (that.reconnect_count < that.config.max_reconnect) {
setTimeout(function() {
console.log('RECONNECTING ATTEMPT ', ++that.reconnect_count);
that.connectWebsocket(that.config.ws_url);
}, that.config.reconnect_timeout);
} else {
that.message_window.className = 'offline';
}
});
// Listen for messages
that.socket.addEventListener('message', function(event) {
var message = null;
try {
message = JSON.parse(event.data);
} catch (err) {
that.trigger('socket_error', err);
return;
}
that.trigger(message.type, message);
});
},
clearReplies: function() {
this.replies.innerHTML = '';
},
quickReply: function(payload) {
this.send(payload);
},
focus: function() {
this.input.focus();
},
renderMessage: function(message) {
var that = this;
if (!that.next_line) {
that.next_line = document.createElement('div');
that.message_list.appendChild(that.next_line);
}
if (message.text) {
message.html = converter.makeHtml(message.text);
}
that.next_line.innerHTML = that.message_template({
message: message
});
if (!message.isTyping) {
delete(that.next_line);
}
},
triggerScript: function(script, thread) {
this.deliverMessage({
type: 'trigger',
user: this.guid,
channel: 'socket',
script: script,
thread: thread
});
},
identifyUser: function(user) {
user.timezone_offset = new Date().getTimezoneOffset();
this.guid = user.id;
Botkit.setCookie('botkit_guid', user.id, 1);
this.current_user = user;
this.deliverMessage({
type: 'identify',
user: this.guid,
channel: 'socket',
user_profile: user,
});
},
receiveCommand: function(event) {
switch (event.data.name) {
case 'trigger':
// tell Botkit to trigger a specific script/thread
console.log('TRIGGER', event.data.script, event.data.thread);
Botkit.triggerScript(event.data.script, event.data.thread);
break;
case 'identify':
// link this account info to this user
console.log('IDENTIFY', event.data.user);
Botkit.identifyUser(event.data.user);
break;
case 'connect':
// link this account info to this user
Botkit.connect(event.data.user);
break;
default:
console.log('UNKNOWN COMMAND', event.data);
}
},
sendEvent: function(event) {
if (this.parent_window) {
this.parent_window.postMessage(event, '*');
}
},
setCookie: function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
},
getCookie: function(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
},
generate_guid: function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
},
boot: function(user) {
console.log('Booting up');
var that = this;
that.message_window = document.getElementById("message_window");
that.message_list = document.getElementById("message_list");
var source = document.getElementById('message_template').innerHTML;
that.message_template = Handlebars.compile(source);
that.replies = document.getElementById('message_replies');
that.input = document.getElementById('messenger_input');
that.focus();
that.on('connected', function() {
that.message_window.className = 'connected';
that.input.disabled = false;
that.sendEvent({
name: 'connected'
});
})
that.on('disconnected', function() {
that.message_window.className = 'disconnected';
that.input.disabled = true;
});
that.on('webhook_error', function(err) {
alert('Error sending message!');
console.error('Webhook Error', err);
});
that.on('typing', function() {
that.clearReplies();
that.renderMessage({
isTyping: true
});
});
that.on('sent', function() {
if (that.options.sound) {
var audio = new Audio('sent.mp3');
audio.play();
}
});
that.on('message', function() {
if (that.options.sound) {
var audio = new Audio('beep.mp3');
audio.play();
}
});
that.on('message', function(message) {
that.renderMessage(message);
});
that.on('message', function(message) {
if (message.goto_link) {
window.location = message.goto_link;
}
});
that.on('message', function(message) {
that.clearReplies();
if (message.quick_replies) {
var list = document.createElement('ul');
var elements = [];
for (var r = 0; r < message.quick_replies.length; r++) {
(function(reply) {
var li = document.createElement('li');
var el = document.createElement('a');
el.innerHTML = reply.title;
el.href = '#';
el.onclick = function() {
that.quickReply(reply.payload);
}
li.appendChild(el);
list.appendChild(li);
elements.push(li);
})(message.quick_replies[r]);
}
that.replies.appendChild(list);
// uncomment this code if you want your quick replies to scroll horizontally instead of stacking
// var width = 0;
// // resize this element so it will scroll horizontally
// for (var e = 0; e < elements.length; e++) {
// width = width + elements[e].offsetWidth + 18;
// }
// list.style.width = width + 'px';
if (message.disable_input) {
that.input.disabled = true;
} else {
that.input.disabled = false;
}
} else {
that.input.disabled = false;
}
});
that.on('history_loaded', function(history) {
if (history) {
for (var m = 0; m < history.length; m++) {
that.renderMessage({
text: history[m].text,
type: history[m].type == 'message_received' ? 'outgoing' : 'incoming', // set appropriate CSS class
});
}
}
});
if (window.self !== window.top) {
// this is embedded in an iframe.
// send a message to the master frame to tell it that the chat client is ready
// do NOT automatically connect... rather wait for the connect command.
that.parent_window = window.parent;
window.addEventListener("message", that.receiveCommand, false);
that.sendEvent({
type: 'event',
name: 'booted'
});
console.log('Messenger booted in embedded mode');
} else {
console.log('Messenger booted in stand-alone mode');
// this is a stand-alone client. connect immediately.
that.connect(user);
}
return that;
}
};
(function() {
// your page initialization code here
// the DOM will be available here
Botkit.boot();
})();