]> git.mxchange.org Git - friendica-addons.git/blob - jappixmini/jappix/js/connection.js
85a718c5fa24b2d0eb13b387800ad8d60761ca39
[friendica-addons.git] / jappixmini / jappix / js / connection.js
1 /*
2
3 Jappix - An open social platform
4 These are the connection JS script for Jappix
5
6 -------------------------------------------------
7
8 License: AGPL
9 Author: Vanaryon
10 Last revision: 29/08/11
11
12 */
13
14 // Does the user login
15 var CURRENT_SESSION = false;
16
17 function doLogin(lNick, lServer, lPass, lResource, lPriority, lRemember) {
18         try {
19                 // We remove the not completed class to avoid problems
20                 $('#home .loginer input').removeClass('please-complete');
21                 
22                 // We add the login wait div
23                 showGeneralWait();
24                 
25                 // We define the http binding parameters
26                 oArgs = new Object();
27                 
28                 if(HOST_BOSH_MAIN)
29                         oArgs.httpbase = HOST_BOSH_MAIN;
30                 else
31                         oArgs.httpbase = HOST_BOSH;
32                 
33                 // We create the new http-binding connection
34                 con = new JSJaCHttpBindingConnection(oArgs);
35                 
36                 // And we handle everything that happen
37                 setupCon(con);
38                 
39                 // Generate a resource
40                 var random_resource = getDB('session', 'resource');
41                 
42                 if(!random_resource)
43                         random_resource = lResource + ' (' + (new Date()).getTime() + ')';
44                 
45                 // We retrieve what the user typed in the login inputs
46                 oArgs = new Object();
47                 oArgs.domain = trim(lServer);
48                 oArgs.username = trim(lNick);
49                 oArgs.resource = random_resource;
50                 oArgs.pass = lPass;
51                 oArgs.secure = true;
52                 oArgs.xmllang = XML_LANG;
53                 
54                 // Store the resource (for reconnection)
55                 setDB('session', 'resource', random_resource);
56                 
57                 // Generate a session XML to be stored
58                 session_xml = '<session><stored>true</stored><domain>' + lServer.htmlEnc() + '</domain><username>' + lNick.htmlEnc() + '</username><resource>' + lResource.htmlEnc() + '</resource><password>' + lPass.htmlEnc() + '</password><priority>' + lPriority.htmlEnc() + '</priority></session>';
59                 
60                 // Save the session parameters (for reconnect if network issue)
61                 CURRENT_SESSION = session_xml;
62                 
63                 // Remember me?
64                 if(lRemember)
65                         setDB('remember', 'session', 1);
66                 
67                 // We store the infos of the user into the data-base
68                 setDB('priority', 1, lPriority);
69                 
70                 // We connect !
71                 con.connect(oArgs);
72                 
73                 // Change the page title
74                 pageTitle('wait');
75                 
76                 logThis('Jappix is connecting...', 3);
77         }
78         
79         catch(e) {
80                 // Logs errors
81                 logThis('Error while logging in: ' + e, 1);
82                 
83                 // Reset Jappix
84                 destroyTalkPage();
85                 
86                 // Open an unknown error
87                 openThisError(2);
88         }
89         
90         finally {
91                 return false;
92         }
93 }
94
95 // Handles the user registration
96 function handleRegistered() {
97         logThis('A new account has been registered.', 3);
98         
99         // We remove the waiting image
100         removeGeneralWait();
101         
102         // Reset the title
103         pageTitle('home');
104         
105         // We show the success information
106         $('#home .registerer .success').fadeIn('fast');
107         
108         // We quit the session
109         logout();
110 }
111
112 // Does the user registration
113 function doRegister(username, domain, pass) {
114         logThis('Trying to register an account...', 3);
115         
116         try {
117                 // We define the http binding parameters
118                 oArgs = new Object();
119                 
120                 if(HOST_BOSH_MAIN)
121                         oArgs.httpbase = HOST_BOSH_MAIN;
122                 else
123                         oArgs.httpbase = HOST_BOSH;
124                 
125                 // We create the new http-binding connection
126                 con = new JSJaCHttpBindingConnection(oArgs);
127                 
128                 // We setup the connection !
129                 con.registerHandler('onconnect', handleRegistered);
130                 con.registerHandler('onerror', handleError);
131                 
132                 // We retrieve what the user typed in the register inputs
133                 oArgs = new Object();
134                 oArgs.domain = trim(domain);
135                 oArgs.username = trim(username);
136                 oArgs.resource = JAPPIX_RESOURCE + ' Register (' + (new Date()).getTime() + ')';
137                 oArgs.pass = pass;
138                 oArgs.register = true;
139                 oArgs.secure = true;
140                 oArgs.xmllang = XML_LANG;
141                 
142                 con.connect(oArgs);
143                 
144                 // We change the registered information text
145                 $('#home .homediv.registerer').append(
146                         '<div class="info success">' + 
147                                 _e("You have been registered, here is your XMPP address:") + ' <b>' + con.username.htmlEnc() + '@' + con.domain.htmlEnc() + '</b> - <a href="#">' + _e("Login") + '</a>' + 
148                         '</div>'
149                 );
150                 
151                 // Login link
152                 $('#home .homediv.registerer .success a').click(function() {
153                         return doLogin(con.username, con.domain, con.pass, con.resource, '10', false);
154                 });
155                 
156                 // Show the waiting image
157                 showGeneralWait();
158                 
159                 // Change the page title
160                 pageTitle('wait');
161         }
162         
163         catch(e) {
164                 // Logs errors
165                 logThis(e, 1);
166         }
167         
168         finally {
169                 return false;
170         }
171 }
172
173 // Does the user anonymous login
174 function doAnonymous() {
175         logThis('Trying to login anonymously...', 3);
176         
177         var aPath = '#home .anonymouser ';
178         var room = $(aPath + '.room').val();
179         var nick = $(aPath + '.nick').val();
180         
181         // If the form is correctly completed
182         if(room && nick) {
183                 // We remove the not completed class to avoid problems
184                 $('#home .anonymouser input').removeClass('please-complete');
185                 
186                 // Redirect the user to the anonymous room
187                 window.location.href = JAPPIX_LOCATION + '?r=' + room + '&n=' + nick;
188         }
189         
190         // We check if the form is entirely completed
191         else {
192                 $(aPath + 'input[type=text]').each(function() {
193                         var select = $(this);
194                         
195                         if(!select.val())
196                                 $(document).oneTime(10, function() {
197                                         select.addClass('please-complete').focus();
198                                 });
199                         else
200                                 select.removeClass('please-complete');  
201                 });
202         }
203         
204         return false;
205 }
206
207 // Handles the user connected event
208 var CONNECTED = false;
209
210 function handleConnected() {
211         logThis('Jappix is now connected.', 3);
212         
213         // Connection markers
214         CONNECTED = true;
215         RECONNECT_TRY = 0;
216         RECONNECT_TIMER = 0;
217         
218         // We hide the home page
219         $('#home').hide();
220         
221         // Not resumed?
222         if(!RESUME) {
223                 // Remember the session?
224                 if(getDB('remember', 'session'))
225                         setPersistent('session', 1, CURRENT_SESSION);
226                 
227                 // We show the chatting app.
228                 createTalkPage();
229                 
230                 // We reset the homepage
231                 switchHome('default');
232                 
233                 // We get all the other things
234                 getEverything();
235                 
236                 // Set last activity stamp
237                 LAST_ACTIVITY = getTimeStamp();
238         }
239         
240         // Resumed
241         else {
242                 // Send our presence
243                 presenceSend();
244                 
245                 // Change the title
246                 updateTitle();
247         }
248         
249         // Remove the waiting item
250         removeGeneralWait();
251 }
252
253 // Handles the user disconnected event
254 function handleDisconnected() {
255         logThis('Jappix is now disconnected.', 3);
256         
257         // Normal disconnection
258         if(!CURRENT_SESSION && !CONNECTED)
259                 destroyTalkPage();
260 }
261
262 // Setups the normal connection
263 function setupCon(con) {
264         // We setup all the necessary handlers for the connection
265         con.registerHandler('message', handleMessage);
266         con.registerHandler('presence', handlePresence);
267         con.registerHandler('iq', handleIQ);
268         con.registerHandler('onconnect', handleConnected);
269         con.registerHandler('onerror', handleError);
270         con.registerHandler('ondisconnect', handleDisconnected);
271 }
272
273 // Logouts from the server
274 function logout() {
275         // We are not connected
276         if(!isConnected())
277                 return false;
278         
279         // Disconnect from the XMPP server
280         con.disconnect();
281         
282         logThis('Jappix is disconnecting...', 3);
283 }
284
285 // Terminates a session
286 function terminate() {
287         if(!isConnected())
288                 return;
289         
290         // Clear temporary session storage
291         resetConMarkers();
292         
293         // Show the waiting item (useful if BOSH is sloooow)
294         showGeneralWait();
295         
296         // Change the page title
297         pageTitle('wait');
298         
299         // Disconnect from the XMPP server
300         logout();
301 }
302
303 // Quitss a session
304 function quit() {
305         if(!isConnected())
306                 return;
307         
308         // We show the waiting image
309         showGeneralWait();
310         
311         // Change the page title
312         pageTitle('wait');
313         
314         // We disconnect from the XMPP server
315         logout();
316 }
317
318 // Creates the reconnect pane
319 var RECONNECT_TRY = 0;
320 var RECONNECT_TIMER = 0;
321
322 function createReconnect(mode) {
323         logThis('This is not a normal disconnection, show the reconnect pane...', 1);
324         
325         // Reconnect pane not yet displayed?
326         if(!exists('#reconnect')) {
327                 // Blur the focused input/textarea/select
328                 $('input, select, textarea').blur();
329                 
330                 // Create the HTML code
331                 var html = '<div id="reconnect" class="lock">' + 
332                                 '<div class="pane">' + 
333                                         _e("Due to a network issue, you were disconnected. What do you want to do now?");
334                 
335                 // Can we cancel reconnection?
336                 if(mode == 'normal')
337                         html += '<a href="#" class="finish cancel">' + _e("Cancel") + '</a>';
338                 
339                 html += '<a href="#" class="finish reconnect">' + _e("Reconnect") + '</a>' + 
340                         '</div></div>';
341                 
342                 // Append the code
343                 $('body').append(html);
344                 
345                 // Click events
346                 if(mode == 'normal')
347                         $('#reconnect a.finish.cancel').click(function() {
348                                 return cancelReconnect();
349                         });
350                 
351                 $('#reconnect a.finish.reconnect').click(function() {
352                         return acceptReconnect(mode);
353                 });
354                 
355                 // Try to reconnect automatically after a while
356                 if(RECONNECT_TRY < 5)
357                         RECONNECT_TIMER = 5 + (5 * RECONNECT_TRY);
358                 else
359                         RECONNECT_TIMER = 120;
360                 
361                 // Change the try number
362                 RECONNECT_TRY++;
363                 
364                 // Fire the event!
365                 $('#reconnect a.finish.reconnect').everyTime('1s', function() {
366                         // We can reconnect!
367                         if(RECONNECT_TIMER == 0)
368                                 return acceptReconnect(mode);
369                         
370                         // Button text
371                         if(RECONNECT_TIMER <= 10)
372                                 $(this).text(_e("Reconnect") + ' (' + RECONNECT_TIMER + ')');
373                         
374                         // Remove 1 second
375                         RECONNECT_TIMER--;
376                 });
377                 
378                 // Page title
379                 updateTitle();
380         }
381 }
382
383 // Reconnects the user if he was disconnected (network issue)
384 var RESUME = false;
385
386 function acceptReconnect(mode) {
387         logThis('Trying to reconnect the user...', 3);
388         
389         // Resume marker
390         RESUME = true;
391         
392         // Show waiting item
393         showGeneralWait();
394         
395         // Reset some various stuffs
396         var groupchats = '#page-engine .page-engine-chan[data-type=groupchat]';
397         $(groupchats + ' .list .role').hide();
398         $(groupchats + ' .one-group, ' + groupchats + ' .list .user').remove();
399         $(groupchats).attr('data-initial', 'false');
400         
401         // Stop the timer
402         $('#reconnect a.finish.reconnect').stopTime();
403         
404         // Remove the reconnect pane
405         $('#reconnect').remove();
406         
407         // Try to login again
408         if(mode == 'normal')
409                 loginFromSession(XMLFromString(CURRENT_SESSION));
410         else if(mode == 'anonymous')
411                 anonymousLogin(HOST_ANONYMOUS);
412         
413         return false;
414 }
415
416 // Cancel the reconnection of user account (network issue)
417 function cancelReconnect() {
418         logThis('User has canceled automatic reconnection...', 3);
419         
420         // Stop the timer
421         $('#reconnect a.finish.reconnect').stopTime();
422         
423         // Remove the reconnect pane
424         $('#reconnect').remove();
425         
426         // Destroy the talk page
427         destroyTalkPage();
428         
429         // Renitialize the previous session parameters
430         resetConMarkers();
431         
432         return false;
433 }
434
435 // Clears session reminder database
436 function clearLastSession() {
437         // Clear temporary storage
438         resetConMarkers();
439         
440         // Clear persistent storage
441         if($(XMLFromString(getPersistent('session', 1))).find('stored').text() == 'true')
442                 removePersistent('session', 1);
443 }
444
445 // Resets the connection markers
446 function resetConMarkers() {
447         CURRENT_SESSION = false;
448         CONNECTED = false;
449         RESUME = false;
450         RECONNECT_TRY = 0;
451         RECONNECT_TIMER = 0;
452 }
453
454 // Logins from a saved session
455 function loginFromSession(data) {
456         // Select the data
457         var session = $(data);
458         
459         // Fire the login event
460         doLogin(
461                 session.find('username').text(),
462                 session.find('domain').text(),
463                 session.find('password').text(),
464                 session.find('resource').text(),
465                 session.find('priority').text(),
466                 false
467         );
468 }
469
470 // Quits a session normally
471 function normalQuit() {
472         // Reset our database
473         clearLastSession();
474         
475         // We quit the current session
476         quit();
477         
478         // We show an info
479         openThisInfo(3);
480         
481         return false;
482 }
483
484 // Gets all the users stuffs
485 function getEverything() {
486         getFeatures();
487         getRoster();
488         listPrivacy();
489         getStorage(NS_ROSTERNOTES);
490 }
491
492 // Plugin launcher
493 function launchConnection() {
494         // Logouts when Jappix is closed
495         $(window).bind('beforeunload', terminate);
496         
497         // Nothing to do when anonymous!
498         if(isAnonymous())
499                 return;
500         
501         // Try to resume a stored session, if not anonymous
502         var session = XMLFromString(getPersistent('session', 1));
503         
504         if($(session).find('stored').text() == 'true') {
505                 // Hide the homepage
506                 $('#home').hide();
507                 
508                 // Show the waiting icon
509                 showGeneralWait();
510                 
511                 // Login!
512                 loginFromSession(session);
513                 
514                 logThis('Saved session found, resuming it...', 3);
515         }
516         
517         // Not connected, maybe a XMPP link is submitted?
518         else if((parent.location.hash != '#OK') && LINK_VARS['x']) {
519                 switchHome('loginer');
520                 
521                 logThis('A XMPP link is set, switch to login page.', 3);
522         }
523 }
524
525 // Launch this plugin!
526 $(document).ready(launchConnection);