Add chat.js and chatui.js (split up from collective.xmpp.chat.js).

This commit is contained in:
JC Brand 2012-06-23 14:26:04 +02:00
parent f270991595
commit 0c6ccf67c8
2 changed files with 647 additions and 0 deletions

190
chat.js Normal file
View File

@ -0,0 +1,190 @@
var helpers = (function (helpers) {
helpers.oc = function (a) {
// Thanks to Jonathan Snook: http://snook.ca
var o = {};
for(var i=0; i<a.length; i++) {
o[a[i]]='';
}
return o;
};
helpers.hash =function (str) {
// FIXME
if (str == 'online-users-container') {
return str;
}
var shaobj = new jsSHA(str);
return shaobj.getHash("HEX");
};
return helpers;
})(helpers || {});
var xmppchat = (function (jarnxmpp, $, console) {
var ob = jarnxmpp;
ob.Collections = {};
ob.Messages = jarnxmpp.Messages || {};
ob.Presence = jarnxmpp.Presence || {};
ob.ChatPartners = (function () {
/* A mapping of bare JIDs to resources, to keep track of
* how many resources we have per chat partner.
*/
var storage = {};
var methods = {};
methods.add = function (bare_jid, resource) {
if (Object.prototype.hasOwnProperty.call(storage, bare_jid)) {
if (!(resource in helpers.oc(storage[bare_jid]))) {
storage[bare_jid].push(resource);
}
} else {
storage[bare_jid] = [resource];
}
};
methods.remove = function (bare_jid, resource) {
if (Object.prototype.hasOwnProperty.call(storage, bare_jid)) {
if (!(resource in helpers.oc(storage[bare_jid]))) {
var idx = storage[bare_jid].indexOf(resource);
if (idx !== undefined) {
storage[bare_jid].splice(idx, 1);
}
}
}
};
return methods;
})();
ob.Messages.sendMessage = function (recipient, text, callback) {
// TODO: Look in ChatPartners to see what resources we have for the recipient.
// if we have one resource, we sent to only that resources, if we have multiple
// we send to the bare jid.
var message;
$.getJSON(portal_url + '/content-transform?', {text: text}, function (data) {
message = $msg({to: recipient, type: 'chat'}).c('body').t(data.text);
xmppchat.connection.send(message);
callback();
});
};
ob.Messages.messageReceived = function (message) {
var jid = $(message).attr('from'),
bare_jid = Strophe.getBareJidFromJid(jid),
resource = Strophe.getResourceFromJid(jid),
delayed = $(message).find('delay').length > 0;
ob.ChatPartners.add(bare_jid, resource);
var body = $(message).children('body').text();
if (body === "") {
// TODO:
return true; // This is a typing notification, we do not handle it here...
}
var xhtml_body = $(message).find('html > body').contents(),
event = jQuery.Event('jarnxmpp.message');
event.from = jid;
event.delayed = delayed;
if (xhtml_body.length > 0) {
event.mtype = 'xhtml';
event.body = xhtml_body.html();
} else {
event.body = body;
event.mtype = 'text';
}
$(document).trigger(event);
return true;
};
ob.Collections.handleError = function (response) {
console.log(response);
};
ob.Collections.handleCollectionRetrieval = function (response) {
// Get the last collection.
return false;
};
ob.Collections.retrieveCollections = function () {
/*
* FIXME: XEP-0136 specifies 'urn:xmpp:archive' but the mod_archive_odbc
* add-on for ejabberd wants the URL below. This might break for other
* Jabber servers.
*/
var uri = 'http://www.xmpp.org/extensions/xep-0136.html#ns';
var iq = $iq({'type':'get'})
.c('list', {'start': '1469-07-21T02:00:00Z',
'xmlns': uri
})
.c('set', {'xmlns': 'http://jabber.org/protocol/rsm'})
.c('max')
.t('30');
xmppchat.connection.sendIQ(iq, this.handleCollectionRetrieval, this.handleError);
};
ob.Presence.sendPresence = function (type) {
if (type === undefined) {
type = xmppchat.Storage.get(xmppchat.username+'-xmpp-status') || 'online';
}
xmppchat.connection.send($pres({'type':type}));
};
ob.Presence.presenceReceived = function (presence) {
var jid = $(presence).attr('from'),
bare_jid = Strophe.getBareJidFromJid(jid),
resource = Strophe.getResourceFromJid(jid),
ptype = $(presence).attr('type'),
status = '';
if (ptype === 'subscribe') {
// User wants to subscribe to us. Always approve and
// ask to subscribe to him
jarnxmpp.connection.send($pres({to: jid, type: 'subscribed'}));
jarnxmpp.connection.send($pres({to: jid, type: 'subscribe'}));
} else if (ptype !== 'error') { // Presence has changed
if (ptype === 'unavailable') {
status = 'unavailable';
} else if (ptype === 'offline') {
status = 'offline';
} else if (ptype === 'busy') {
status = 'busy';
} else if (ptype === 'away') {
status = 'away';
} else {
status = ($(presence).find('show').text() === '') ? 'online' : 'away';
}
if ((status !== 'offline')&&(status !== 'unavilable')) {
xmppchat.ChatPartners.add(bare_jid, resource);
} else {
xmppchat.ChatPartners.remove(bare_jid, resource);
}
$(document).trigger('jarnxmpp.presence', [jid, status, presence]);
}
return true;
};
ob.Taskbuffer = (function ($) {
buffer = {};
buffer.tasks = [];
buffer.deferred = $.when();
buffer.handleTasks = function () {
var task;
// If the current deferred task is resolved and there are more tasks
if (buffer.deferred.isResolved() && buffer.tasks.length > 0) {
// Get the next task in the queue and set the new deferred.
task = buffer.tasks.shift();
buffer.deferred = $.when(task.method.apply(task.that, task.parameters));
if (buffer.tasks.length > 0) {
buffer.deferred.done(buffer.handleTasks);
}
}
};
return buffer;
})(jQuery);
return ob;
})(jarnxmpp || {}, jQuery, console || {log: function(){}});

457
chatui.js Normal file
View File

@ -0,0 +1,457 @@
xmppchat.UI = (function (xmppUI, $, console) {
var ob = xmppUI;
ob.chats = [];
ob.chat_focus = [];
ob.chatbox_width = 205;
ob.sanitizePath = function (call) {
return xmppchat.base_url + call;
};
ob.updateOnPresence = function (jid, status, presence) {
// TODO: When a presence indicator shows that a resource has
// gone offline, we need to look in the ChatPartners storage to see
// if there are more storages before we mark the user as offline in the UI.
var user_id = Strophe.getNodeFromJid(jid),
barejid = Strophe.getBareJidFromJid(jid),
existing_user_element = $('#online-users-' + user_id),
online_count;
if (barejid === Strophe.getBareJidFromJid(jarnxmpp.connection.jid)) {
return;
}
if (existing_user_element.length) {
if (status === 'offline' && jarnxmpp.Presence.online.hasOwnProperty(user_id)) {
existing_user_element.attr('class', status);
return;
}
existing_user_element.attr('class', status);
} else {
$.get(portal_url + '/xmpp-userDetails?jid=' + barejid, function (user_details) {
// FIXME: this ajax call returns a bunch of unnecessary stuff...
if ($('#online-users-' + user_id).length > 0) {
return;
}
user_details = $(user_details);
$('#online-users').append(user_details);
$('#online-users li[data-userid]').sortElements(function (a, b) {
return $('a.user-details-toggle', a).text().trim() > $('a.user-details-toggle', b).text().trim() ? 1 : -1;
});
});
// Pre-fetch user info if we have a session storage.
if (jarnxmpp.Storage.storage !== null) {
jarnxmpp.Presence.getUserInfo(user_id, function (data) {});
}
}
online_count = jarnxmpp.Presence.onlineCount();
if (online_count > 0) {
$('#no-users-online').hide();
} else {
$('#no-users-online').show();
}
$('#online-count').text(online_count);
};
ob.positionNewChat = function ($chat) {
var open_chats = 0,
offset;
for (var i=0; i<this.chats.length; i++) {
if ($("#"+helpers.hash(this.chats[i])).is(':visible')) {
open_chats++;
}
}
if (open_chats === 0) {
$chat.animate({'right':'15px'});
}
else {
offset = (open_chats)*(this.chatbox_width+7)+15;
$chat.animate({'right': (offset+'px')});
}
};
ob.handleChatEvents = function (chat_id) {
var chat_area = $("#"+chat_id+" .chat-textarea"),
chat_type = chat_id.split('_')[0],
that = this;
that.chat_focus[chat_id] = false;
chat_area.blur(function () {
that.chat_focus[chat_id] = false;
chat_area.removeClass('chat-textarea-'+chat_type+'-selected');
}).focus(function (){
that.chat_focus[chat_id] = true;
chat_area.addClass('chat-textarea-'+chat_type+'-selected');
});
var chatbox = $("#"+chat_id);
chatbox.click(function () {
if (chatbox.find('.chat-content').is(':visible')) {
chatbox.find('.chat-textarea').focus();
}
});
};
ob.createChatbox = function (jid, callback) {
var path = this.sanitizePath('/@@render_chat_box'),
chat_id = helpers.hash(jid),
that = this;
$.ajax({
url: path,
cache: false,
async: false,
data: {
chat_id: 'chatbox_'+jid,
box_id: chat_id,
jid: jid,
tzoffset: -(new Date().getTimezoneOffset())
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
return;
},
success: function(data) {
var chat_id = $(data).attr('id');
var $chat = $('body').append(data).find('#'+chat_id);
$chat.find('.chat-message .time').each(function () {
var jthis = $(this);
var time = jthis.text().split(':');
var hour = time[0];
var minutes = time[1];
var date = new Date();
date.setHours(hour - date.getTimezoneOffset() / 60);
date.setMinutes(minutes);
jthis.replaceWith(date.toLocaleTimeString().substring(0,5));
});
callback($chat);
}
});
};
ob.prepNewChat = function (chat, jid) {
// Some operations that need to be applied on a chatbox
// after it has been created.
var chat_content,
value;
if (jid === 'online-users-container') {
// Make sure the xmpp status is correctly set on the control box
value = xmppchat.Storage.get(xmppchat.username+'-xmpp-status') || 'online';
$(chat).find('#select-xmpp-status').val(value);
} else {
chat_content = $(chat).find('.chat-content');
$(chat).find(".chat-textarea").focus();
if (chat_content.length > 0) {
chat_content.scrollTop(chat_content[0].scrollHeight);
}
}
if (!(jid in helpers.oc(this.chats))) {
this.chats.push(jid);
}
this.addChatToCookie(jid);
};
ob.getChatbox = function (jid, callback) {
// Get a chatbox. Either it exists, then just ensure
// that it's visible and return it. Otherwise, create it.
//
// This method can be deferred.
// http://www.erichynds.com/jquery/using-deferreds-in-jquery/
var chat_content,
chat_id = helpers.hash(jid),
$chat = $("#"+chat_id),
that = this,
dfd = $.Deferred();
if (callback === undefined) {
callback = function () {};
}
if ($chat.length > 0) {
if ($chat.is(':visible')) {
callback($chat);
dfd.resolve();
} else {
// The chatbox exists, merely hidden
$chat.show('fast', function () {
that.prepNewChat(this, jid);
that.reorderChats();
callback(this);
dfd.resolve();
});
}
} else {
this.createChatbox(jid, function ($chat) {
// that.retrieveCollections();
that.positionNewChat($chat);
$chat.show('fast', function () {
that.prepNewChat(this, jid);
that.handleChatEvents(chat_id);
callback(this);
dfd.resolve();
});
});
}
return dfd.promise();
};
ob.reorderChats = function () {
var index = 0,
chat_id,
offset,
$chat;
if ('online-users-container' in helpers.oc(this.chats)) {
index = 1;
$chat = $("#"+helpers.hash(helpers.oc(this.chats)['online-users-container']));
if ($chat.is(':visible')) {
$chat.animate({'right': '15px'});
}
}
for (var i=0; i < this.chats.length; i++) {
chat_id = this.chats[i];
if (chat_id === 'online-users-container') {
continue;
}
$chat = $("#"+helpers.hash(this.chats[i]));
if ($chat.is(':visible')) {
if (index === 0) {
$chat.animate({'right': '15px'});
}
else {
offset = (index)*(this.chatbox_width+7)+15;
$chat.animate({'right': offset +'px'});
}
index++;
}
}
};
ob.addChatToCookie = function (jid) {
var cookie = jQuery.cookie('chats-open-'+xmppchat.username),
new_cookie,
open_chats = [];
if (cookie) {
open_chats = cookie.split('|');
}
if (!(jid in helpers.oc(open_chats))) {
// Update the cookie if this new chat is not yet in it.
open_chats.push(jid);
new_cookie = open_chats.join('|');
jQuery.cookie('chats-open-'+xmppchat.username, new_cookie, {path: '/'});
console.log('updated cookie = ' + new_cookie + '\n');
}
};
ob.removeChatFromCookie = function (jid) {
var cookie = jQuery.cookie('chats-open-'+xmppchat.username),
open_chats = [],
new_chats = [];
if (cookie) {
open_chats = cookie.split('|');
}
for (var i=0; i < open_chats.length; i++) {
if (open_chats[i] != jid) {
new_chats.push(open_chats[i]);
}
}
if (new_chats.length) {
jQuery.cookie('chats-open-'+xmppchat.username, new_chats.join('|'), {path: '/'});
}
else {
jQuery.cookie('chats-open-'+xmppchat.username, null, {path: '/'});
}
};
ob.addMessageToChatbox = function (event) {
/* XXX: event.mtype should be 'xhtml' for XHTML-IM messages,
but I only seem to get 'text'.
XXX: Some messages might be delayed, we must get the time from the event.
*/
var user_id = Strophe.getNodeFromJid(event.from),
jid = Strophe.getBareJidFromJid(event.from),
text = event.body.replace(/<br \/>/g, ""),
that = this;
xmppchat.Presence.getUserInfo(user_id, function (data) {
that.getChatbox(jid, function (chat) {
var chat_content = $(chat).find(".chat-content"),
now = new Date(),
time = now.toLocaleTimeString().substring(0,5),
div = $('<div class="chat-message"></div>');
if (event.delayed) {
div.addClass('delayed');
}
if (user_id == that.username) {
message_html = div.append(
'<span class="chat-message-me">'+time+' me:&nbsp;&nbsp;</span>' +
'<span class="chat-message-content">'+text+'</span>'
);
} else {
message_html = div.append(
'<span class="chat-message-them">'+time+' '+data.fullname+':&nbsp;&nbsp;</span>' +
'<span class="chat-message-content">'+text+'</span>'
);
}
chat_content.append(message_html);
chat_content.scrollTop(chat_content[0].scrollHeight);
xmppchat.UI.msg_counter += 1;
xmppchat.UI.updateMsgCounter();
});
});
};
ob.closeChat = function (jid) {
var chat_id = helpers.hash(jid),
that = this;
jQuery('#'+chat_id).hide('fast', function () {
var idx = that.chats.indexOf(jid);
if (idx !== undefined) {
that.chats.splice(idx, 1);
}
that.removeChatFromCookie(jid);
that.reorderChats();
});
};
ob.restoreOpenChats = function () {
/* Check the open-chats cookie and re-open all the chatboxes it mentions.
* We need to wait for current chatbox creation to finish before we create the
* next, so we use a task buffer to make sure the next task is only
* executed after the previous is done.
*/
var cookie = jQuery.cookie('chats-open-'+xmppchat.username),
open_chats = [];
jQuery.cookie('chats-open-'+xmppchat.username, null, {path: '/'});
if (cookie) {
open_chats = cookie.split('|');
// FIXME: Change this so that the online contacts box is always created first.
for (var i=0; i<open_chats.length; i++) {
xmppchat.Taskbuffer.tasks.push({'that': this, 'method':this.getChatbox, 'parameters':[open_chats[i]]});
}
xmppchat.Taskbuffer.handleTasks();
}
};
ob.keyPressed = function (ev, textarea) {
if(ev.keyCode == 13 && !ev.shiftKey) {
var $textarea = jQuery(textarea),
message = $textarea.val(),
jid = $textarea.attr('data-recipient'),
form = $textarea.parent(),
now,
minutes,
time,
chat_content;
message = message.replace(/^\s+|\s+jQuery/g,"");
$textarea.val('').focus();
if (message !== '') {
xmppchat.Messages.sendMessage(jid, message, function () {
message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
list = message.match(/\b(http:\/\/www\.\S+\.\w+|www\.\S+\.\w+|http:\/\/(?=[^w]){3}\S+[\.:]\S+)[^ ]+\b/g);
if (list) {
for (i = 0; i < list.length; i++) {
message = message.replace( list[i], "<a target='_blank' href='" + escape( list[i] ) + "'>"+ list[i] + "</a>" );
}
}
now = new Date();
minutes = now.getMinutes().toString();
if (minutes.length==1) {minutes = '0'+minutes;}
time = now.toLocaleTimeString().substring(0,5);
chat_content = jQuery('#'+helpers.hash(jid)+' .chat-content');
chat_content.append(
'<div class="chat-message">' +
'<span class="chat-message-me">'+time+' me:&nbsp;&nbsp;</span>' +
'<span class="chat-message-content">'+message+'</span>' +
'</div>');
chat_content.scrollTop(chat_content[0].scrollHeight);
});
}
}
};
return ob;
})(xmppchat.UI || {}, jQuery, console || {log: function(){}} );
// Event handlers
// --------------
$(document).ready(function () {
var chatdata = jQuery('span#babble-client-chatdata'),
$toggle = $('a#toggle-online-users');
xmppchat.username = chatdata.attr('username');
xmppchat.base_url = chatdata.attr('base_url');
$toggle.unbind('click');
$toggle.bind('click', function (e) {
e.preventDefault();
if ($("div#online-users-container").is(':visible')) {
xmppchat.UI.closeChat('online-users-container');
} else {
xmppchat.UI.getChatbox('online-users-container');
}
});
$(document).unbind('jarnxmpp.message');
$(document).bind('jarnxmpp.message', function (event) {
xmppchat.UI.addMessageToChatbox(event);
});
$(document).bind('xmppchat.send_presence', function (event, jid, type) {
xmppchat.connection.send($pres({'type':type}));
});
$(document).unbind('jarnxmpp.presence');
$(document).bind('jarnxmpp.presence', function (event, jid, status, presence) {
xmppchat.UI.updateOnPresence(jid, status, presence);
});
$(document).unbind('jarnxmpp.connected');
$(document).bind('jarnxmpp.connected', function () {
// Logging
xmppchat.connection.rawInput = xmppchat.rawInput;
xmppchat.connection.rawOutput = xmppchat.rawOutput;
// Messages
xmppchat.connection.addHandler(xmppchat.Messages.messageReceived, null, 'message', 'chat');
//Roster
xmppchat.connection.addHandler(xmppchat.Roster.rosterResult, Strophe.NS.ROSTER, 'iq', 'result');
xmppchat.connection.addHandler(xmppchat.Roster.rosterSuggestedItem, 'http://jabber.org/protocol/rosterx', 'message', null);
// Presence
xmppchat.connection.addHandler(xmppchat.Presence.presenceReceived, null, 'presence', null);
xmppchat.UI.restoreOpenChats();
xmppchat.Presence.sendPresence();
});
$('a.user-details-toggle').live('click', function (e) {
var $field = $('[name="message"]:input', $(this).parent()[0]),
jid = $field.attr('data-recipient');
e.preventDefault();
xmppchat.UI.getChatbox(jid);
});
$('textarea.chat-textarea').live('keypress', function (ev) {
xmppchat.UI.keyPressed(ev, this);
});
$('a.close-chatbox-button').live('click', function (ev) {
var jid = $(ev.target).parent().parent().attr('data-recipient');
xmppchat.UI.closeChat(jid);
});
$('ul.tabs').tabs('div.panes > div');
$('select#select-xmpp-status').bind('change', function (ev) {
var jid = xmppchat.connection.jid,
value = ev.target.value;
xmppchat.Presence.sendPresence(value);
xmppchat.Storage.set(xmppchat.username+'-xmpp-status', value);
});
});