5d24dac381f9c0a9d049c266265fad16ea28071c
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.js
1 /******************************************************************************
2  * Copyright 2012 Intel Corporation.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  * http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *****************************************************************************/
16
17
18
19 /*****************************************************************************/
20
21 var dbus = { // hook object for dbus types not translated by python-json
22                 Double: function(value, level) {
23                         return value;
24                 }
25 };
26
27
28
29 /*****************************************************************************/
30
31 var cloudeebus = window.cloudeebus = {
32                 version: "0.4.0",
33                 minVersion: "0.3.2"
34 };
35
36 cloudeebus.reset = function() {
37         cloudeebus.sessionBus = null;
38         cloudeebus.systemBus = null;
39         cloudeebus.wampSession = null;
40         cloudeebus.uri = null;
41 };
42
43
44 cloudeebus.log = function(msg) { 
45 };
46
47
48 cloudeebus.versionCheck = function(version) {
49         var ver = version.split(".");
50         var min = cloudeebus.minVersion.split(".");
51         for (var i=0; i<ver.length; i++) {
52                 if (Number(ver[i]) > Number(min[i]))
53                         return true;
54                 if (Number(ver[i]) < Number(min[i]))
55                         return false;
56         }
57         return true;
58 };
59
60
61 cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
62         cloudeebus.reset();
63         cloudeebus.uri = uri;
64         
65         function onCloudeebusVersionCheckCB(version) {
66                 if (cloudeebus.versionCheck(version)) {
67                         cloudeebus.log("Connected to " + cloudeebus.uri);
68                         if (successCB)
69                                 successCB();
70                 } else {
71                         var errorMsg = "Cloudeebus server version " + version + " unsupported, need version " + cloudeebus.minVersion + " or superior";
72                         cloudeebus.log(errorMsg);
73                         if (errorCB)
74                                 errorCB(errorMsg);
75                 }
76         }
77         
78         function onWAMPSessionAuthErrorCB(error) {
79                 cloudeebus.log("Authentication error: " + error.desc);
80                 if (errorCB)
81                         errorCB(error.desc);
82         }
83         
84         function onWAMPSessionAuthenticatedCB(permissions) {
85                 cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
86                 cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
87                 cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
88         }
89         
90         function onWAMPSessionChallengedCB(challenge) {
91                 var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
92                 cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
93         }
94         
95         function onWAMPSessionConnectedCB(session) {
96                 cloudeebus.wampSession = session;
97                 if (manifest)
98                         cloudeebus.wampSession.authreq(
99                                         manifest.name, 
100                                         {permissions: manifest.permissions}
101                                 ).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
102                 else
103                         cloudeebus.wampSession.authreq().then(function() {
104                                 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
105                                 }, onWAMPSessionAuthErrorCB);
106         }
107
108         function onWAMPSessionErrorCB(code, reason) {
109                 if (code == ab.CONNECTION_UNSUPPORTED) {
110                         cloudeebus.log("Browser is not supported");
111                 }
112                 else {
113                         cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
114                 }
115                 if (errorCB)
116                         errorCB(reason);
117         }
118
119         return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
120 };
121
122
123 cloudeebus.SessionBus = function() {
124         return cloudeebus.sessionBus;
125 };
126
127
128 cloudeebus.SystemBus = function() {
129         return cloudeebus.systemBus;
130 };
131
132
133
134 /*****************************************************************************/
135
136 cloudeebus.BusConnection = function(name, session) {
137         this.name = name;
138         this.wampSession = session;
139         this.service = null;
140         return this;
141 };
142
143
144 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
145         var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
146         if (introspectCB)
147                 proxy._introspect(introspectCB, errorCB);
148         return proxy;
149 };
150
151
152 cloudeebus.BusConnection.prototype.addService = function(serviceName, successCB, errorCB) {
153         var self = this;
154         
155         cloudeebusService = new cloudeebus.Service(this.wampSession, this, serviceName);
156         
157         function busServiceAddedSuccessCB(service) {
158                 self.service = cloudeebusService;
159                 if (successCB)
160                         successCB(cloudeebusService);
161         }
162         
163         cloudeebusService.add(busServiceAddedSuccessCB, errorCB);
164         return cloudeebusService;
165 };
166
167 cloudeebus.BusConnection.prototype.removeService = function(serviceName, successCB, errorCB) {
168         var self = this;
169         
170         function busServiceRemovedSuccessCB(serviceName) {
171                 // Be sure we are removing the service requested...
172                 if (serviceName == self.service.name) {
173                         self.service = null;
174                         if (successCB)
175                                 successCB(serviceName);
176                 }
177         }
178         
179         cloudeebusService.remove(busServiceRemovedSuccessCB, errorCB);
180 };
181
182
183 /*****************************************************************************/
184
185 cloudeebus.Service = function(session, busConnection, name) {
186         this.wampSession = session;
187         this.busConnection = busConnection; 
188         this.name = name;
189         this.isCreated = false;
190         return this;
191 };
192
193 cloudeebus.Service.prototype.add = function(successCB, errorCB) {
194         var self = this;
195         
196         function ServiceAddedSuccessCB(serviceName) {
197                 if (successCB) {
198                         try {
199                                 successCB(self);
200                         }
201                         catch (e) {
202                                 alert("Exception adding service " + serviceName + " : " + e);
203                         }
204                 }
205         }
206         
207         var arglist = [
208             this.busConnection,
209             this.name
210             ];
211
212         // call dbusSend with bus type, destination, object, message and arguments
213         this.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, errorCB);
214 };
215
216 cloudeebus.Service.prototype.remove = function(successCB, errorCB) {
217         function ServiceRemovedSuccessCB(serviceName) {
218                 if (successCB) {
219                         try {
220                                 successCB(serviceName);
221                         }
222                         catch (e) {
223                                 alert("Exception removing service " + serviceName + " : " + e);
224                         }
225                 }
226         }
227         
228         var arglist = [
229             this.name
230             ];
231
232         // call dbusSend with bus type, destination, object, message and arguments
233         this.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, errorCB);
234 };
235
236 cloudeebus.Service.prototype._searchMethod = function(ifName, method, objectJS) {
237
238         var funcToCall = null;
239         
240         // Check if 'objectJS' has a member 'interfaceProxies' with an interface named 'ifName' 
241         // and a method named 'method'
242         if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName] &&
243                 objectJS.interfaceProxies[ifName][method]) {
244                 funcToCall = objectJS.interfaceProxies[ifName][method];
245         } else {
246                 // retrieve the method directly from 'root' of objectJs
247                 funcToCall = objectJS[method];
248         }
249
250         return funcToCall;
251 };
252
253 cloudeebus.Service.prototype._addMethod = function(objectPath, ifName, method, objectJS) {
254
255         var service = this;
256         var methodId = this.name + "#" + objectPath + "#" + ifName + "#" + method;
257         var funcToCall = this._searchMethod(ifName, method, objectJS);
258
259         if (funcToCall == null)
260                 cloudeebus.log("Method " + method + " doesn't exist in Javascript object");
261         else {
262                 objectJS.wrapperFunc[method] = function() {
263                         var result;
264                         var methodId = arguments[0];
265                         var callDict = {};
266                         // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
267                         eval("callDict = " + arguments[1]);
268                         try {
269                                 result = funcToCall.apply(objectJS, callDict.args);
270                                 service._returnMethod(methodId, callDict.callIndex, true, result);
271                         }
272                         catch (e) {
273                                 cloudeebus.log("Method " + ifName + "." + method + " call on " + objectPath + " exception: " + e);
274                                 service._returnMethod(methodId, callDict.callIndex, false, e.message);
275                         }
276                 };
277                 this._registerMethod(methodId, objectJS.wrapperFunc[method]);
278         }
279 };
280
281 cloudeebus.Service.prototype._addSignal = function(objectPath, ifName, signal, objectJS) {
282         var service = this;
283         var methodExist = false;
284
285         if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName])
286                 if (objectJS.interfaceProxies[ifName][signal]) {
287                         methodExist = true;
288                 } else {
289                         objectJS.interfaceProxies[ifName][signal] = function() {
290                                 service.emitSignal(objectPath, signal, arguments[0]);
291                         };
292                 return;
293         }
294                 
295         if ((objectJS[signal] == undefined || objectJS[signal] == null) && !methodExist) 
296                 objectJS[signal] = function() {
297                         service.emitSignal(objectPath, signal, arguments[0]);
298                 };
299         else
300                 cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
301 };
302
303 cloudeebus.Service.prototype._createWrapper = function(xmlTemplate, objectPath, objectJS) {
304         var self = this;
305         var parser = new DOMParser();
306         var xmlDoc = parser.parseFromString(xmlTemplate, "text/xml");
307         var ifXml = xmlDoc.getElementsByTagName("interface");
308         objectJS.wrapperFunc = [];
309         for (var i=0; i < ifXml.length; i++) {
310                 var ifName = ifXml[i].attributes.getNamedItem("name").value;
311                 var ifChild = ifXml[i].firstChild;
312                 while (ifChild) {
313                         if (ifChild.nodeName == "method") {
314                                 var metName = ifChild.attributes.getNamedItem("name").value;
315                                 self._addMethod(objectPath, ifName, metName, objectJS);
316                         }
317                         if (ifChild.nodeName == "signal") {
318                                 var metName = ifChild.attributes.getNamedItem("name").value;
319                                 self._addSignal(objectPath, ifName, metName, objectJS);
320                         }
321                         ifChild = ifChild.nextSibling;
322                 }
323         }
324 };
325
326 cloudeebus.Service.prototype.addAgent = function(objectPath, xmlTemplate, objectJS, successCB, errorCB) {
327         function ServiceAddAgentSuccessCB(objPath) {
328                 if (successCB) {
329                         try {
330                                 successCB(objPath);
331                         }
332                         catch (e) {
333                                 alert("Exception adding agent " + objectPath + " : " + e);
334                         }
335                 }
336         }
337         
338         try {
339                 this._createWrapper(xmlTemplate, objectPath, objectJS);
340         }
341         catch (e) {
342                 alert("Exception creating agent wrapper " + objectPath + " : " + e);
343                 errorCB(e.desc);
344                 return;
345         }
346         
347         var arglist = [
348             objectPath,
349             xmlTemplate
350             ];
351
352         // call dbusSend with bus type, destination, object, message and arguments
353         this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
354 };
355
356 cloudeebus.Service.prototype.delAgent = function(objectPath, successCB, errorCB) {
357         function ServiceDelAgentSuccessCB(agent) {
358                 if (successCB) {
359                         try {
360                                 successCB(agent);
361                         }
362                         catch (e) {
363                                 alert("Exception deleting agent " + objectPath + " : " + e);
364                         }
365                 }
366         }
367         
368         var arglist = [
369             objectPath
370             ];
371
372         // call dbusSend with bus type, destination, object, message and arguments
373         this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
374 };
375
376 cloudeebus.Service.prototype._registerMethod = function(methodId, methodHandler) {
377         this.wampSession.subscribe(methodId, methodHandler);
378 };
379
380 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
381         var arglist = [
382             methodId,
383             callIndex,
384             success,
385             result
386             ];
387
388         this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
389 };
390
391 cloudeebus.Service.prototype.emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
392         var arglist = [
393             objectPath,
394             signalName,
395             result
396             ];
397
398         this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
399 };
400
401
402 /*****************************************************************************/
403
404 function _processWrappers(wrappers, value) {
405         for (var i=0; i<wrappers.length; i++)
406                 wrappers[i](value);
407 }
408
409
410 function _processWrappersAsync(wrappers, value) {
411         var taskid = -1;
412         function processAsyncOnce() {
413                 _processWrappers(wrappers, value);
414                 clearInterval(taskid);
415         }
416         taskid = setInterval(processAsyncOnce, 200);
417 }
418
419
420
421 /*****************************************************************************/
422
423 cloudeebus.FutureResolver = function(future) {
424         this.future = future;
425         this.resolved = null;
426     return this;
427 };
428
429
430 cloudeebus.FutureResolver.prototype.resolve = function(value, sync) {
431         if (this.resolved)
432                 return;
433         
434         try {
435                 this.accept(value, sync);
436         }
437         catch (e) {
438                 this.reject(e, sync);
439         }
440 };
441
442
443 cloudeebus.FutureResolver.prototype.accept = function(value, sync) {
444         if (this.resolved)
445                 return;
446         
447         var future = this.future;
448         future.state = "accepted";
449         future.result = value;
450         
451         this.resolved = true;
452         if (sync)
453                 _processWrappers(future._acceptWrappers, value);
454         else
455                 _processWrappersAsync(future._acceptWrappers, value);
456 };
457
458
459 cloudeebus.FutureResolver.prototype.reject = function(value, sync) {
460         if (this.resolved)
461                 return;
462         
463         var future = this.future;
464         future.state = "rejected";
465         future.result = value;
466         
467         this.resolved = true;
468         if (sync)
469                 _processWrappers(future._rejectWrappers, value);
470         else
471                 _processWrappersAsync(future._rejectWrappers, value);
472 };
473
474
475
476 /*****************************************************************************/
477
478 cloudeebus.Future = function(init) {
479         this.state = "pending";
480         this.result = null;
481         this._acceptWrappers = [];
482         this._rejectWrappers = [];
483         this.resolver = new cloudeebus.FutureResolver(this);
484         if (init) {
485                 try {
486                         init.apply(this, [this.resolver]);
487                 }
488                 catch (e) {
489                         this.resolver.reject(e, true);
490                 }
491         }
492     return this;
493 };
494
495
496 cloudeebus.Future.prototype.appendWrappers = function(acceptWrapper, rejectWrapper) {
497         this._acceptWrappers.push(acceptWrapper);
498         this._rejectWrappers.push(rejectWrapper);
499         if (this.state == "accepted")
500                 _processWrappersAsync(this._acceptWrappers, this.result);
501         if (this.state == "rejected")
502                 _processWrappersAsync(this._rejectWrappers, this.result);
503 };
504
505
506 cloudeebus.Future.prototype.then = function(acceptCB, rejectCB) {
507         var future = new cloudeebus.Future();
508         var resolver = future.resolver;
509         var acceptWrapper, rejectWrapper;
510         
511         if (acceptCB)
512                 acceptWrapper = function(arg) {
513                         try {
514                                 var value = acceptCB.apply(future, [arg]);
515                                 resolver.accept(value, true);
516                         }
517                         catch (e) {
518                                 resolver.reject(e, true);
519                         }
520                 };
521         else
522                 acceptWrapper = function(arg) {
523                         resolver.accept(arg, true);
524                 };
525         
526         if (rejectCB)
527                 rejectWrapper = function(arg) {
528                         try {
529                                 var value = rejectCB.apply(future, [arg]);
530                                 resolver.reject(value, true);
531                         }
532                         catch (e) {
533                                 resolver.reject(e, true);
534                         }
535                 };
536         else
537                 rejectWrapper = function(arg) {
538                         resolver.reject(arg, true);
539                 };
540         
541         this.appendWrappers(acceptWrapper,rejectWrapper);
542         return future;
543 };
544
545
546
547 /*****************************************************************************/
548
549 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
550         this.wampSession = session; 
551         this.busConnection = busConnection; 
552         this.busName = busName; 
553         this.objectPath = objectPath; 
554         this.interfaceProxies = {};
555         return this;
556 };
557
558
559 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
560         return this.interfaceProxies[ifName];
561 };
562
563
564 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
565         
566         var self = this; 
567
568         function getAllPropertiesSuccessCB(props) {
569                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
570                 for (var prop in props)
571                         ifProxy[prop] = self[prop] = props[prop];
572                 getAllPropertiesNextInterfaceCB();
573         }
574         
575         function getAllPropertiesNextInterfaceCB() {
576                 self.propInterfaces.pop();
577                 if (self.propInterfaces.length > 0) 
578                         self.callMethod("org.freedesktop.DBus.Properties", 
579                                 "GetAll", 
580                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
581                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
582                 else {
583                         self.propInterfaces = null;
584                         if (successCB)
585                                 successCB(self);
586                 }
587         }
588         
589         function introspectSuccessCB(str) {
590                 var parser = new DOMParser();
591                 var xmlDoc = parser.parseFromString(str, "text/xml");
592                 var interfaces = xmlDoc.getElementsByTagName("interface");
593                 self.propInterfaces = [];
594                 var supportDBusProperties = false;
595                 for (var i=0; i < interfaces.length; i++) {
596                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
597                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
598                         if (ifName == "org.freedesktop.DBus.Properties")
599                                 supportDBusProperties = true;
600                         var hasProperties = false;
601                         var ifChild = interfaces[i].firstChild;
602                         while (ifChild) {
603                                 if (ifChild.nodeName == "method") {
604                                         var nArgs = 0;
605                                         var signature = "";
606                                         var metChild = ifChild.firstChild;
607                                         while (metChild) {
608                                                 if (metChild.nodeName == "arg" &&
609                                                         metChild.attributes.getNamedItem("direction").value == "in") {
610                                                                 signature += metChild.attributes.getNamedItem("type").value;
611                                                                 nArgs++;
612                                                 }
613                                                 metChild = metChild.nextSibling;
614                                         }
615                                         var metName = ifChild.attributes.getNamedItem("name").value;
616                                         if (!self[metName])
617                                                 self._addMethod(ifName, metName, nArgs, signature);
618                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
619                                 }
620                                 else if (ifChild.nodeName == "property") {
621                                         if (!hasProperties)
622                                                 self.propInterfaces.push(ifName);
623                                         hasProperties = true;
624                                 }
625                                 ifChild = ifChild.nextSibling;
626                         }
627                 }
628                 if (supportDBusProperties && self.propInterfaces.length > 0) {
629                         self.callMethod("org.freedesktop.DBus.Properties", 
630                                 "GetAll", 
631                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
632                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
633                 }
634                 else {
635                         self.propInterfaces = null;
636                         if (successCB)
637                                 successCB(self);
638                 }
639         }
640
641         // call Introspect on self
642         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
643 };
644
645
646 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
647
648         var self = this;
649         
650         self[method] = function() {
651                 var args = [];
652                 for (var i=0; i < nArgs; i++ )
653                         args.push(arguments[i]);
654                 return self.callMethod(ifName, method, args, signature);
655         };      
656 };
657
658
659 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
660         
661         var self = this;
662         
663         var future = new cloudeebus.Future(function (resolver) {
664                 function callMethodSuccessCB(str) {
665                         try { // calling dbus hook object function for un-translated types
666                                 var result = eval(str);
667                                 resolver.accept(result[0]);
668                         }
669                         catch (e) {
670                                 cloudeebus.log("Method callback exception: " + e);
671                                 resolver.reject(e);
672                         }
673                 }
674
675                 function callMethodErrorCB(error) {
676                         cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
677                         resolver.reject(error.desc);
678                 }
679
680                 var arglist = [
681                         self.busConnection.name,
682                         self.busName,
683                         self.objectPath,
684                         ifName,
685                         method,
686                         JSON.stringify(args)
687                 ];
688
689                 // call dbusSend with bus type, destination, object, message and arguments
690                 self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
691         });
692         
693         return future;
694 };
695
696
697 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
698         
699         var self = this; 
700
701         function signalHandler(id, data) {
702                 if (successCB) {
703                         try { // calling dbus hook object function for un-translated types
704                                 successCB.apply(self, eval(data));
705                         }
706                         catch (e) {
707                                 cloudeebus.log("Signal handler exception: " + e);
708                                 if (errorCB)
709                                         errorCB(e);
710                         }
711                 }
712         }
713         
714         function connectToSignalSuccessCB(str) {
715                 try {
716                         self.wampSession.subscribe(str, signalHandler);
717                 }
718                 catch (e) {
719                         cloudeebus.log("Subscribe error: " + e);
720                 }
721         }
722
723         function connectToSignalErrorCB(error) {
724                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
725                 if (errorCB)
726                         errorCB(error.desc);
727         }
728
729         var arglist = [
730                 self.busConnection.name,
731                 self.busName,
732                 self.objectPath,
733                 ifName,
734                 signal
735         ];
736
737         // call dbusSend with bus type, destination, object, message and arguments
738         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
739 };
740
741
742 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
743         try {
744                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
745         }
746         catch (e) {
747                 cloudeebus.log("Unsubscribe error: " + e);
748         }
749 };