cloudeebus.Request implements DOMRequest as defined in
[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 cloudeebus.Request = function(proxy, onsuccess, onerror) {
155         this.proxy = proxy; 
156         this.readyState = "pending";
157         this.error = null;
158         this.result = null;
159         this.onsuccess = onsuccess;
160         this.onerror = onerror;
161     return this;
162 };
163
164 cloudeebus.Request.prototype.then = function(onsuccess, onerror) {
165         this.onsuccess = onsuccess;
166         this.onerror = onerror;
167         return this;
168 };
169
170
171
172 /*****************************************************************************/
173
174 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
175         this.wampSession = session; 
176         this.busConnection = busConnection; 
177         this.busName = busName; 
178         this.objectPath = objectPath; 
179         this.interfaceProxies = {};
180         return this;
181 };
182
183
184 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
185         return this.interfaceProxies[ifName];
186 };
187
188
189 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
190         
191         var self = this; 
192
193         function getAllPropertiesSuccessCB(props) {
194                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
195                 for (var prop in props)
196                         ifProxy[prop] = self[prop] = props[prop];
197                 getAllPropertiesNextInterfaceCB();
198         }
199         
200         function getAllPropertiesNextInterfaceCB() {
201                 self.propInterfaces.pop();
202                 if (self.propInterfaces.length > 0) 
203                         self.callMethod("org.freedesktop.DBus.Properties", 
204                                 "GetAll", 
205                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
206                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
207                 else {
208                         self.propInterfaces = null;
209                         if (successCB)
210                                 successCB(self);
211                 }
212         }
213         
214         function introspectSuccessCB(str) {
215                 var parser = new DOMParser();
216                 var xmlDoc = parser.parseFromString(str, "text/xml");
217                 var interfaces = xmlDoc.getElementsByTagName("interface");
218                 self.propInterfaces = [];
219                 var supportDBusProperties = false;
220                 for (var i=0; i < interfaces.length; i++) {
221                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
222                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
223                         if (ifName == "org.freedesktop.DBus.Properties")
224                                 supportDBusProperties = true;
225                         var hasProperties = false;
226                         var ifChild = interfaces[i].firstChild;
227                         while (ifChild) {
228                                 if (ifChild.nodeName == "method") {
229                                         var nArgs = 0;
230                                         var signature = "";
231                                         var metChild = ifChild.firstChild;
232                                         while (metChild) {
233                                                 if (metChild.nodeName == "arg" &&
234                                                         metChild.attributes.getNamedItem("direction").value == "in") {
235                                                                 signature += metChild.attributes.getNamedItem("type").value;
236                                                                 nArgs++;
237                                                 }
238                                                 metChild = metChild.nextSibling;
239                                         }
240                                         var metName = ifChild.attributes.getNamedItem("name").value;
241                                         if (!self[metName])
242                                                 self._addMethod(ifName, metName, nArgs, signature);
243                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs, signature);
244                                 }
245                                 else if (ifChild.nodeName == "property") {
246                                         if (!hasProperties)
247                                                 self.propInterfaces.push(ifName);
248                                         hasProperties = true;
249                                 }
250                                 ifChild = ifChild.nextSibling;
251                         }
252                 }
253                 if (supportDBusProperties && self.propInterfaces.length > 0) {
254                         self.callMethod("org.freedesktop.DBus.Properties", 
255                                 "GetAll", 
256                                 [self.propInterfaces[self.propInterfaces.length-1]]).then(getAllPropertiesSuccessCB, 
257                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
258                 }
259                 else {
260                         self.propInterfaces = null;
261                         if (successCB)
262                                 successCB(self);
263                 }
264         }
265
266         // call Introspect on self
267         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", []).then(introspectSuccessCB, errorCB);
268 };
269
270
271 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs, signature) {
272
273         var self = this;
274         
275         self[method] = function() {
276                 var args = [];
277                 for (var i=0; i < nArgs; i++ )
278                         args.push(arguments[i]);
279                 return self.callMethod(ifName, method, args, signature);
280         };      
281 };
282
283 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, signature) {
284         
285         var self = this;
286         var request = new cloudeebus.Request(this);
287         
288         function callMethodSuccessCB(str) {
289                 request.readyState = "done";
290                 try { // calling dbus hook object function for un-translated types
291                         request.result = eval(str);
292                         if (request.onsuccess)
293                                 request.onsuccess.apply(request, request.result);
294                 }
295                 catch (e) {
296                         cloudeebus.log("Method callback exception: " + e);
297                         request.error = e;
298                         if (request.onerror)
299                                 request.onerror.apply(request, [request.error]);
300                 }
301         }
302
303         function callMethodErrorCB(error) {
304                 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
305                 request.readyState = "done";
306                 request.error = error.desc;
307                 if (request.onerror)
308                         request.onerror.apply(request, [request.error]);
309         }
310
311         var arglist = [
312                 self.busConnection.name,
313                 self.busName,
314                 self.objectPath,
315                 ifName,
316                 method,
317                 JSON.stringify(args)
318         ];
319
320         // call dbusSend with bus type, destination, object, message and arguments
321         self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
322         return request;
323 };
324
325
326 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
327         
328         var self = this; 
329
330         function signalHandler(id, data) {
331                 if (successCB) {
332                         try { // calling dbus hook object function for un-translated types
333                                 successCB.apply(self, eval(data));
334                         }
335                         catch (e) {
336                                 cloudeebus.log("Signal handler exception: " + e);
337                                 if (errorCB)
338                                         errorCB(e);
339                         }
340                 }
341         }
342         
343         function connectToSignalSuccessCB(str) {
344                 try {
345                         self.wampSession.subscribe(str, signalHandler);
346                 }
347                 catch (e) {
348                         cloudeebus.log("Subscribe error: " + e);
349                 }
350         }
351
352         function connectToSignalErrorCB(error) {
353                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
354                 if (errorCB)
355                         errorCB(error.desc);
356         }
357
358         var arglist = [
359                 self.busConnection.name,
360                 self.busName,
361                 self.objectPath,
362                 ifName,
363                 signal
364         ];
365
366         // call dbusSend with bus type, destination, object, message and arguments
367         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
368 };
369
370
371 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
372         try {
373                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
374         }
375         catch (e) {
376                 cloudeebus.log("Unsubscribe error: " + e);
377         }
378 };