WIP
[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 = {version: "0.3.0"};
32
33 cloudeebus.reset = function() {
34         cloudeebus.sessionBus = null;
35         cloudeebus.systemBus = null;
36         cloudeebus.wampSession = null;
37         cloudeebus.uri = null;
38 };
39
40
41 cloudeebus.log = function(msg) { 
42 };
43
44
45 cloudeebus.connect = function(uri, manifest, successCB, errorCB) {
46         cloudeebus.reset();
47         cloudeebus.uri = uri;
48         
49         function onCloudeebusVersionCheckCB(version) {
50                 if (cloudeebus.version == version) {
51                         cloudeebus.log("Connected to " + cloudeebus.uri);
52                         if (successCB)
53                                 successCB();
54                 } else {
55                         var errorMsg = "Cloudeebus server version " + version + " and client version " + cloudeebus.version + " mismatch";
56                         cloudeebus.log(errorMsg);
57                         if (errorCB)
58                                 errorCB(errorMsg);
59                 }
60         }
61         
62         function onWAMPSessionAuthErrorCB(error) {
63                 cloudeebus.log("Authentication error: " + error.desc);
64                 if (errorCB)
65                         errorCB(error.desc);
66         }
67         
68         function onWAMPSessionAuthenticatedCB(permissions) {
69                 cloudeebus.sessionBus = new cloudeebus.BusConnection("session", cloudeebus.wampSession);
70                 cloudeebus.systemBus = new cloudeebus.BusConnection("system", cloudeebus.wampSession);
71                 cloudeebus.wampSession.call("getVersion").then(onCloudeebusVersionCheckCB, errorCB);
72         }
73         
74         function onWAMPSessionChallengedCB(challenge) {
75                 var signature = cloudeebus.wampSession.authsign(challenge, manifest.key);
76                 cloudeebus.wampSession.auth(signature).then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
77         }
78         
79         function onWAMPSessionConnectedCB(session) {
80                 cloudeebus.wampSession = session;
81                 if (manifest)
82                         cloudeebus.wampSession.authreq(
83                                         manifest.name, 
84                                         {permissions: JSON.stringify(manifest.permissions)}
85                                 ).then(onWAMPSessionChallengedCB, onWAMPSessionAuthErrorCB);
86                 else
87                         cloudeebus.wampSession.authreq().then(function() {
88                                 cloudeebus.wampSession.auth().then(onWAMPSessionAuthenticatedCB, onWAMPSessionAuthErrorCB);
89                                 }, onWAMPSessionAuthErrorCB);
90         }
91
92         function onWAMPSessionErrorCB(code, reason) {
93                 if (code == ab.CONNECTION_UNSUPPORTED) {
94                         cloudeebus.log("Browser is not supported");
95                 }
96                 else {
97                         cloudeebus.log("Failed to open session, code = " + code + ", reason = " + reason);
98                 }
99                 if (errorCB)
100                         errorCB(reason);
101         }
102
103         return ab.connect(cloudeebus.uri, onWAMPSessionConnectedCB, onWAMPSessionErrorCB);
104 };
105
106
107 cloudeebus.SessionBus = function() {
108         return cloudeebus.sessionBus;
109 };
110
111
112 cloudeebus.SystemBus = function() {
113         return cloudeebus.systemBus;
114 };
115
116
117
118 /*****************************************************************************/
119
120 cloudeebus.BusConnection = function(name, session) {
121         this.name = name;
122         this.wampSession = session;
123         this.service = null;
124         return this;
125 };
126
127
128 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
129         var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
130         if (introspectCB)
131                 proxy._introspect(introspectCB, errorCB);
132         return proxy;
133 };
134
135
136 cloudeebus.BusConnection.prototype.addService = function(serviceName, successCB, errorCB) {
137         var self = this;
138         
139         cloudeebusService = new cloudeebus.Service(this.wampSession, this, serviceName);
140         
141         function busServiceAddedSuccessCB(service) {
142                 self.service = cloudeebusService;
143                 if (successCB)
144                         successCB(cloudeebusService);
145         }
146         
147         cloudeebusService.add(busServiceAddedSuccessCB, errorCB);
148         return cloudeebusService;
149 };
150
151 cloudeebus.BusConnection.prototype.removeService = function(serviceName, successCB, errorCB) {
152         var self = this;
153         
154         function busServiceRemovedSuccessCB(serviceName) {
155                 // Be sure we are removing the service requested...
156                 if (serviceName == self.service.name) {
157                         self.service = null;
158                         if (successCB)
159                                 successCB(serviceName);
160                 }
161         }
162         
163         cloudeebusService.remove(busServiceRemovedSuccessCB, errorCB);
164 };
165
166
167 /*****************************************************************************/
168
169 cloudeebus.Service = function(session, busConnection, name) {
170         this.wampSession = session;
171         this.busConnection = busConnection; 
172         this.name = name;
173         this.isCreated = false;
174         return this;
175 };
176
177 cloudeebus.Service.prototype.add = function(successCB, errorCB) {
178         var self = this;
179         
180         function ServiceAddedSuccessCB(serviceName) {
181                 if (successCB) {
182                         try { // calling dbus hook object function for un-translated types
183                                 successCB(self);
184                         }
185                         catch (e) {
186                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
187                         }
188                 }
189         }
190         
191         var arglist = [
192             this.busConnection,
193             this.name
194             ];
195
196         // call dbusSend with bus type, destination, object, message and arguments
197         this.wampSession.call("serviceAdd", arglist).then(ServiceAddedSuccessCB, errorCB);
198 };
199
200 cloudeebus.Service.prototype.remove = function(successCB, errorCB) {
201         function ServiceRemovedSuccessCB(serviceName) {
202                 if (successCB) {
203                         try { // calling dbus hook object function for un-translated types
204                                 successCB(serviceName);
205                         }
206                         catch (e) {
207                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
208                         }
209                 }
210         }
211         
212         var arglist = [
213             this.name
214             ];
215
216         // call dbusSend with bus type, destination, object, message and arguments
217         this.wampSession.call("serviceRelease", arglist).then(ServiceRemovedSuccessCB, errorCB);
218 };
219
220 cloudeebus.Service.prototype._addMethod = function(objectPath, objectJS, method, nArgs) {
221
222         var self = this;
223         var methodId = self.name + "#" + objectPath + "#" + method;
224         var object = objectJS;
225         
226         objectJS.wrapperFunc[method] = function() {
227                 var result;
228                 if (arguments.length < nArgs || arguments.length > nArgs + 2)
229                         throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
230                 var args = [];
231                 var successCB = null;
232                 var errorCB = null;
233                 var methodId = arguments[0];
234                 var callDict = JSON.parse(arguments[1]);
235                 for (var i=0; i < nArgs; i++ )
236                         args.push(arguments[i]);
237                 if (arguments.length > nArgs)
238                         successCB = arguments[nArgs];
239                 if (arguments.length > nArgs + 1)
240                         errorCB = arguments[nArgs + 1];
241                 
242                 var str_exec = "object.prototype."+method+"()";
243                 try {
244                         result = eval(str_exec);
245                         self._returnMethod(methodId, callDict.callIndex, true, result);         
246                 }
247                 catch (e) {
248                         alert(arguments.callee.name + "-> Method callback exception: " + e);
249                         self._returnMethod(methodId, callDict.callIndex, false, e);             
250                 }
251         };
252         
253         self._registerMethod(methodId, objectJS.wrapperFunc[method]);
254
255         
256 };
257
258 cloudeebus.Service.prototype._createWrapper = function(xmlTemplate, objectPath, objectJS) {
259         var self = this;
260         var parser = new DOMParser();
261         var xmlDoc = parser.parseFromString(xmlTemplate, "text/xml");
262         var interfaces = xmlDoc.getElementsByTagName("interface");
263         objectJS.wrapperFunc = []
264         for (var i=0; i < interfaces.length; i++) {
265 //              var ifName = interfaces[i].attributes.getNamedItem("name").value;
266                 var ifChild = interfaces[i].firstChild;
267                 while (ifChild) {
268                         if (ifChild.nodeName == "method") {
269                                 var nArgs = 0;
270                                 var metChild = ifChild.firstChild;
271                                 while (metChild) {
272                                         if (metChild.nodeName == "arg" &&
273                                                 metChild.attributes.getNamedItem("direction") != null && 
274                                                 metChild.attributes.getNamedItem("direction").value == "in")
275                                                         nArgs++;
276                                         metChild = metChild.nextSibling;
277                                 }
278                                 var metName = ifChild.attributes.getNamedItem("name").value;
279                                 self._addMethod(objectPath, objectJS, metName, nArgs);
280                         }
281                         ifChild = ifChild.nextSibling;
282                 }
283         }
284 };
285
286 cloudeebus.Service.prototype.addAgent = function(objectPath, xmlTemplate, objectJS, successCB, errorCB) {
287         function ServiceAddAgentSuccessCB(objPath) {
288                 if (successCB) {
289                         try { // calling dbus hook object function for un-translated types
290                                 successCB(objPath);
291                         }
292                         catch (e) {
293                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
294                         }
295                 }
296         }
297         
298         try { // calling dbus hook object function for un-translated types
299                 this._createWrapper(xmlTemplate, objectPath, objectJS);
300         }
301         catch (e) {
302                 alert(arguments.callee.name + "-> Method callback exception: " + e);
303                 errorCB(e.desc);
304                 return;
305         }
306         
307         var arglist = [
308             objectPath,
309             xmlTemplate
310             ];
311
312         // call dbusSend with bus type, destination, object, message and arguments
313         this.wampSession.call("serviceAddAgent", arglist).then(ServiceAddAgentSuccessCB, errorCB);
314 };
315
316 cloudeebus.Service.prototype.delAgent = function(objectPath, successCB, errorCB) {
317         function ServiceDelAgentSuccessCB(agent) {
318                 if (successCB) {
319                         try { // calling dbus hook object function for un-translated types
320                                 successCB(agent);
321                         }
322                         catch (e) {
323                                 alert(arguments.callee.name + "-> Method callback exception: " + e);
324                         }
325                 }
326         }
327         
328         var arglist = [
329             objectPath
330             ];
331
332         // call dbusSend with bus type, destination, object, message and arguments
333         this.wampSession.call("serviceDelAgent", arglist).then(ServiceDelAgentSuccessCB, errorCB);
334 };
335
336 cloudeebus.Service.prototype._registerMethod = function(methodId, methodHandler) {
337         this.wampSession.subscribe(methodId, methodHandler);
338 };
339
340 cloudeebus.Service.prototype._returnMethod = function(methodId, callIndex, success, result, successCB, errorCB) {
341         var arglist = [
342             methodId,
343             callIndex,
344             success,
345             result
346             ];
347
348         this.wampSession.call("returnMethod", arglist).then(successCB, errorCB);
349 };
350
351 cloudeebus.Service.prototype.emitSignal = function(objectPath, signalName, result, successCB, errorCB) {
352         var arglist = [
353             objectPath,
354             signalName,
355             result
356             ];
357
358         this.wampSession.call("emitSignal", arglist).then(successCB, errorCB);
359 };
360
361
362 /*****************************************************************************/
363
364 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
365         this.wampSession = session; 
366         this.busConnection = busConnection; 
367         this.busName = busName; 
368         this.objectPath = objectPath; 
369         this.interfaceProxies = {};
370         return this;
371 };
372
373
374 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
375         return this.interfaceProxies[ifName];
376 };
377
378
379 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
380         
381         var self = this; 
382
383         function getAllPropertiesSuccessCB(props) {
384                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
385                 for (var prop in props)
386                         ifProxy[prop] = self[prop] = props[prop];
387                 getAllPropertiesNextInterfaceCB();
388         }
389         
390         function getAllPropertiesNextInterfaceCB() {
391                 self.propInterfaces.pop();
392                 if (self.propInterfaces.length > 0) 
393                         self.callMethod("org.freedesktop.DBus.Properties", 
394                                 "GetAll", 
395                                 [self.propInterfaces[self.propInterfaces.length-1]], 
396                                 getAllPropertiesSuccessCB, 
397                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
398                 else {
399                         self.propInterfaces = null;
400                         if (successCB)
401                                 successCB(self);
402                 }
403         }
404         
405         function introspectSuccessCB(str) {
406                 var parser = new DOMParser();
407                 var xmlDoc = parser.parseFromString(str, "text/xml");
408                 var interfaces = xmlDoc.getElementsByTagName("interface");
409                 self.propInterfaces = [];
410                 var supportDBusProperties = false;
411                 for (var i=0; i < interfaces.length; i++) {
412                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
413                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
414                         if (ifName == "org.freedesktop.DBus.Properties")
415                                 supportDBusProperties = true;
416                         var hasProperties = false;
417                         var ifChild = interfaces[i].firstChild;
418                         while (ifChild) {
419                                 if (ifChild.nodeName == "method") {
420                                         var nArgs = 0;
421                                         var metChild = ifChild.firstChild;
422                                         while (metChild) {
423                                                 if (metChild.nodeName == "arg" &&
424                                                         metChild.attributes.getNamedItem("direction").value == "in")
425                                                                 nArgs++;
426                                                 metChild = metChild.nextSibling;
427                                         }
428                                         var metName = ifChild.attributes.getNamedItem("name").value;
429                                         if (!self[metName])
430                                                 self._addMethod(ifName, metName, nArgs);
431                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs);
432                                 }
433                                 else if (ifChild.nodeName == "property") {
434                                         if (!hasProperties)
435                                                 self.propInterfaces.push(ifName);
436                                         hasProperties = true;
437                                 }
438                                 ifChild = ifChild.nextSibling;
439                         }
440                 }
441                 if (supportDBusProperties && self.propInterfaces.length > 0) {
442                         self.callMethod("org.freedesktop.DBus.Properties", 
443                                 "GetAll", 
444                                 [self.propInterfaces[self.propInterfaces.length-1]], 
445                                 getAllPropertiesSuccessCB, 
446                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
447                 }
448                 else {
449                         self.propInterfaces = null;
450                         if (successCB)
451                                 successCB(self);
452                 }
453         }
454
455         // call Introspect on self
456         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
457 };
458
459
460 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {
461
462         var self = this;
463         
464         self[method] = function() {
465                 if (arguments.length < nArgs || arguments.length > nArgs + 2)
466                         throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
467                 var args = [];
468                 var successCB = null;
469                 var errorCB = null;
470                 for (var i=0; i < nArgs; i++ )
471                         args.push(arguments[i]);
472                 if (arguments.length > nArgs)
473                         successCB = arguments[nArgs];
474                 if (arguments.length > nArgs + 1)
475                         errorCB = arguments[nArgs + 1];
476                 self.callMethod(ifName, method, args, successCB, errorCB);
477         };
478         
479 };
480
481
482 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {
483         
484         var self = this; 
485
486         function callMethodSuccessCB(str) {
487                 if (successCB) {
488                         try { // calling dbus hook object function for un-translated types
489                                 successCB.apply(self, eval(str));
490                         }
491                         catch (e) {
492                                 cloudeebus.log("Method callback exception: " + e);
493                                 if (errorCB)
494                                         errorCB(e);
495                         }
496                 }
497         }
498
499         function callMethodErrorCB(error) {
500                 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
501                 if (errorCB)
502                         errorCB(error.desc);
503         }
504
505         var arglist = [
506                 self.busConnection.name,
507                 self.busName,
508                 self.objectPath,
509                 ifName,
510                 method,
511                 JSON.stringify(args)
512         ];
513
514         // call dbusSend with bus type, destination, object, message and arguments
515         self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
516 };
517
518
519 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
520         
521         var self = this; 
522
523         function signalHandler(id, data) {
524                 if (successCB) {
525                         try { // calling dbus hook object function for un-translated types
526                                 successCB.apply(self, eval(data));
527                         }
528                         catch (e) {
529                                 cloudeebus.log("Signal handler exception: " + e);
530                                 if (errorCB)
531                                         errorCB(e);
532                         }
533                 }
534         }
535         
536         function connectToSignalSuccessCB(str) {
537                 try {
538                         self.wampSession.subscribe(str, signalHandler);
539                 }
540                 catch (e) {
541                         cloudeebus.log("Subscribe error: " + e);
542                 }
543         }
544
545         function connectToSignalErrorCB(error) {
546                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
547                 if (errorCB)
548                         errorCB(error.desc);
549         }
550
551         var arglist = [
552                 self.busConnection.name,
553                 self.busName,
554                 self.objectPath,
555                 ifName,
556                 signal
557         ];
558
559         // call dbusSend with bus type, destination, object, message and arguments
560         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
561 };
562
563
564 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
565         try {
566                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
567         }
568         catch (e) {
569                 cloudeebus.log("Unsubscribe error: " + e);
570         }
571 };