diff options
| author | Scott Ostler <sostler@deathmachine.local> | 2010-01-20 01:14:54 -0500 |
|---|---|---|
| committer | Scott Ostler <sostler@deathmachine.local> | 2010-01-20 01:14:54 -0500 |
| commit | faab952a795a1eee1ed6eaca476d56fcb77998aa (patch) | |
| tree | 5b90a7e345c82583cadac9eda58a6c5d5ec9b9c2 /static/js/pichat.js | |
| parent | a91eb914edb95a5facd62b2eac00186b7b8c63c1 (diff) | |
| parent | 9b9f1b51d63ee0a46d766d285ffac028d7c40cbb (diff) | |
Getting up to date
Diffstat (limited to 'static/js/pichat.js')
| -rwxr-xr-x | static/js/pichat.js | 275 |
1 files changed, 275 insertions, 0 deletions
diff --git a/static/js/pichat.js b/static/js/pichat.js new file mode 100755 index 0000000..df79c17 --- /dev/null +++ b/static/js/pichat.js @@ -0,0 +1,275 @@ +var cache = {} + +function escapeHtml(txt) { + if (!txt) { return ""; } + else { return $("<span>").text(txt).html(); } +} + +function linkify(text) { + var URLRegex = /((\b(http\:\/\/|https\:\/\/|ftp\:\/\/)|(www\.))+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi; + return text.replace(URLRegex, linkReplace); +} + +function linkReplace(match){ + var PicRegex = /\.(jpg|jpeg|png|gif|bmp)$/i; + var matchWithoutParams = match.replace(/\?.*$/i, "") + if (PicRegex.test(matchWithoutParams)){ + return "<a target='_blank' href='" + match + "'><img src='" + match + "'></a>" + } else { + return "<a target='_blank' href='" + match + "'>" + match + "</a>" + } +} + +function buildMsgContent(content) { + return linkify(content) +} + +var SpinnerImage = '<img class="spinner" src="/static/spinner.gif" />'; + +function buildMessageDiv(msg, isLoading) { + var nick = escapeHtml(msg.nick); + var msgId = !isLoading ? 'id="message-' + msg.message_id + '"' : ''; + var spinnerHtml = isLoading ? SpinnerImage : ''; + var loadingClass = isLoading ? ' loading' : ''; + return '<div class="msgDiv ' + loadingClass + '" ' + msgId + '>' + + '<b><a href="/u/' + nick + ' ">' + nick + '</a>: </b>' + + buildMsgContent(msg.content) + + spinnerHtml + + '</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>'; + } +} + +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({ + // (string | mandatory) the heading of the notification + title: user, + // (string | mandatory) the text inside the notification + 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!"); + } +} + +function submitMessage() { + var content = $.trim($('#msgInput').val()); + if (content == '') { return; } + PostedMessages.push(content); + $('#msgInput').val(''); + + var msg = { 'nick': Nick, 'content': content }; + var div = addNewMessage(msg, true); + + var onSuccess = function(json) { + div.attr('id', 'message-' + json) + .removeClass('loading').addClass('loaded'); + div.find('.spinner').remove(); + }; + var onError = function(resp, textStatus, errorThrown) { + div.remove(); + handleMsgError(resp); + }; + + $.ajax({ + type: 'GET', + 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 isScrolledToBottom(div) { + return Math.abs(div.scrollTop - (div.scrollHeight - div.offsetHeight)) <= 3; +} + +function scrollToBottom(div) { + div.scrollTop = div.scrollHeight; +} + +// Give images time to start loading before scrolling. +// Needed until server knows size of images. +function delayedScrollToBottom(delay) { + setTimeout(scrollToBottom, delay, $('#messageList')[0]); +} + +function addNewMessages(msgs) { + var wasScrolledToBottom = isScrolledToBottom($('#messageList')[0]); + var msgStr = $.map(msgs, buildMessageDiv).join(''); + $('#messageList').append(msgStr); + + if (wasScrolledToBottom) { delayedScrollToBottom(500); } +} + +function addNewMessage(msg, isLoading) { + var wasScrolledToBottom = isScrolledToBottom($('#messageList')[0]); + var msgStr = buildMessageDiv(msg, isLoading); + var div = $(msgStr).appendTo('#messageList'); + if (wasScrolledToBottom) { delayedScrollToBottom(500); } + return div; +} + +function setUserList(users) { + $("#userList").html($.map(users, buildUserDiv).join('')); +} + +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 = users.sort().join(",") + if (!('userlist' in cache) || flattened != cache.userlist) { + $("#userList").html($.map(users, buildUserDiv).join('')); + } + cache.userlist = flattened + } +} + +// A duplicate message is a message that was likely to have +// originated from this browser. +// TODO: replace w/ msg_id checks. +function isDuplicateMessage(m) { + if (m.nick != Nick || $.inArray(m.content, PostedMessages) == -1) { + return false; + } + var now = new Date().getTime(); + return m.created_on - now < 5000; +} + +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') { + UnseenMsgCounter += messages.length; + } + } catch(e) { + if (IsAdmin) { + alert("Exception in refresh"); + console.log(e); + } + } + setTimeout(refresh, 1000); + }; + var onError = function(resp, textStatus, errorThrown) { + if (IsAdmin) { + console.log(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); + + delayedScrollToBottom(500); + setTimeout(refresh, 1000); +} + +function initProfile() { + $('.logged-dump .content').each(function() { + var t = $(this); + t.html(buildMsgContent(t.text())); + }); + + var onSubmit = function(original_element, edit, old) { + edit = $.trim(edit); + if (edit == old) { return old }; + // TODO: Prevent entering script tags + if (original_element == 'avatar' && edit.indexOf("<") != -1) { + return old; + } + $.ajax({ + type: "GET", + timeout: 5000, + url: "/update-profile", + data: { 'attr': original_element, 'val': edit } + }); + if (original_element == 'avatar') { + var s = '<img id="avatarPic" src="' + edit + '" width="150" />'; + $('#avatarPic').replaceWith(s); + } + return escapeHtml(edit); + }; + + var opt = { 'default_text': 'Enter here!', + 'callback': onSubmit, + 'field_type': 'text', + 'callbackShowErrors': false }; + $('#avatar.editable').editInPlace(opt); + + + opt['field_type'] = 'textarea'; + $('#contact.editable, #bio.editable').editInPlace(opt); + +}; + +function initLog() { + $('.logged-dump .content').each(function() { + var t = $(this); + t.html(buildMsgContent(t.text())); + }); + +} + +function favoriteImage() {}; |
