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