3293e83c79a5ca2a3e52ef24d82c1300ce7deab6
[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         return this;
140 };
141
142
143 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
144         var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
145         if (introspectCB)
146                 proxy._introspect(introspectCB, errorCB);
147         return proxy;
148 };
149
150
151
152 /*****************************************************************************/
153
154 function _processWrappers(wrappers, value) {
155         for (var i=0; i<wrappers.length; i++)
156                 wrappers[i](value);
157 }
158
159
160 function _processWrappersAsync(wrappers, value) {
161         var taskid = -1;
162         function processAsyncOnce() {
163                 _processWrappers(wrappers, value);
164                 clearInterval(taskid);
165         }
166         taskid = setInterval(processAsyncOnce, 200);
167 }
168
169
170
171 /*****************************************************************************/
172
173 cloudeebus.FutureResolver = function(future) {
174         this.future = future;
175         this.resolved = null;
176     return this;
177 };
178
179
180 cloudeebus.FutureResolver.prototype.resolve = function(value, sync) {
181         if (this.resolved)
182                 return;
183         
184         var then = (value && value.then && value.then.apply) ? value.then : null;
185         if (then) {
186                 var self = this;                
187                 var acceptCallback = function(arg) {
188                         self.accept(arg, true);
189                 };      
190                 var rejectCallback = function(arg) {
191                         self.reject(arg, true);
192                 };
193                 try {
194                         then.apply(value, [acceptCallback, rejectCallback]);
195                 }
196                 catch (e) {
197                         this.reject(e, true);
198                 }
199         }
200         
201         this.accept(value, sync);
202 };
203
204
205 cloudeebus.FutureResolver.prototype.accept = function(value, sync) {
206         if (this.resolved)
207                 return;
208         
209         var future = this.future;
210         future.state = "accepted";
211         future.result = value;
212         
213         this.resolved = true;
214         if (sync)
215                 _processWrappers(future._acceptWrappers, value);
216         else
217                 _processWrappersAsync(future._acceptWrappers, value);
218 };
219
220
221 cloudeebus.FutureResolver.prototype.reject = function(value, sync) {
222         if (this.resolved)
223                 return;
224         
225         var future = this.future;
226         future.state = "rejected";
227         future.result = value;
228         
229         this.resolved = true;
230         if (sync)
231                 _processWrappers(future._rejectWrappers, value);
232         else
233                 _processWrappersAsync(future._rejectWrappers, value);
234 };
235
236
237
238 /*****************************************************************************/
239
240 cloudeebus.Future = function(init) {
241         this.state = "pending";
242         this.result = null;
243         this._acceptWrappers = [];
244         this._rejectWrappers = [];
245         this.resolver = new cloudeebus.FutureResolver(this);
246         if (init) {
247                 try {
248                         init.apply(this, [this.resolver]);
249                 }
250                 catch (e) {
251                         this.resolver.reject(e, true);
252                 }
253         }
254     return this;
255 };
256
257
258 cloudeebus.Future.prototype.appendWrappers = function(acceptWrapper, rejectWrapper) {
259         this._acceptWrappers.push(acceptWrapper);
260         this._rejectWrappers.push(rejectWrapper);
261         if (this.state == "accepted")
262                 _processWrappersAsync(this._acceptWrappers, this.result);
263         if (this.state == "rejected")
264                 _processWrappersAsync(this._rejectWrappers, this.result);
265 };
266
267
268 cloudeebus.Future.prototype.then = function(acceptCB, rejectCB) {
269         var future = new cloudeebus.Future();
270         var resolver = future.resolver;
271         var acceptWrapper, rejectWrapper;
272         
273         if (acceptCB)
274                 acceptWrapper = function(arg) {
275                         try {
276                                 var value = acceptCB.apply(future, [arg]);
277                                 resolver.resolve(value, true);
278                         }
279                         catch (e) {
280                                 resolver.reject(e, true);
281                         }
282                 };
283         else
284                 acceptWrapper = function(arg) {
285                         resolver.accept(arg, true);
286                 };
287         
288         if (rejectCB)
289                 rejectWrapper = function(arg) {
290                         try {
291                                 var value = rejectCB.apply(future, [arg]);
292                                 resolver.resolve(value, true);
293                         }
294                         catch (e) {
295                                 resolver.reject(e, true);
296                         }
297                 };
298         else
299                 rejectWrapper = function(arg) {
300                         resolver.reject(arg, true);
301                 };
302         
303         this.appendWrappers(acceptWrapper,rejectWrapper);
304         return future;
305 };
306
307
308
309 /*****************************************************************************/
310
311 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
312         this.wampSession = session; 
313         this.busConnection = busConnection; 
314         this.busName = busName; 
315         this.objectPath = objectPath; 
316         this.interfaceProxies = {};
317         return this;
318 };
319
320
321 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
322         return this.interfaceProxies[ifName];
323 };
324
325
326 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
327         
328         var self = this; 
329
330         function getAllPropertiesSuccessCB(props) {
331                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
332                 for (var prop in props)
333                         ifProxy[prop] = self[prop] = props[prop];
334                 getAllPropertiesNextInterfaceCB();
335         }
336         
337         function getAllPropertiesNextInterfaceCB() {
338                 self.propInterfaces.pop();
339                 if (self.propInterfaces.length > 0) 
340                         self.callMethod("org.freedesktop.DBus.Properties", 
341                                 "GetAll", 
342                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
343                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
344                 else {
345                         self.propInterfaces = null;
346                         if (successCB)
347                                 successCB(self);
348                 }
349         }
350         
351         function introspectSuccessCB(str) {
352                 var parser = new DOMParser();
353                 var xmlDoc = parser.parseFromString(str, "text/xml");
354                 var interfaces = xmlDoc.getElementsByTagName("interface");
355                 self.propInterfaces = [];
356                 var supportDBusProperties = false;
357                 for (var i=0; i < interfaces.length; i++) {
358                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
359                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
360                         if (ifName == "org.freedesktop.DBus.Properties")
361                                 supportDBusProperties = true;
362                         var hasProperties = false;
363                         var ifChild = interfaces[i].firstChild;
364                         while (ifChild) {
365                                 if (ifChild.nodeName == "method") {
366                                         var nArgs = 0;
367                                         var signature = "";
368                                         var metChild = ifChild.firstChild;
369                                         while (metChild) {
370                                                 if (metChild.nodeName == "arg" &&
371                                                         metChild.attributes.getNamedItem("direction").value == "in") {
372                                                                 signature += metChild.attributes.getNamedItem("type").value;
373                                                                 nArgs++;
374                                                 }
375                                                 metChild = metChild.nextSibling;
376                                         }
377                                         var metName = ifChild.attributes.getNamedItem("name").value;
378                                         if (!self[metName])
379                                                 self._addMethod(ifName, metName, nArgs, signature);
380                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
381                                 }
382                                 else if (ifChild.nodeName == "property") {
383                                         if (!hasProperties)
384                                                 self.propInterfaces.push(ifName);
385                                         hasProperties = true;
386                                 }
387                                 ifChild = ifChild.nextSibling;
388                         }
389                 }
390                 if (supportDBusProperties && self.propInterfaces.length > 0) {
391                         self.callMethod("org.freedesktop.DBus.Properties", 
392                                 "GetAll", 
393                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
394                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
395                 }
396                 else {
397                         self.propInterfaces = null;
398                         if (successCB)
399                                 successCB(self);
400                 }
401         }
402
403         // call Introspect on self
404         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
405 };
406
407
408 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
409
410         var self = this;
411         
412         self[method] = function() {
413                 var args = [];
414                 for (var i=0; i < nArgs; i++ )
415                         args.push(arguments[i]);
416                 return self.callMethod(ifName, method, args, signature);
417         };      
418 };
419
420
421 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
422         
423         var self = this;
424         
425         var future = new cloudeebus.Future(function (resolver) {
426                 function callMethodSuccessCB(str) {
427                         try { // calling dbus hook object function for un-translated types
428                                 var result = eval(str);
429                                 resolver.accept(result[0]);
430                         }
431                         catch (e) {
432                                 cloudeebus.log("Method callback exception: " + e);
433                                 resolver.reject(e);
434                         }
435                 }
436
437                 function callMethodErrorCB(error) {
438                         cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
439                         resolver.reject(error.desc);
440                 }
441
442                 var arglist = [
443                         self.busConnection.name,
444                         self.busName,
445                         self.objectPath,
446                         ifName,
447                         method,
448                         JSON.stringify(args)
449                 ];
450
451                 // call dbusSend with bus type, destination, object, message and arguments
452                 self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
453         });
454         
455         return future;
456 };
457
458
459 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
460         
461         var self = this; 
462
463         function signalHandler(id, data) {
464                 if (successCB) {
465                         try { // calling dbus hook object function for un-translated types
466                                 successCB.apply(self, eval(data));
467                         }
468                         catch (e) {
469                                 cloudeebus.log("Signal handler exception: " + e);
470                                 if (errorCB)
471                                         errorCB(e);
472                         }
473                 }
474         }
475         
476         function connectToSignalSuccessCB(str) {
477                 try {
478                         self.wampSession.subscribe(str, signalHandler);
479                 }
480                 catch (e) {
481                         cloudeebus.log("Subscribe error: " + e);
482                 }
483         }
484
485         function connectToSignalErrorCB(error) {
486                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
487                 if (errorCB)
488                         errorCB(error.desc);
489         }
490
491         var arglist = [
492                 self.busConnection.name,
493                 self.busName,
494                 self.objectPath,
495                 ifName,
496                 signal
497         ];
498
499         // call dbusSend with bus type, destination, object, message and arguments
500         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
501 };
502
503
504 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
505         try {
506                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
507         }
508         catch (e) {
509                 cloudeebus.log("Unsubscribe error: " + e);
510         }
511 };