]> cgit.babelmonkeys.de Git - socialXMPP.git/blob - scripts/basic.js
(Coding) style
[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     if ($('#' + jid2id(jid)).length > 0) {
176         $('#' + id).css( 'top', $('#' + jid2id(jid)).position().top + 40);
177         $('#' + id).css( 'left', $('#' + jid2id(jid)).position().left + 40);
178     }
179 }
180
181 function addFriend(jid, nick) {
182     roster[jid2id(jid)] = new Buddy(nick, jid);
183     $('#friends').append('<div class="friend" id="'+jid2id(jid)+'"><img src="imgs/none.png" /><br /><a class="nick">'+nick+'</a></div>');
184     $('#' + jid2id(jid) + ' img').click(function() {
185         getVCard(jid);
186     });
187     $('#' + jid2id(jid) + ' a').click(function() {
188         var id = jid2id(jid) + 'Chat';
189         if ($('#' + id).length <= 0) {
190             createBubble(jid);
191         }
192         $('#' + id).show();
193     });
194
195 }
196
197 function handleTune(jid, tuneXML) {
198     var tune = new Tune();
199     if (tuneXML.childNodes.length > 0) {
200         tune.artist = Strophe.getText(tuneXML.getElementsByTagName('artist')[0]);
201         tune.length= Strophe.getText(tuneXML.getElementsByTagName('length')[0]);
202         tune.rating= Strophe.getText(tuneXML.getElementsByTagName('rating')[0]);
203         tune.source= Strophe.getText(tuneXML.getElementsByTagName('source')[0]);
204         tune.title= Strophe.getText(tuneXML.getElementsByTagName('title')[0]);
205         tune.track= Strophe.getText(tuneXML.getElementsByTagName('track')[0]);
206         tune.uri= Strophe.getText(tuneXML.getElementsByTagName('uri')[0]);
207         if (roster[jid2id(jid)].visible === true) {
208             if ( $('#tune').length > 0) {
209                 $('#tune').empty();
210                 $('#tune').append('<span class="vCardName">Tune: </span>');
211                 $('#tune').append(Strophe.xmlTextNode('Listening to '+ tune.title +
212                         ' by ' + tune.artist + ' from ' + tune.source));
213             } else {
214                 $('#vCard ul').append('<li id="tune"><span class="vCardName">Tune: </span>Listening to '+ tune.title +
215                         ' by ' + tune.artist + ' from ' + tune.source + '</li>');
216             }
217         }
218     } else {
219         $('#tune').remove();
220     }
221     roster[jid2id(jid)].tune = tune;
222 }
223
224 function _cbPEP(e) {
225     var from = e.getAttribute('from'), items;
226     if (Strophe.getBareJidFromJid(from) == Strophe.getBareJidFromJid(connection.jid)) {
227         return true; // Drop own PEP events
228     }
229     items = e.getElementsByTagName('items')[0];
230     // Handle Tune
231     if (items.getAttribute('node') == Strophe.NS.TUNE) {
232         handleTune(from, items.getElementsByTagName('tune')[0]);
233     }
234     return true;
235 }
236
237 function _cbRoster(e) {
238     var query = e.getElementsByTagName('query')[0],
239     entries = query.getElementsByTagName('item'), item, nick, initialPresence;
240     for (item = 0; item < entries.length; item++) {
241         nick = entries[item].getAttribute('name');
242         if (!nick) {
243             nick = entries[item].getAttribute('jid').split('@')[0];
244         }
245         addFriend(entries[item].getAttribute('jid'), nick);
246     }
247     connection.addHandler(_cbPEP, Strophe.NS.PEP, 'message');
248     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();
249     connection.send(initialPresence.tree());
250
251     $('#friends').css('display', 'table');
252
253     return false;
254 }
255
256 function getRoster() {
257     var id, rosteriq;
258     id = connection.getUniqueId('roster');
259
260     rosteriq = $iq({'id':id,
261                         'type':'get'}
262         ).c('query', {'xmlns':Strophe.NS.ROSTER});
263
264     connection.addHandler(_cbRoster, null, 'iq', 'result', id);
265     connection.send(rosteriq.tree());
266 }
267
268 function _cbDisco(e) {
269     var i, id, jid, response, query, response;
270     id = e.getAttribute('id');
271     jid = e.getAttribute('from');
272
273     if (jid) {
274         response = $iq({id: id, type: 'result', to: jid});
275     } else {
276         response = $iq({id: id, type: 'result'});
277     }
278     query = response.c('query', {xmlns: Strophe.NS.DISCO_INFO});
279     query.c('identity', {category: 'client', type: 'web', name: appName}).up();
280     for (i = 0; i < features.length; i++) {
281         query.c('feature', {'var': features[i]}).up();
282     }
283     connection.send(response.tree());
284
285     return true;
286 }
287
288 function sendMessage(form, to) {
289     var id, message;
290     if (form.text.value) {
291         id = jid2id(to) + 'Chat';
292         message = $msg({'type': 'chat', 'to': to}).c('body').t(form.text.value);
293         connection.send(message.tree());
294         if ($('#' + id + ' p *').length > 0) {
295             $('#' + id + ' p').append('<br/>');
296         }
297         $('#' + id + ' p').append('<span class="receiver">' + localJID + ': </span>');
298         $('#' + id + ' p').append(form.text.value);
299         form.text.value = '';
300     }
301
302     return false;
303 }
304
305 function _cbMessage(msg) {
306     var id, jid, body;
307     if ($(msg).attr('type') != 'chat') {
308         return true;
309     }
310     jid = $(msg).attr('from');
311     id = jid2id(jid) + 'Chat';
312     body = $(msg).find('body:first').text();
313     body = escape(body);
314     body = body.replace(/%0A/g, '<br/>');
315     body = body.replace(/%3C/g, '&lt;');
316     body = body.replace(/%3E/g, '&gt;');
317     body = body.replace(/%26/g, '&amp;');
318     body = unescape(body);
319     if ($('#' + id).length <= 0) {
320         createBubble(jid);
321     }
322     if ($('#' + id + ' p *').length > 0) {
323         $('#' + id + ' p').append('<br/>');
324     }
325     $('#' + id + ' p').append('<span class="sender">' + jid + ': </span>');
326     $('#' + id + ' p').append(body);
327     $('#' + id).show();
328
329     return true;
330 }
331
332 function showConnect() {
333     var jid, pass, button;
334     jid = $('#jid');
335     pass = $('#pass');
336     button = $('#connect').get(0);
337
338     $('#log').empty();
339     $('#ownInfo').empty();
340     $('#ownInfo').hide();
341     $('#vCard_container').empty();
342     $('#friends').empty();
343     $('#friends').hide();
344     $('.chat').remove();
345     $('label').show();
346     jid.show();
347     pass.show();
348     button.value = 'connect';
349     return false;
350 }
351
352 function onConnect(status) {
353     if (status == Strophe.Status.CONNECTING) {
354         log('Strophe is connecting.');
355     } else if (status == Strophe.Status.CONNFAIL) {
356         log('Strophe failed to connect.');
357         showConnect();
358     } else if (status == Strophe.Status.DISCONNECTING) {
359         log('Strophe is disconnecting.');
360     } else if (status == Strophe.Status.DISCONNECTED) {
361         log('Strophe is disconnected.');
362         showConnect();
363     } else if (status == Strophe.Status.AUTHFAIL) {
364         log('Authentication failed');
365         if (connection) {
366             connection.disconnect();
367         }
368     } else if (status == Strophe.Status.CONNECTED) {
369         log('Strophe is connected.');
370         getOwnInfo();
371         getRoster();
372         connection.addHandler(_cbDisco, Strophe.NS.DISCO_INFO, 'iq', 'get');
373         connection.addHandler(_cbMessage, Strophe.NS.CLIENT, 'message');
374     }
375 }
376
377 function showDisconnect() {
378     var jid, pass, button;
379     jid = $('#jid');
380     pass = $('#pass');
381     button = $('#connect').get(0);
382
383     button.value = 'disconnect';
384     pass.hide();
385     jid.hide();
386     $('label').hide();
387     return false;
388 }
389
390 $(document).ready(function () {
391     var button, jid, pass;
392     if (DEBUG) {
393         $('#log_container').show();
394     }
395     connection = new Strophe.Connection(BOSH_SERVICE);
396     connection.rawInput = rawInput;
397     connection.rawOutput = rawOutput;
398
399     $("#log_toggle").click(function () {
400         $("#log").toggle();
401       });
402
403     $('#cred').bind('submit', function () {
404         button = $('#connect').get(0);
405         jid = $('#jid');
406         pass = $('#pass');
407         localJID = jid.get(0).value;
408
409         if (button.value == 'connect') {
410             showDisconnect();
411             connection.connect(localJID,
412                                pass.get(0).value,
413                                onConnect);
414         } else {
415             connection.disconnect();
416         }
417         return false;
418     });
419 });
420
421 // Element moving
422 var dragElement = null;
423 var mouseX = 0;
424 var mouseY = 0;
425 var offX = 0;
426 var offY = 0;
427
428 function startDrag(element) {
429     dragElement = element;
430     offX = mouseX - dragElement.offsetLeft;
431     offY = mouseY - dragElement.offsetTop;
432 }
433
434 function doDrag(eve) {
435     mouseX = eve.pageX;
436     mouseY = eve.pageY;
437
438     if (dragElement) {
439         dragElement.style.left = (mouseX - offX) + 'px';
440         dragElement.style.top = (mouseY - offY) + 'px';
441     }
442 }
443
444 function stopDrag(eve) {
445     dragElement = null;
446 }
447
448 onunload = function() {
449     if (connection) {
450         connection.disconnect();
451     }
452 };
453
454 onmousemove = doDrag;
455 onmouseup = stopDrag;
456