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