-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
282 lines (226 loc) · 8.55 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
//initialize a Chat singleton
var Chat = (function(){
var setCookie = function(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
};
var getCookie = function(c_name){
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
};
//current date stamp for generating a UID
var now = new Date();
//current name of the user, if none uses UID
var chat_name = null;
//current set of users on chat
var users = {};
/**
* the different types of messages
* 1) JOIN, when a users joins this is sent out to notify all users someone has joined the chat
* 2) JOIN_ACK, a response from the other users in the chat room to notify the user that just joined who else is there
* 3) CHAT, primary type, for sending standard chat messages
* 4) LEAVE, when someone leaves chat, notifies users to remove them from there user set
* 5) RENAME, when the user renames there user id
* 6) ERROR, when something bad happens, disconnect or error on PUBNUB
*/
var TYPES = {JOIN: 1, JOIN_ACK:2, CHAT: 3, LEAVE: 4, RENAME: 5, ERROR:6 };
//get the previous UID stored in the CHAT_UID cookie
var UID = getCookie('CHAT_UID');
var USERNAME = getCookie('CHAT_USERNAME');
if(USERNAME === undefined){
USERNAME = null;
}
var from_session = 1;
if(UID === undefined){
UID = Date.UTC(now.getYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes(),now.getSeconds(),now.getMilliseconds());
from_session = 0;
}
setCookie('CHAT_UID',UID,1);
//create a message to be sent over PUBNUB
var createMsg = function(type,message){
return {'user':UID,'type':type, 'payload':message};
};
/**
* append a message to the words div, given a message object(from createMsg)
*
* @param Object
* @return void
*/
var appendMsg = function(message){
var usr = users[message.user] === null || users[message.user] === undefined? message.user: users[message.user];
if(message.type === TYPES.CHAT ){
document.getElementById('words').innerHTML += '<div class="word'+message.type+'"><div class="rounded shadow"><span class="user">'+usr+' </span><span class="payload">'+message.payload+'</span></div></div>';
}
else{
document.getElementById('words').innerHTML += '<div class="word'+message.type+'"><div class="rounded"><span class="payload">'+message.payload+'</span></div></div>';
}
//keep scroll position on the bottom
document.getElementById('words').scrollTop = document.getElementById('words').scrollHeight;
};
//binary flag used by rename so not to show the input when it's already shown
var showing = 0;
/**
* rename the user on the DOM Element and in the users array
*
* @param string
* @param string
* @return void
*/
var rename_user = function(user_id,user_name){
users[user_id] = user_name;
if(user_id === UID){
setCookie('CHAT_USERNAME',user_name);
}
var inner = user_name;
if(user_id === UID){
inner = '<a href="#" onclick="Chat.rename(this.parentNode,'+user_id+')">'+user_name+'</a>';
}
document.getElementById('user'+user_id).innerHTML = inner;
};
/**
* handle a rename event, when the user hits enter in the rename input box
*
* @param Object
* @param string
* @param string
* @return void
*/
var renameSubmit = function(e,user_name,user_id){
if(e.keyCode === 13){
user_id = user_id === null? UID:user_id;
showing = 0;
PUBNUB.publish({'channel':'chat_room',message:createMsg(TYPES.RENAME,user_name)});
rename_user(user_id,user_name);
}
};
/**
* show the rename user interface by showing a input box for the user to type
*
* @param DOMElement
* @param string
* @return void
*/
var rename = function(el,user_id){
var user_name = users[user_id] !== null? users[user_id] : user_id;
if(!showing){
el.innerHTML = '<input id="rename-user" onkeyup="Chat.renameSubmit(event,this.value,null)" type="text" value="'+user_name+'" name="rename" />';
showing = 1;
}
};
/**
* append a user to the users div, given the user id and user name
*
* @param string
* @param string
* @return void
*/
var appendUsr = function(user_id,user_name){
if(users[user_id] === undefined){
users[user_id] = user_name;
var inner = user_id;
if( user_name !== null && user_name !== undefined ){
inner = user_name;
}
if(user_id === UID){
inner = '<a href="#" onclick="Chat.rename(this.parentNode,'+user_id+');">'+inner+'</a>'
}
document.getElementById('users').innerHTML += '<li id="user' + user_id + '" >'+inner+'</li>';
}
};
/**
* remove a user fromt he users div
*
* @param string
* @return void
*/
var removeUsr = function(user_id) {
var user_li = document.getElementById('user'+user_id);
if(user_li !== null){
delete users[user_id];
document.getElementById('users').removeChild(user_li);
}
};
/**
* when the user closes the browser notify the other users the UID no longer exists
* this only handles the browser close use case, not browser refresh
*/
window.onbeforeunload = function(e){
PUBNUB.publish({
'channel': 'chat_room',
'message': createMsg(TYPES.LEAVE, users[UID] === null?UID:users[UID])
});
};
var subscribe = function(){
//subscribe to the chat room
PUBNUB.subscribe({
'channel': "chat_room",
'restore': false,
'callback': function(message) {
if(message.type === TYPES.JOIN){
var payload = UID;
if(users[UID] !== null){
payload = users[UID];
}
PUBNUB.publish({
channel:"chat_room",
message:createMsg(TYPES.JOIN_ACK, payload )
});
appendMsg(message);
}
else if(message.type === TYPES.JOIN_ACK && users[message.user] === undefined){
if(message.user !== UID){
appendUsr(message.user,message.payload);
}
}
else if(message.type === TYPES.CHAT){
appendMsg(message);
}
else if(message.type === TYPES.LEAVE){
if(message.user != UID){
removeUsr(message.payload);
appendMsg(createMsg(TYPES.LEAVE,message.payload + ' has left'));
}
}
else if(message.type === TYPES.RENAME){
rename_user(message.user,message.payload);
}
},
'disconnect': function() { // LOST CONNECTION.
appendMsg(createMsg(TYPES.ERROR,'You disconnected'));
},
'reconnect': function() { // CONNECTION RESTORED.
/*PUBNUB.publish({
'channel': 'chat_room',
'message': createMsg(TYPES.JOIN, UID)
});
*/
},
'error': function(msg){
appendMsg(createMsg(TYPES.ERROR,'There was an unknown error'));
},
'connect': function() { // CONNECTION ESTABLISHED.
var msg = USERNAME === null?UID:USERNAME;
PUBNUB.publish({ // SEND A MESSAGE.
channel : "chat_room",
message : createMsg(TYPES.JOIN, msg + " connected ..."),
callback:function(info){
appendUsr(UID,USERNAME);
}
});
}
});
}
subscribe();
return {'createMsg': createMsg,'TYPES': TYPES, 'rename': rename,'renameSubmit':renameSubmit };
})();