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
|
var cache = {}
var PendingMessages = {}
var MaxImagePosts = 40
// Utils
function escapeHtml(txt) {
if (!txt) { return ""; }
else { return $("<span>").text(txt).html(); }
}
function linkify(text) {
LastMsgContainsImage = false
var URLRegex = /((\b(http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
return text.replace(URLRegex, linkReplace);
}
// durty hack to use a global to check this... but otherwise i'd have to rewrite the String.replace function? :/
var LastMsgContainsImage = false
function linkReplace(url){
var PicRegex = /\.(jpg|jpeg|png|gif|bmp)$/i;
var urlWithoutParams = url.replace(/\?.*$/i, "");
linkUrl = url.indexOf('http://') == 0 ? url : 'http://' + url;
if (PicRegex.test(urlWithoutParams)){
LastMsgContainsImage = true
return "<a target='_blank' href='" + linkUrl + "'><img src='" + linkUrl + "'></a>"
} else {
return "<a target='_blank' href='" + linkUrl + "'>" + url + "</a>"
}
}
function linkifyWithoutImage(text) {
LastMsgContainsImage = false
var URLRegex = /((\b(http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
return text.replace(URLRegex, linkReplaceWithoutImage);
}
function linkReplaceWithoutImage(url){
var PicRegex = /\.(jpg|jpeg|png|gif|bmp)$/i;
var urlWithoutParams = url.replace(/\?.*$/i, "");
linkUrl = url.indexOf('http://') == 0 ? url : 'http://' + url;
return "<a target='_blank' href='" + linkUrl + "'>" + url + "</a>"
}
// Message Handling
var ImageMsgCount = 0
function removeOldMessages(){
// don't count posts that are all text
if (LastMsgContainsImage) ImageMsgCount += 1;
while (ImageMsgCount > MaxImagePosts) {
var imgMsg = $(".contains-image:first")
if (imgMsg.length) {
imgMsg.prevAll().remove() // remove all text messages before the image message
imgMsg.remove()
} else break;
ImageMsgCount -= 1;
}
}
function buildMsgContent(content) {
return linkify(escapeHtml(content));
}
function buildMessageDiv(msg, isLoading) {
removeOldMessages()
var nick = escapeHtml(msg.nick);
var msgId = !isLoading ? 'id="message-' + msg.msg_id + '"' : '';
var loadingClass = isLoading ? ' loading' : '';
var containsImageClass = LastMsgContainsImage ? ' contains-image' : '';
return '<div class="msgDiv ' + loadingClass + containsImageClass + '" ' + msgId + '>'
+ '<b><a href="/u/' + nick + ' ">' + nick + '</a>: </b>'
+ buildMsgContent(msg.content)
+ '</div>';
}
function buildUserDiv(user) {
if (user.avatar) {
return '<div class="username">'
+ '<a href="/u/' + escapeHtml(user.nick) + '" target="_blank">'
+ '<img src="' + user.avatar + '" width="50" height="50">'
+ escapeHtml(user.nick) + '</a></div>';
} else {
return '<div class="username">'
+ '<a href="/u/' + escapeHtml(user.nick) + '" target="_blank">'
+ escapeHtml(user.nick) + '</a></div>';
}
}
// Growl
function buildGrowlDataAndPopDatShit(msg) {
var nick = escapeHtml(msg.nick);
nick = '<a href="/u/' + nick + ' " style="color:pink">' + nick + '</a>:'
var msg = buildMsgContent(msg.content)
growl(nick, msg)
}
function growl(user, msg) {
$.gritter.add({title: user, text: msg});
}
function handleMsgError(resp) {
var respText = resp.responseText ? resp.responseText.trim() : false;
if (respText == 'MUST_LOGIN') {
alert("Can't send message! Please login.");
} else if (respText) {
alert("Can't send message! (" + respText + ")");
} else {
alert("Can't send message!");
}
}
// Messages
function submitMessage() {
var content = $.trim($('#msgInput').val());
$('#msgInput').val('');
if (content == '') { return; }
PendingMessages[content] = true;
var msg = { 'nick': Nick, 'content': content };
var div = addNewMessage(msg, true);
var onSuccess = function(json) {
if (typeof pageTracker !== 'undefined') {
pageTracker._trackEvent('Message', 'Submit', typeof Room !== 'undefined' ? Room : 'UnknownRoom');
}
div.attr('id', 'message-' + json)
.removeClass('loading').addClass('loaded');
};
var onError = function(resp, textStatus, errorThrown) {
div.remove();
handleMsgError(resp);
};
$.ajax({
type: 'POST',
timeout: 5000,
url: '/msg',
data: { 'room': Room, 'content': content },
cache: false,
dataType: 'json',
success: onSuccess,
error: onError
});
}
function ifEnter(fn) {
return function(e) {
if (e.keyCode == 13) { fn(); }
};
}
function addNewMessages(msgs) {
var msgStr = $.map(msgs, buildMessageDiv).join('');
$('#messageList').append(msgStr);
}
function addNewMessage(msg, isLoading) {
var msgStr = buildMessageDiv(msg, isLoading);
var div = $(msgStr).appendTo('#messageList');
return div;
}
function setUserList(users) {
$("#userList").html($.map(users, buildUserDiv).join(''));
}
function flattenUserJson(users) {
var s = "";
$.map(users.sort(), function(user) {
s += user.nick + user.avatar;
});
return s;
}
function updateUI(msgs, users) {
if (window['growlize'] && msgs && msgs.length > 0) {
$.map(msgs, buildGrowlDataAndPopDatShit)
} else if (msgs && msgs.length > 0) {
addNewMessages(msgs);
}
if (users !== null) {
var flattened = flattenUserJson(users);
if (!('userlist' in cache) || flattened != cache.userlist) {
$("#userList").html($.map(users, buildUserDiv).join(''));
}
cache.userlist = flattened
}
}
function isDuplicateMessage(m) {
if (m.nick == Nick && m.content in PendingMessages) {
delete PendingMessages[m.content];
return true;
} else {
return false;
}
}
var CurrentTopic = null;
function isSameTopic(curTopic, newTopic) {
if (!!curTopic != !!newTopic) { return false; }
else if (!curTopic) { return false; } // => !newTopic also
else {
return curTopic.topic == newTopic.topic &&
curTopic.deadline == newTopic.deadline &&
curTopic.maker == newTopic.maker;
}
}
function updateTopic(newTopic) {
if (isSameTopic(CurrentTopic, newTopic)) { return; }
alert('new topic');
CurrentTopic = newTopic;
$('#topic').text(topic.topic);
}
function refresh() {
var onSuccess = function(json) {
try {
Timestamp = json.timestamp;
var messages = $.grep(
json.messages,
function(m) { return !isDuplicateMessage(m) });
updateUI(messages, json.users);
if (typeof UnseenMsgCounter !== 'undefined' && !HasFocus) {
UnseenMsgCounter += messages.length;
}
if (json.topic) {
updateTopic(json.topic);
}
} catch(e) {
if (IsAdmin && window.console) {
console.error(e);
}
}
setTimeout(refresh, 1000);
};
var onError = function(resp, textStatus, errorThrown) {
if (IsAdmin && window.console) {
console.error(resp, textStatus, errorThrown);
}
setTimeout(refresh, 1000);
};
$.ajax({
type: 'GET',
timeout: 5000,
url: '/refresh',
data: { 'room': Room, 'since': Timestamp },
cache: false,
dataType: 'json',
success: onSuccess,
error: onError
});
}
function initChat() {
$('.msgDiv .content').each(function() {
var t = $(this);
t.html(buildMsgContent(t.text()));
});
$('#msgInput').keyup(ifEnter(submitMessage));
$('#msgSubmit').click(submitMessage);
messageList = $("#messageList")[0]
scrollToEnd()
scrollWatcher()
// see /static/webcam/webcam.js
if ('webcam' in window) webcam.init()
setTimeout(refresh, 1000);
}
function makePlainText() {
var j = $(this);
j.text(j.text());
}
function activateProfileEditable() {
var onSubmit = function(attr, newVal, oldVal) {
newVal = $.trim(newVal);
if (newVal == oldVal) { return oldVal };
$.ajax({
type: "POST",
timeout: 5000,
url: "/update-profile",
data: { 'attr': attr, 'val': newVal }
});
if (attr == 'avatar') {
if (newVal != "") {
var s = '<img id="avatarPic" src="' + newVal + '" width="150" />';
$('#avatarPic').replaceWith(s).show();
} else {
$('#avatarPic').hide();
}
}
return escapeHtml(newVal);
};
var avatarOpts = { 'default_text': 'Paste URL here!',
'callback': onSubmit,
'field_type': 'text',
'callbackShowErrors': false };
if ($('#avatar.editable').length > 0) {
$('#avatar.editable').editInPlace(avatarOpts);
setupUploadAvatar('upload');
}
var textareaOpts = { 'default_text': 'Enter here!',
'callback': onSubmit,
'field_type': 'textarea',
'callbackShowErrors': false };
$('#contact.editable, #bio.editable')
.editInPlace(textareaOpts)
.each(makePlainText);
}
function enableProfileEdit() {
$('img#contact').replaceWith('<div id="contact" class="linkify"></div>');
$('img#bio').replaceWith('<div id="bio" class="linkify"></div>');
$('#contact, #bio, #avatar').addClass('editable');
$('#avatar-editing').show();
var resetPage = function() { location.reload() };
$('#edit-toggle a').text('done editing').click(resetPage);
activateProfileEditable();
}
function initProfile() {
$(".linkify").each(function() {
var text = jQuery(this).text();
jQuery(this).html(linkifyWithoutImage(text));
});
$('#edit-toggle').click(enableProfileEdit);
activateProfileEditable();
$('.logged-dump .content').each(function() {
var t = $(this);
t.html(buildMsgContent(t.text()));
});
};
function initLog() {
$('.logged-dump .content').each(function() {
var t = $(this);
t.html(buildMsgContent(t.text()));
});
}
// TODO
function favoriteImage() {};
function setupUpload(elementId, roomKey) {
var onSubmit = function(file, ext) {
if (!(ext && /^(jpg|png|jpeg|gif|bmp)$/i.test(ext))) {
alert('SORRY, NOT AN IMAGE DUDE... ');
return false;
}
};
var onComplete = function(file, response) {
if (typeof pageTracker !== 'undefined') {
pageTracker._trackEvent('Message', 'Upload', typeof Room !== 'undefined' ? Room : 'UnknownRoom');
}
}
new AjaxUpload(elementId, {
action: '/upload/message',
autoSubmit: true,
name: 'image',
data: { room: roomKey },
onSubmit: onSubmit,
onComplete: onComplete
});
}
function setupUploadAvatar(elementId) {
// NOTE: AjaxUpload responses aren't converted from JSON.
var onSubmit = function(file, error) {
$('#spinner').show();
};
var onComplete = function(file, resp) {
$('#spinner').hide();
if (resp == 'INVALID_REQUEST') {
location.reload();
} else if (resp == 'NOT_LOGGED_IN') {
location.reload();
} else if (resp == 'INVALID_IMAGE') {
alert("Sorry, dump.fm can't deal with your image. Pick another :(");
return;
}
var s = '<img id="avatarPic" src="' + resp + '" width="150" />';
$('#avatarPic').replaceWith(s).show();
$('#avatar').text(resp);
};
new AjaxUpload(elementId, {
action: '/upload/avatar',
autoSubmit: true,
name: 'image',
onSubmit: onSubmit,
onComplete: onComplete
});
}
// scrolling stuff
// this code keeps the div scrolled to the bottom, but will also let the user scroll up, without jumping down
function isScrolledToBottom(){
var threshold = 15;
var containerHeight = messageList.style.pixelHeight || messageList.offsetHeight
var currentHeight = (messageList.scrollHeight > 0) ? messageList.scrollHeight : 0
var result = (currentHeight - messageList.scrollTop - containerHeight < threshold);
return result;
}
function scrollIfPossible(){
if (lastScriptedScrolledPosition <= messageList.scrollTop || isScrolledToBottom())
scrollToEnd()
}
var lastScriptedScrolledPosition = 0
function scrollToEnd(){
messageList.scrollTop = messageList.scrollHeight
lastScriptedScrolledPosition = messageList.scrollTop
}
function scrollWatcher(){
scrollIfPossible()
setTimeout(scrollWatcher, 500)
}
// well fuck webkit for not supporting {text-decoration: blink}
function blinkStart(){
blinkTimer = setInterval(function(){
$(".blink").removeClass("blink").addClass("blink-turning-off")
$(".blink-off").removeClass("blink-off").addClass("blink")
$(".blink-turning-off").removeClass("blink-turning-off").addClass("blink-off")
},500);
}
function blinkStop(){
clearInterval(blinkTimer);
}
|