]> git.babelmonkeys.de Git - socialXMPP.git/blob - scripts/basic.js
Make PEP support a bit more flexible
[socialXMPP.git] / scripts / basic.js
1 var NS_VCARD = 'vcard-temp';
2 var NS_CAPS= 'http://jabber.org/protocol/caps';
3 var NS_PEP = 'http://jabber.org/protocol/pubsub#event';
4 var NS_TUNE = 'http://jabber.org/protocol/tune';
5 var BOSH_SERVICE = 'http://localhost:5280/http-bind/';
6
7 var localJID = null;
8 var connection   = null;
9 var show_log     = true;
10
11 var features = new Array(NS_CAPS, NS_TUNE+'+notify', Strophe.NS.DISCO_INFO);
12 var appName = 'socialXMPP';
13
14 var roster = new Array();
15
16 function log(msg) {
17     var entry = $('<div></div>').append(document.createTextNode(msg));
18     $('#log').append(entry);
19 }
20
21 function rawInput(data) {
22     log('RECV: ' + data);
23 }
24
25 function rawOutput(data) {
26     log('SENT: ' + data);
27 }
28
29 function jid2id(jid) {
30     jid = Strophe.getBareJidFromJid(jid);
31     return jid.split('@').join('-').split('.').join('-');
32 }
33
34 function populateVCard(e, jid) {
35     var easy_cases = new Array('FN', 'FAMILY', 'MIDDLE', 'GIVEN', 'NICKNAME', 'BDAY', 'CTRY', 'USERID');
36     for (var i=0; i<easy_cases.length; i++) {
37         var text = e.getElementsByTagName(easy_cases[i])[0];
38         if (text) {
39             text = Strophe.getText(text);
40             $('#'+easy_cases[i]).append(Strophe.xmlTextNode(text));
41         }
42     }
43     var avatar = e.getElementsByTagName('PHOTO')[0];
44     if (avatar) {
45         var mime = Strophe.getText(avatar.getElementsByTagName('TYPE')[0]);
46         var binval = Strophe.getText(avatar.getElementsByTagName('BINVAL')[0]);
47
48         $("#"+jid2id(jid)+" img").attr('src', 'data:'+mime+';base64,'+binval);
49         $("#PHOTO img").attr('src', 'data:'+mime+';base64,'+binval);
50     }
51     $(e).find('TEL:has(HOME)').each(function() {
52         $('#TELHOME').append(Strophe.xmlTextNode($(this).find('NUMBER').text()));
53     });
54     $(e).find('TEL:has(WORK)').each(function() {
55         $('#TELWORK').append(Strophe.xmlTextNode($(this).find('NUMBER').text()));
56     });
57     $(e).find('EMAIL:has(HOME)').each(function() {
58         $('#EMAILHOME').append(Strophe.xmlTextNode($(this).find('USERID').text()));
59     });
60     $(e).find('EMAIL:has(WORK)').each(function() {
61         $('#EMAILWORK').append(Strophe.xmlTextNode($(this).find('USERID').text()));
62     });
63
64     if (!roster[jid2id(jid)].tune.isEmpty()) {
65         $('#vCard ul').append('<li id="tune"><span class="vCardName">Tune: </span>Listening to '+
66                         roster[jid2id(jid)].tune.title + ' by ' + roster[jid2id(jid)].tune.artist +
67                         ' from ' + roster[jid2id(jid)].tune.source + '</li>')
68     }
69
70     $('#vCard').click(function () {
71         $('#vCard_container').slideUp("normal", function() {
72                 $('#box-overlay').hide();
73         });
74         roster[jid2id(jid)].visible = false;
75       });
76
77     $('#box-overlay').show();
78     $('#vCard_container').slideDown("normal");
79     roster[jid2id(jid)].visible = true;
80 }
81
82 function _cbVCard(e) {
83     var jid = e.getAttribute('from');
84     if (roster[jid2id(jid)].vCard == "") {
85         roster[jid2id(jid)].vCard = e;
86     }
87     if ($('#vCard_container').is(':visible')) {
88         $('#vCard_container').hide();
89     }
90     $('#vCard_container').empty();
91     $('#vCard_container').load('vCard.html #vCard', function() {populateVCard(e, jid);});
92
93     return false;
94 }
95
96 function _cbOwnVCard(e) {
97     $('#ownInfo').empty();
98     $('#ownInfo').load('vCard.html #ownvCard', function() {
99     var easy_cases = new Array('FN', 'FAMILY', 'MIDDLE', 'GIVEN', 'NICKNAME', 'BDAY', 'CTRY', 'USERID');
100     for (var i=0; i<easy_cases.length; i++) {
101         var text = e.getElementsByTagName(easy_cases[i])[0];
102         if (text) {
103             text = Strophe.getText(text);
104             $('#own'+easy_cases[i]).append(Strophe.xmlTextNode(text));
105         }
106     }
107     var avatar = e.getElementsByTagName('PHOTO')[0];
108     if (avatar) {
109         var mime = Strophe.getText(avatar.getElementsByTagName('TYPE')[0]);
110         var binval = Strophe.getText(avatar.getElementsByTagName('BINVAL')[0]);
111
112         $("#ownPHOTO img").attr('src', 'data:'+mime+';base64,'+binval);
113     }
114     $(e).find('TEL:has(HOME)').each(function() {
115         $('#ownTELHOME').append(Strophe.xmlTextNode($(this).find('NUMBER').text()));
116     });
117     $(e).find('TEL:has(WORK)').each(function() {
118         $('#ownTELWORK').append(Strophe.xmlTextNode($(this).find('NUMBER').text()));
119     });
120     $(e).find('EMAIL:has(HOME)').each(function() {
121         $('#ownEMAILHOME').append(Strophe.xmlTextNode($(this).find('USERID').text()));
122     });
123     $(e).find('EMAIL:has(WORK)').each(function() {
124         $('#ownEMAILWORK').append(Strophe.xmlTextNode($(this).find('USERID').text()));
125     });
126     $('#ownInfo').show();
127     });
128
129     return false;
130 }
131
132 function getVCard(jid) {
133     var id = connection.getUniqueId('vCardGet');
134     if (roster[jid2id(jid)].vCard == "") {
135         var vCardiq = $iq({'to':jid,
136                         'id':id,
137                         'type':'get'}
138                 ).c('vCard', {'xmlns':NS_VCARD});
139         connection.addHandler(_cbVCard, null, 'iq', 'result', id);
140         connection.send(vCardiq.tree());
141     } else {
142         _cbVCard(roster[jid2id(jid)].vCard);
143     }
144 }
145
146 function getOwnInfo() {
147     var id = connection.getUniqueId('vCardGet');
148     var vCardiq = $iq({'id': id, 'type': 'get'}
149         ).c('vCard', {'xmlns':NS_VCARD});
150     connection.addHandler(_cbOwnVCard, null, 'iq', 'result', id);
151     connection.send(vCardiq.tree());
152 }
153
154 function addFriend(jid, nick) {
155     roster[jid2id(jid)] = new Buddy(nick, jid);
156     $('#friends').append('<div class="friend" id="'+jid2id(jid)+'"><img src="imgs/none.png" /><br /><a class="nick">'+nick+'</a></div>');
157     $('#' + jid2id(jid) + ' img').click(function() {
158         getVCard(jid);
159     });
160     $('#' + jid2id(jid) + ' a').click(function() {
161         var id = jid2id(jid) + 'Chat';
162         if ($('#' + id).length <= 0) {
163             createBubble(jid);
164         }
165         $('#' + id).show();
166     });
167
168 }
169
170 function _cbRoster(e) {
171     var query = e.getElementsByTagName('query')[0];
172     var entries = query.getElementsByTagName('item');
173     for (var item=0; item<entries.length; item++) {
174         nick = entries[item].getAttribute('name');
175         if (!nick) {
176             nick = entries[item].getAttribute('jid').split('@')[0];
177         }
178         addFriend(entries[item].getAttribute('jid'), nick);
179     }
180     connection.addHandler(_cbPEP, NS_PEP, 'message');
181     var initialPresence = $pres().c('show').t('online').up().c('status').t('Hy, I am an socialXMPP instance').up().c('priority').t('1').up().c('c', {xmlns: NS_CAPS, hash: 'sha-1', node: 'http://jabber.babelmonkeys.de', ver: genCaps()}).up();
182     connection.send(initialPresence.tree());
183
184     $('#friends').show();
185
186     return false;
187 }
188
189 function getRoster() {
190     var id = connection.getUniqueId('roster');
191
192     var rosteriq = $iq({'id':id,
193                         'type':'get'}
194         ).c('query', {'xmlns':Strophe.NS.ROSTER});
195
196     connection.addHandler(_cbRoster, null, 'iq', 'result', id);
197     connection.send(rosteriq.tree());
198 }
199
200 function _cbDisco(e) {
201     var id = e.getAttribute('id');
202     var jid = e.getAttribute('from');
203
204     if (jid) {
205         var response = $iq({id: id, type: 'result', to: jid});
206     } else {
207         var response = $iq({id: id, type: 'result'});
208     }
209     var query = response.c('query', {xmlns: Strophe.NS.DISCO_INFO})
210     query.c('identity', {category: 'client', type: 'web', name: appName}).up();
211     for (var i = 0; i < features.length; i++) {
212         query.c('feature', {'var': features[i]}).up();
213     }
214     connection.send(response.tree());
215
216     return true;
217 }
218
219 function sendMessage(form, to) {
220     if (form.text.value) {
221         var id = jid2id(to) + 'Chat';
222         var message = $msg({'type': 'chat', 'to': to}).c('body').t(form.text.value);
223         connection.send(message.tree());
224         if ($('#' + id + ' p *').length > 0) {
225             $('#' + id + ' p').append('<br/>');
226         }
227         $('#' + id + ' p').append('<span class="receiver">' + localJID + ': </span>');
228         $('#' + id + ' p').append(form.text.value);
229         form.text.value = '';
230     }
231
232     return false;
233 }
234
235 function createBubble(jid) {
236     var id = jid2id(jid) + 'Chat';
237     $('body').append('<div class="chat" id="' + id + '" onmousedown="startDrag(this)"><a href="#" onclick="$(' + "'#" + id + "'" + ').hide()">Close</a>' +
238                     '<span class ="chatTitle"> ' + jid + '</span><p></p></div>');
239     $('#' + id).append('<form id="' + id + 'Form" class="chatForm" onsubmit="return sendMessage(this, \'' + jid + '\');" action="#"><input type="text" name="text" id="' + id + 'Text" class="chatForm" /></form>')
240     $('#' + id).css( 'top', $('#' + jid2id(jid)).position().top + 40);
241     $('#' + id).css( 'left', $('#' + jid2id(jid)).position().left + 40);
242 }
243
244
245 function _cbMessage(msg) {
246     if ($(msg).attr('type') != 'chat')
247         return true;
248     var jid = $(msg).attr('from');
249     var id = jid2id(jid) + 'Chat';
250     var body = $(msg).find('body:first').text();
251     body = escape(body);
252     body = body.replace(/%0A/g, '<br/>');
253     body = body.replace(/%3C/g, '&lt;');
254     body = body.replace(/%3E/g, '&gt;');
255     body = body.replace(/%26/g, '&amp;');
256     body = unescape(body);
257     if ($('#' + id).length <= 0) {
258         createBubble(jid);
259     }
260     if ($('#' + id + ' p *').length > 0) {
261         $('#' + id + ' p').append('<br/>');
262     }
263     $('#' + id + ' p').append('<span class="sender">' + jid + ': </span>');
264     $('#' + id + ' p').append(body);
265     $('#' + id).show();
266
267     return true;
268 }
269
270 function genCaps() {
271     var S = '';
272     S += 'client/web//' + appName + '<'
273     features.sort();
274     for (var i = 0; i < features.length; i++) {
275         S += features[i] + '<';
276     }
277     return b64_sha1(S);
278 }
279
280 function handleTune(jid, tuneXML) {
281     var tune = new Tune();
282     if (tuneXML.childNodes.length > 0) {
283         tune.artist = Strophe.getText(tuneXML.getElementsByTagName('artist')[0]);
284         tune.length= Strophe.getText(tuneXML.getElementsByTagName('length')[0]);
285         tune.rating= Strophe.getText(tuneXML.getElementsByTagName('rating')[0]);
286         tune.source= Strophe.getText(tuneXML.getElementsByTagName('source')[0]);
287         tune.title= Strophe.getText(tuneXML.getElementsByTagName('title')[0]);
288         tune.track= Strophe.getText(tuneXML.getElementsByTagName('track')[0]);
289         tune.uri= Strophe.getText(tuneXML.getElementsByTagName('uri')[0]);
290         if (roster[jid2id(jid)].visible == true) {
291             if ( $('#tune').length > 0) {
292                 $('#tune').empty();
293                 $('#tune').append('<span class="vCardName">Tune: </span>');
294                 $('#tune').append(Strophe.xmlTextNode('Listening to '+ tune.title +
295                         ' by ' + tune.artist + ' from ' + tune.source));
296             } else {
297                 $('#vCard ul').append('<li id="tune"><span class="vCardName">Tune: </span>Listening to '+ tune.title +
298                         ' by ' + tune.artist + ' from ' + tune.source + '</li>')
299             }
300         }
301     } else {
302         $('#tune').remove();
303     }
304     roster[jid2id(jid)].tune = tune;
305 }
306
307 function _cbPEP(e) {
308     var from = e.getAttribute('from');
309     if (Strophe.getBareJidFromJid(from) == Strophe.getBareJidFromJid(connection.jid)) {
310         return true; // Drop own PEP events
311     }
312     var items = e.getElementsByTagName('items')[0];
313     // Handle Tune
314     if (items.getAttribute('node') == NS_TUNE) {
315         handleTune(from, items.getElementsByTagName('tune')[0]);
316     }
317     return true;
318 }
319
320 function onConnect(status) {
321     if (status == Strophe.Status.CONNECTING) {
322         log('Strophe is connecting.');
323     } else if (status == Strophe.Status.CONNFAIL) {
324         log('Strophe failed to connect.');
325         showConnect();
326     } else if (status == Strophe.Status.DISCONNECTING) {
327         log('Strophe is disconnecting.');
328     } else if (status == Strophe.Status.DISCONNECTED) {
329         log('Strophe is disconnected.');
330         showConnect();
331     } else if (status == Strophe.Status.AUTHFAIL) {
332         log('Authentication failed');
333         if (connection) {
334             connection.disconnect();
335         }
336     } else if (status == Strophe.Status.CONNECTED) {
337         log('Strophe is connected.');
338         getOwnInfo();
339         getRoster();
340         connection.addHandler(_cbDisco, Strophe.NS.DISCO_INFO, 'iq', 'get');
341         connection.addHandler(_cbMessage, Strophe.NS.CLIENT, 'message');
342     }
343 }
344
345 function showConnect() {
346     var jid = $('#jid');
347     var pass = $('#pass');
348     var button = $('#connect').get(0);  
349
350     $('#log').empty();
351     $('#ownInfo').empty();
352     $('#ownInfo').hide();
353     $('#vCard_container').empty();
354     $('#friends').empty();
355     $('#friends').hide();
356     $('.chat').remove();
357     $('label').show();
358     jid.show();
359     pass.show();
360     button.value = 'connect';
361     return false;
362 }
363
364 function showDisconnect() {
365     var jid = $('#jid');
366     var pass = $('#pass');
367     var button = $('#connect').get(0);  
368
369     button.value = 'disconnect';
370     pass.hide();
371     jid.hide();
372     $('label').hide();
373     return false;
374 }
375
376 $(document).ready(function () {
377     connection = new Strophe.Connection(BOSH_SERVICE);
378     connection.rawInput = rawInput;
379     connection.rawOutput = rawOutput;
380
381     $("#log_toggle").click(function () {
382         $("#log").toggle();     
383       });
384
385     $('#cred').bind('submit', function () {
386         var button = $('#connect').get(0);
387         var jid = $('#jid');
388         var pass = $('#pass');  
389         localJID = jid.get(0).value;
390         
391         if (button.value == 'connect') {
392             showDisconnect();
393             connection.connect(localJID,
394                                pass.get(0).value,
395                                onConnect);
396         } else {
397             connection.disconnect();
398         }
399         return false;
400     });
401 });
402
403 // Element moving
404 var dragElement = null;
405 var mouseX = 0;
406 var mouseY = 0;
407 var offX = 0;
408 var offY = 0;
409
410 function startDrag(element) {
411     dragElement = element;
412     offX = mouseX - dragElement.offsetLeft;
413     offY = mouseY - dragElement.offsetTop;
414 }
415
416 function doDrag(eve) {
417     mouseX = eve.pageX;
418     mouseY = eve.pageY;
419
420     if (dragElement) {
421         dragElement.style.left = (mouseX - offX) + 'px';
422         dragElement.style.top = (mouseY - offY) + 'px';
423     }
424 }
425
426 function stopDrag(eve) {
427     dragElement = null;
428 }
429
430 onunload = function() {
431     if (connection) {
432         connection.disconnect();
433     }
434 }
435
436 onmousemove = doDrag;
437 onmouseup = stopDrag;
438