d991d3502648150f7f71c7b808c7e9213a044c57
[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.3.2",
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 { // calling dbus hook object function for un-translated types
199                                 successCB(self);
200                         }
201                         catch (e) {
202                                 alert(arguments.callee.name + "-> Method callback exception: " + 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 { // calling dbus hook object function for un-translated types
220                                 successCB(serviceName);
221                         }
222                         catch (e) {
223                                 alert(arguments.callee.name + "-> Method callback exception: " + 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                         try {
266                                 // affectation of callDict in eval, otherwise dictionary(='{}') interpreted as block of code by eval
267                                 eval("var callDict = " + arguments[1]);
268                                 result = funcToCall.apply(objectJS, callDict.args);
269                                 service._returnMethod(methodId, callDict.callIndex, true, result);
270                         }
271                         catch (e) {
272                                 cloudeebus.log(arguments.callee.name + "-> Method callback exception: " + e);
273                                 service._returnMethod(methodId, callDict.callIndex, false, e.message);
274                         }
275                 };
276                 this._registerMethod(methodId, objectJS.wrapperFunc[method]);
277         }
278 };
279
280 cloudeebus.Service.prototype._addSignal = function(objectPath, ifName, signal, objectJS) {
281         var service = this;
282         var methodExist = false;
283
284         if (objectJS.interfaceProxies && objectJS.interfaceProxies[ifName])
285                 if (objectJS.interfaceProxies[ifName][signal]) {
286                         methodExist = true;
287                 } else {
288                         objectJS.interfaceProxies[ifName][signal] = function() {
289                                 var result = JSON.parse(arguments[0]);
290                                 service.emitSignal(objectPath, signal, result);
291                         };
292                 return;
293         }
294                 
295         if ((objectJS[signal] == undefined || objectJS[signal] == null) && !methodExist) 
296                 objectJS[signal] = function() {
297                         var result = JSON.parse(arguments[0]);
298                         service.emitSignal(objectPath, signal, result);
299                 };
300         else
301                 cloudeebus.log("Can not create new method to emit signal '" + signal + "' in object JS this method already exist!");
302 };
303
304 cloudeebus.Service.prototype._createWrapper = function(xmlTemplate, objectPath, objectJS) {
305         var self = this;
306         var parser = new DOMParser();
307         var xmlDoc = parser.parseFromString(xmlTemplate, "text/xml");
308         var ifXml = xmlDoc.getElementsByTagName("interface");
309         objectJS.wrapperFunc = []
310         for (var i=0; i < ifXml.length; i++) {
311                 var ifName = ifXml[i].attributes.getNamedItem("name").value;
312                 var ifChild = ifXml[i].firstChild;
313                 while (ifChild) {
314                         if (ifChild.nodeName == "method") {
315                                 var metName = ifChild.attributes.getNamedItem("name").value;
316                                 self._addMethod(objectPath, ifName, metName, objectJS);
317                         }
318                         if (ifChild.nodeName == "signal") {
319                                 var metName = ifChild.attributes.getNamedItem("name").value;
320                                 self._addSignal(objectPath, ifName, metName, objectJS);
321                         }
322                         ifChild = ifChild.nextSibling;
323                 }
324         }
325 };
326
327 cloudeebus.Service.prototype.addAgent = function(objectPath, xmlTemplate, objectJS, successCB, errorCB) {
328         function ServiceAddAgentSuccessCB(objPath) {
329                 if (successCB) {
330                         try { // calling dbus hook object function for un-translated types
331                                 successCB(objPath);
332                         }
333                         catch (e) {
334                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
335                         }
336                 }
337         }
338         
339         try { // calling dbus hook object function for un-translated types
340                 this._createWrapper(xmlTemplate, objectPath, objectJS);
341         }
342         catch (e) {
343                 alert(arguments.callee.name + "-> Method callback exception: " + e);
344                 errorCB(e.desc);
345                 return;
346         }
347         
348         var arglist = [
349             objectPath,
350             xmlTemplate
351             ];
352
353         // call dbusSend with bus type, destination, object, message and arguments
354         this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
355 };
356
357 cloudeebus.Service.prototype.delAgent = function(objectPath, successCB, errorCB) {
358         function ServiceDelAgentSuccessCB(agent) {
359                 if (successCB) {
360                         try { // calling dbus hook object function for un-translated types
361                                 successCB(agent);
362                         }
363                         catch (e) {
364                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
365                         }
366                 }
367         }
368         
369         var arglist = [
370             objectPath
371             ];
372
373         // call dbusSend with bus type, destination, object, message and arguments
374         this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
375 };
376
377 cloudeebus.Service.prototype._registerMethod = function(methodId, methodHandler) {
378         this.wampSession.subscribe(methodId, methodHandler);
379 };
380
381 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
382         var arglist = [
383             methodId,
384             callIndex,
385             success,
386             result
387             ];
388
389         this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
390 };
391
392 cloudeebus.Service.prototype.emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
393         var arglist = [
394             objectPath,
395             signalName,
396             result
397             ];
398
399         this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
400 };
401
402
403 /*****************************************************************************/
404
405 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
406         this.wampSession = session; 
407         this.busConnection = busConnection; 
408         this.busName = busName; 
409         this.objectPath = objectPath; 
410         this.interfaceProxies = {};
411         return this;
412 };
413
414
415 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
416         return this.interfaceProxies[ifName];
417 };
418
419
420 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
421         
422         var self = this; 
423
424         function getAllPropertiesSuccessCB(props) {
425                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
426                 for (var prop in props)
427                         ifProxy[prop] = self[prop] = props[prop];
428                 getAllPropertiesNextInterfaceCB();
429         }
430         
431         function getAllPropertiesNextInterfaceCB() {
432                 self.propInterfaces.pop();
433                 if (self.propInterfaces.length > 0) 
434                         self.callMethod("org.freedesktop.DBus.Properties", 
435                                 "GetAll", 
436                                 [self.propInterfaces[self.propInterfaces.length-1]], 
437                                 getAllPropertiesSuccessCB, 
438                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
439                 else {
440                         self.propInterfaces = null;
441                         if (successCB)
442                                 successCB(self);
443                 }
444         }
445         
446         function introspectSuccessCB(str) {
447                 var parser = new DOMParser();
448                 var xmlDoc = parser.parseFromString(str, "text/xml");
449                 var interfaces = xmlDoc.getElementsByTagName("interface");
450                 self.propInterfaces = [];
451                 var supportDBusProperties = false;
452                 for (var i=0; i < interfaces.length; i++) {
453                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
454                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
455                         if (ifName == "org.freedesktop.DBus.Properties")
456                                 supportDBusProperties = true;
457                         var hasProperties = false;
458                         var ifChild = interfaces[i].firstChild;
459                         while (ifChild) {
460                                 if (ifChild.nodeName == "method") {
461                                         var nArgs = 0;
462                                         var metChild = ifChild.firstChild;
463                                         while (metChild) {
464                                                 if (metChild.nodeName == "arg" &&
465                                                         metChild.attributes.getNamedItem("direction").value == "in")
466                                                                 nArgs++;
467                                                 metChild = metChild.nextSibling;
468                                         }
469                                         var metName = ifChild.attributes.getNamedItem("name").value;
470                                         if (!self[metName])
471                                                 self._addMethod(ifName, metName, nArgs);
472                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs);
473                                 }
474                                 else if (ifChild.nodeName == "property") {
475                                         if (!hasProperties)
476                                                 self.propInterfaces.push(ifName);
477                                         hasProperties = true;
478                                 }
479                                 ifChild = ifChild.nextSibling;
480                         }
481                 }
482                 if (supportDBusProperties && self.propInterfaces.length > 0) {
483                         self.callMethod("org.freedesktop.DBus.Properties", 
484                                 "GetAll", 
485                                 [self.propInterfaces[self.propInterfaces.length-1]], 
486                                 getAllPropertiesSuccessCB, 
487                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
488                 }
489                 else {
490                         self.propInterfaces = null;
491                         if (successCB)
492                                 successCB(self);
493                 }
494         }
495
496         // call Introspect on self
497         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
498 };
499
500
501 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {
502
503         var self = this;
504         
505         self[method] = function() {
506                 if (arguments.length < nArgs || arguments.length > nArgs + 2)
507                         throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
508                 var args = [];
509                 var successCB = null;
510                 var errorCB = null;
511                 for (var i=0; i < nArgs; i++ )
512                         args.push(arguments[i]);
513                 if (arguments.length > nArgs)
514                         successCB = arguments[nArgs];
515                 if (arguments.length > nArgs + 1)
516                         errorCB = arguments[nArgs + 1];
517                 self.callMethod(ifName, method, args, successCB, errorCB);
518         };
519         
520 };
521
522
523 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {
524         
525         var self = this; 
526
527         function callMethodSuccessCB(str) {
528                 if (successCB) {
529                         try { // calling dbus hook object function for un-translated types
530                                 successCB.apply(self, eval(str));
531                         }
532                         catch (e) {
533                                 cloudeebus.log("Method callback exception: " + e);
534                                 if (errorCB)
535                                         errorCB(e);
536                         }
537                 }
538         }
539
540         function callMethodErrorCB(error) {
541                 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
542                 if (errorCB)
543                         errorCB(error.desc);
544         }
545
546         var arglist = [
547                 self.busConnection.name,
548                 self.busName,
549                 self.objectPath,
550                 ifName,
551                 method,
552                 JSON.stringify(args)
553         ];
554
555         // call dbusSend with bus type, destination, object, message and arguments
556         self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
557 };
558
559
560 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
561         
562         var self = this; 
563
564         function signalHandler(id, data) {
565                 if (successCB) {
566                         try { // calling dbus hook object function for un-translated types
567                                 successCB.apply(self, eval(data));
568                         }
569                         catch (e) {
570                                 cloudeebus.log("Signal handler exception: " + e);
571                                 if (errorCB)
572                                         errorCB(e);
573                         }
574                 }
575         }
576         
577         function connectToSignalSuccessCB(str) {
578                 try {
579                         self.wampSession.subscribe(str, signalHandler);
580                 }
581                 catch (e) {
582                         cloudeebus.log("Subscribe error: " + e);
583                 }
584         }
585
586         function connectToSignalErrorCB(error) {
587                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
588                 if (errorCB)
589                         errorCB(error.desc);
590         }
591
592         var arglist = [
593                 self.busConnection.name,
594                 self.busName,
595                 self.objectPath,
596                 ifName,
597                 signal
598         ];
599
600         // call dbusSend with bus type, destination, object, message and arguments
601         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
602 };
603
604
605 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
606         try {
607                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
608         }
609         catch (e) {
610                 cloudeebus.log("Unsubscribe error: " + e);
611         }
612 };