-
Notifications
You must be signed in to change notification settings - Fork 152
/
chat.js
407 lines (289 loc) · 9.87 KB
/
chat.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
/******************************************************************************
*
* Copyright 2012-2014 Tavendo GmbH.
*
* Licensed under the Apache 2.0 license
* http://www.apache.org/licenses/LICENSE-2.0.html
*
******************************************************************************/
"use strict";
var demoRealm = "crossbardemo";
var demoPrefix = "io.crossbar.demo";
// the URL of the WAMP Router (Crossbar.io)
//
var wsuri;
if (document.location.origin == "file://") {
wsuri = "ws://127.0.0.1:8080";
} else {
wsuri = (document.location.protocol === "http:" ? "ws:" : "wss:") + "//" +
document.location.host + "/ws";
}
var httpUri;
if (document.location.origin == "file://") {
httpUri = "http://127.0.0.1:8080/lp";
} else {
httpUri = (document.location.protocol === "http:" ? "http:" : "https:") + "//" +
document.location.host + "/lp";
}
var initialChannel = null,
currentSubscription = null,
presetNicks = ["Nick", "Knatterton", "Micky", "Maus", "Donald", "Bruce", "Wayne", "Clark", "Kent", "Sarah", "Connor", "Mary", "Shelley", "Rosemary", "Wilma", "Louis", "Selina", "Barbara", "Gordon", "Herbert", "The Count"],
nick,
oldNick,
assignedNicks = {},
nickColors = ["black", "orange", "green", "blue", "red"],
sess = null,
retryCount = 0,
retryDelay = 2,
oldHash = window.location.href,
isReconnect = false;
var chatWindow = null;
updateStatusline("Not connected.");
// check for controller channel id in the URL
var windowUrl = document.URL; // string
if (windowUrl.indexOf('#') !== -1) {
initialChannel = windowUrl.split('#')[1];
} else {
window.location.hash = "ch1";
}
setupDemo();
connect();
function switchChannel(oldChannelID, newChannelID) {
console.log("switchChannel called");
// either oldChannelID or newChannelID could be null = start page with no demo selected
if (oldChannelID && currentSubscription !== null && currentSubscription.session.isOpen === true) {
currentSubscription.unsubscribe().then(
function() {
console.log("successful unsubscribe");
},
function(error) {
console.log("unsubscribe error ", error);
}
);
}
sess.subscribe("api:" + newChannelID, onMessage).then(
function(subscription) {
console.log("subscriped", subscription);
currentSubscription = subscription;
},
function(error) {
console.log("subscription failed ", error);
}
);
// clear messages box
$("#messages_box").html('');
// set the second instance link
$('#secondInstance').attr('href', window.location.pathname + '#' + newChannelID);
// clear the unread chat message indicator if set
$("#show_chat_window").removeClass("message_received");
}
function updateStatusline(status) {
$(".statusline").html(status);
};
function connect() {
// the WAMP connection to the Router
//
var connection = new autobahn.Connection({
// url: wsuri,
transports: [
{
'type': 'websocket',
'url': wsuri
},
{
'type': 'longpoll',
'url': httpUri
}
],
realm: "crossbardemo"
});
connection.onopen = function (session, details) {
sess = session;
sess.prefix("api", demoPrefix + ".chat");
if (details.x_cb_node_id) {
updateStatusline("Connected to node <strong>" + details.x_cb_node_id + "</strong> at " + wsuri);
} else {
updateStatusline("Connected to " + wsuri);
}
console.log("initialChannel", initialChannel, isReconnect);
// if window url contained channel id, trigger the necessary actions
if (initialChannel && !isReconnect) {
switchChannel(null, initialChannel);
changeChannelIndicators(initialChannel);
isReconnect = true;
}
};
connection.onclose = function(reason, details) {
sess = null;
console.log("connection closed ", reason, details);
if (details.will_retry) {
updateStatusline("Trying to reconnect in " + parseInt(details.retry_delay) + " s.");
} else {
updateStatusline("Disconnected");
}
}
connection.open();
}
function onHashChanged(evt) {
console.log("onHashChanged", oldHash);
var newUrl = window.location.href;
var oldUrl = oldHash;
oldHash = newUrl;
var newChannelID;
var oldChannelID;
if (newUrl.indexOf('#') !== -1) {
newChannelID = newUrl.split('#')[1];
}
else {
newChannelID = null;
}
if (oldUrl.indexOf('#') !== -1) {
oldChannelID = oldUrl.split('#')[1];
}
else {
oldChannelID = null;
}
switchChannel ( oldChannelID, newChannelID );
changeChannelIndicators ( newChannelID );
}
function changeChannelIndicators ( newChannelID ) {
// indicate presently picked channel via highlighting
var channelSelectors = $(".chat_channel_selector"),
currentChannel;
for (var i = 0; i < channelSelectors.length; i++) {
if ("ch" + (i + 1) == newChannelID) {
$(channelSelectors[i]).addClass("channel_selected");
currentChannel = i + 1;
}
else if ($(channelSelectors[i]).hasClass("channel_selected")) {
$(channelSelectors[i]).removeClass("channel_selected");
}
}
// set the channel title on the chat window
$("#channel_title").text("Channel " + currentChannel);
}
function setupDemo() {
chatWindow = $("#chat_window");
// add 'onhashchange' event to trigger the channel change + chat window display
window.onhashchange = onHashChanged;
// initial timed display of the chat window
window.setTimeout(function() { $("#chat_window").toggle(300) }, 2300);
// set up show + hide chat window handlers
document.getElementById("show_chat_window").onclick = function () {
$("#chat_window").toggle(300);
var messagesBox = $("#messages_box")[0];
// scroll messages box
messagesBox.scrollTop = messagesBox.scrollHeight;
};
document.getElementById("hide_chat_window").onclick = function () {
$("#chat_window").toggle(300);
$("#show_chat_window").removeClass("message_received");
};
// set random preset nick
nick = $("#nick");
var randomNick = presetNicks[Math.floor(Math.random() * presetNicks.length)];
nick.val(randomNick);
oldNick = nick.val();
getNickColor(nick.val()); // assigns a color to the nick
// set 'enter' on chat message textarea sends message
var messageInput = $("#message_input")[0];
messageInput.onkeypress = function(e) {
var e = e || event; // IE8 fix, since here the window.event, not the event itself contains the keyCode
if (e.keyCode === 13) {
console.log("enter");
sendMessage(messageInput);
return false;
};
};
$("#helpButton").click(function() {
$(".info_bar").toggle();
if ($("#chat_window:visible").length) {
$("#chat_window").toggle(300);
}
});
}
function sendMessage(messageInput) {
console.log("send message");
var message = messageInput.value;
var currentNick = nick.val();
// check if own nick has changed since last send
if (currentNick !== oldNick) {
changeOwnNick(currentNick);
}
var channel;
var windowUrl = document.URL;
if (windowUrl.indexOf('#') !== -1) {
channel = windowUrl.split('#')[1];
}
var payload = {};
payload.message = message;
payload.nick = currentNick;
sess.publish("api:" + channel, [payload], {}, {exclude_me: false});
// clear the message input
messageInput.value = '';
messageInput.placeholder = '';
};
function changeOwnNick(currentNick) {
// get the color value for the old nick
var nickColor = assignedNicks[oldNick];
// delete the old nick
delete assignedNicks[oldNick];
// add new nick with the old color
assignedNicks[currentNick] = nickColor;
};
function getNickColor(nickString) {
// check if nickstring has color assigned, and return this
if (!(nickString in assignedNicks)) {
// count the nicks
var nickCounter = 0;
for (var i in assignedNicks) {
if (assignedNicks.hasOwnProperty(i)) {
nickCounter += 1;
}
}
// pick a color
var nickColor;
if (nickCounter <= nickColors.length) {
nickColor = nickColors[nickCounter];
}
else {
nickColor = nickColors[(nickCounter % nickColors.length)];
}
// add the nick and color
assignedNicks[nickString] = nickColor;
}
return assignedNicks[nickString];
};
// function onMessage(topicUri, event) {
function onMessage(args, kwargs, details) {
console.log("on message");
addMessage(args[0]);
// set new message highlighting on "chat" button
$("#show_chat_window").addClass("message_received");
}
function addMessage(payload) {
// get the parts of the message event
var message = payload.message;
var messageNick = payload.nick;
var nickColor = getNickColor(messageNick);
var messageTime = formattedMessageTime();
var messagesBox = $("#messages_box")[0];
// add html to messages box
$(messagesBox).append("<p class='nick_line' style='color: " + nickColor + ";'>" + messageNick + " - <span class='message_time'>" + messageTime + "</span></p>");
$(messagesBox).append("<p class='message_line'>" + message + "</p>");
$(messagesBox).append("</br>");
// scroll messages box
messagesBox.scrollTop = messagesBox.scrollHeight;
}
function formattedMessageTime() {
var messageTimeRaw = new Date();
var day = messageTimeRaw.getDate();
var month = messageTimeRaw.getMonth() + 1;
var hours = messageTimeRaw.getHours();
var minutes = messageTimeRaw.getMinutes();
// add initial '0' where necessary
minutes = minutes < 10 ? "0" + minutes : minutes;
hours = hours < 10 ? "0" + hours : hours;
var formattedMessageTime = hours + ":" + minutes;
return formattedMessageTime;
};