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