forked from mohlendo/node_chat
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.js
285 lines (233 loc) · 6.49 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
var CONFIG = { debug: false
, nick: "#" // set in onConnect
, id: null // set in onConnect
, last_message_time: 1
};
var nicks = [];
function updateUsersLink ( ) {
var t = nicks.length.toString() + " user";
if (nicks.length != 1) t += "s";
$("#usersLink").text(t);
}
function userJoin(nick, timestamp) {
addMessage(nick, "joined", timestamp, "join");
for (var i = 0; i < nicks.length; i++)
if (nicks[i] == nick) return;
nicks.push(nick);
updateUsersLink();
}
function userPart(nick, timestamp) {
addMessage(nick, "left", timestamp, "part");
for (var i = 0; i < nicks.length; i++) {
if (nicks[i] == nick) {
nicks.splice(i,1)
break;
}
}
updateUsersLink();
}
// utility functions
util = {
urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
// html sanitizer
toStaticHTML: function(inputHtml) {
return inputHtml.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
},
zeroPad: function (digits, n) {
n = n.toString();
while (n.length < digits)
n = '0' + n;
return n;
},
timeString: function (date) {
var minutes = date.getMinutes().toString();
var hours = date.getHours().toString();
return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
},
isBlank: function(text) {
var blank = /^\s*$/;
return (text.match(blank) !== null);
}
};
function scrollDown () {
window.scrollBy(0, 100000000000000000);
$("#entry").focus();
}
function addMessage (from, text, time, _class) {
if (text === null)
return;
if (time == null) {
// if the time is null or undefined, use the current time.
time = new Date();
} else if ((time instanceof Date) === false) {
// if it's a timestamp, interpret it
time = new Date(time);
}
var messageElement = $(document.createElement("table"));
messageElement.addClass("message");
if (_class)
messageElement.addClass(_class);
// sanitize
text = util.toStaticHTML(text);
// See if it matches our nick?
var nick_re = new RegExp(CONFIG.nick);
if (nick_re.exec(text))
messageElement.addClass("personal");
// replace URLs with links
text = text.replace(util.urlRE, '<a target="_blank" href="$&">$&</a>');
var content = '<tr>'
+ ' <td class="date">' + util.timeString(time) + '</td>'
+ ' <td class="nick">' + util.toStaticHTML(from) + '</td>'
+ ' <td class="msg-text">' + text + '</td>'
+ '</tr>'
;
messageElement.html(content);
$("#log").append(messageElement);
scrollDown();
}
var transmission_errors = 0;
var first_poll = true;
function longPoll (data) {
if (transmission_errors > 2) {
showConnect();
return;
}
if (data && data.messages) {
for (var i = 0; i < data.messages.length; i++) {
var message = data.messages[i];
if (message.timestamp > CONFIG.last_message_time)
CONFIG.last_message_time = message.timestamp;
switch (message.type) {
case "msg":
addMessage(message.nick, message.text, message.timestamp);
break;
case "join":
userJoin(message.nick, message.timestamp);
break;
case "part":
userPart(message.nick, message.timestamp);
break;
}
}
if (first_poll) {
first_poll = false;
who();
}
}
$.ajax({ cache: false
, type: "GET"
, url: "/recv"
, dataType: "json"
, data: { since: CONFIG.last_message_time, id: CONFIG.id }
, error: function () {
addMessage("", "long poll error. trying again...", new Date(), "error");
transmission_errors += 1;
setTimeout(longPoll, 10*1000);
}
, success: function (data) {
transmission_errors = 0;
longPoll(data);
}
});
}
function send(msg) {
if (CONFIG.debug === false) {
// XXX should be POST
jQuery.get("/send", {id: CONFIG.id, text: msg}, function (data) { }, "json");
}
}
function showConnect () {
$("#connect").show();
$("#loading").hide();
$("#toolbar").hide();
$("#nickInput").focus();
}
function showLoad () {
$("#connect").hide();
$("#loading").show();
$("#toolbar").hide();
}
function showChat (nick) {
$("#toolbar").show();
$("#entry").focus();
$("#connect").hide();
$("#loading").hide();
scrollDown();
}
function onConnect (session) {
if (session.error) {
alert("error connecting: " + session.error);
showConnect();
return;
}
CONFIG.nick = session.nick;
CONFIG.id = session.id;
showChat(CONFIG.nick);
}
function outputUsers () {
var nick_string = nicks.length > 0 ? nicks.join(", ") : "(none)";
addMessage("users:", nick_string, new Date(), "notice");
return false;
}
function who () {
jQuery.get("/who", {}, function (data, status) {
if (status != "success") return;
nicks = data.nicks;
outputUsers();
}, "json");
}
$(document).ready(function() {
$("#entry").keypress(function (e) {
if (e.keyCode != 13 /* Return */) return;
var msg = $("#entry").attr("value").replace("\n", "");
if (!util.isBlank(msg)) send(msg);
$("#entry").attr("value", ""); // clear the entry field.
});
$("#usersLink").click(outputUsers);
$("#connectButton").click(function () {
showLoad();
var nick = $("#nickInput").attr("value");
if (nick.length > 50) {
alert("Nick too long. 50 character max.");
showConnect();
return false;
}
if (/[^\w_\-^!]/.exec(nick)) {
alert("Bad character in nick. Can only have letters, numbers, and '_', '-', '^', '!'");
showConnect();
return false;
}
$.ajax({ cache: false
, type: "GET" // XXX should be POST
, dataType: "json"
, url: "/join"
, data: { nick: nick }
, error: function () {
alert("error connecting to server");
showConnect();
}
, success: onConnect
});
return false;
});
// update the clock every second
setInterval(function () {
var now = new Date();
$("#currentTime").text(util.timeString(now));
}, 1000);
if (CONFIG.debug) {
$("#loading").hide();
$("#connect").hide();
scrollDown();
return;
}
// remove fixtures
$("#log table").remove();
longPoll();
showConnect();
});
$(window).unload(function () {
jQuery.get("/part", {id: CONFIG.id}, function (data) { }, "json");
});