bump version 0.3.1 with network-based access control
[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.1"};
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         return this;
124 };
125
126
127 cloudeebus.BusConnection.prototype.getObject = function(busName, objectPath, introspectCB, errorCB) {
128         var proxy = new cloudeebus.ProxyObject(this.wampSession, this, busName, objectPath);
129         if (introspectCB)
130                 proxy._introspect(introspectCB, errorCB);
131         return proxy;
132 };
133
134
135
136 /*****************************************************************************/
137
138 cloudeebus.ProxyObject = function(session, busConnection, busName, objectPath) {
139         this.wampSession = session; 
140         this.busConnection = busConnection; 
141         this.busName = busName; 
142         this.objectPath = objectPath; 
143         this.interfaceProxies = {};
144         return this;
145 };
146
147
148 cloudeebus.ProxyObject.prototype.getInterface = function(ifName) {
149         return this.interfaceProxies[ifName];
150 };
151
152
153 cloudeebus.ProxyObject.prototype._introspect = function(successCB, errorCB) {
154         
155         var self = this; 
156
157         function getAllPropertiesSuccessCB(props) {
158                 var ifProxy = self.interfaceProxies[self.propInterfaces[self.propInterfaces.length-1]];
159                 for (var prop in props)
160                         ifProxy[prop] = self[prop] = props[prop];
161                 getAllPropertiesNextInterfaceCB();
162         }
163         
164         function getAllPropertiesNextInterfaceCB() {
165                 self.propInterfaces.pop();
166                 if (self.propInterfaces.length > 0) 
167                         self.callMethod("org.freedesktop.DBus.Properties", 
168                                 "GetAll", 
169                                 [self.propInterfaces[self.propInterfaces.length-1]], 
170                                 getAllPropertiesSuccessCB, 
171                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
172                 else {
173                         self.propInterfaces = null;
174                         if (successCB)
175                                 successCB(self);
176                 }
177         }
178         
179         function introspectSuccessCB(str) {
180                 var parser = new DOMParser();
181                 var xmlDoc = parser.parseFromString(str, "text/xml");
182                 var interfaces = xmlDoc.getElementsByTagName("interface");
183                 self.propInterfaces = [];
184                 var supportDBusProperties = false;
185                 for (var i=0; i < interfaces.length; i++) {
186                         var ifName = interfaces[i].attributes.getNamedItem("name").value;
187                         self.interfaceProxies[ifName] = new cloudeebus.ProxyObject(self.wampSession, self.busConnection, self.busName, self.objectPath);
188                         if (ifName == "org.freedesktop.DBus.Properties")
189                                 supportDBusProperties = true;
190                         var hasProperties = false;
191                         var ifChild = interfaces[i].firstChild;
192                         while (ifChild) {
193                                 if (ifChild.nodeName == "method") {
194                                         var nArgs = 0;
195                                         var metChild = ifChild.firstChild;
196                                         while (metChild) {
197                                                 if (metChild.nodeName == "arg" &&
198                                                         metChild.attributes.getNamedItem("direction").value == "in")
199                                                                 nArgs++;
200                                                 metChild = metChild.nextSibling;
201                                         }
202                                         var metName = ifChild.attributes.getNamedItem("name").value;
203                                         if (!self[metName])
204                                                 self._addMethod(ifName, metName, nArgs);
205                                         self.interfaceProxies[ifName]._addMethod(ifName, metName, nArgs);
206                                 }
207                                 else if (ifChild.nodeName == "property") {
208                                         if (!hasProperties)
209                                                 self.propInterfaces.push(ifName);
210                                         hasProperties = true;
211                                 }
212                                 ifChild = ifChild.nextSibling;
213                         }
214                 }
215                 if (supportDBusProperties && self.propInterfaces.length > 0) {
216                         self.callMethod("org.freedesktop.DBus.Properties", 
217                                 "GetAll", 
218                                 [self.propInterfaces[self.propInterfaces.length-1]], 
219                                 getAllPropertiesSuccessCB, 
220                                 errorCB ? errorCB : getAllPropertiesNextInterfaceCB);
221                 }
222                 else {
223                         self.propInterfaces = null;
224                         if (successCB)
225                                 successCB(self);
226                 }
227         }
228
229         // call Introspect on self
230         self.callMethod("org.freedesktop.DBus.Introspectable", "Introspect", [], introspectSuccessCB, errorCB);
231 };
232
233
234 cloudeebus.ProxyObject.prototype._addMethod = function(ifName, method, nArgs) {
235
236         var self = this;
237         
238         self[method] = function() {
239                 if (arguments.length < nArgs || arguments.length > nArgs + 2)
240                         throw "Error: method " + method + " takes " + nArgs + " parameters, got " + arguments.length + ".";
241                 var args = [];
242                 var successCB = null;
243                 var errorCB = null;
244                 for (var i=0; i < nArgs; i++ )
245                         args.push(arguments[i]);
246                 if (arguments.length > nArgs)
247                         successCB = arguments[nArgs];
248                 if (arguments.length > nArgs + 1)
249                         errorCB = arguments[nArgs + 1];
250                 self.callMethod(ifName, method, args, successCB, errorCB);
251         };
252         
253 };
254
255
256 cloudeebus.ProxyObject.prototype.callMethod = function(ifName, method, args, successCB, errorCB) {
257         
258         var self = this; 
259
260         function callMethodSuccessCB(str) {
261                 if (successCB) {
262                         try { // calling dbus hook object function for un-translated types
263                                 successCB.apply(self, eval(str));
264                         }
265                         catch (e) {
266                                 cloudeebus.log("Method callback exception: " + e);
267                                 if (errorCB)
268                                         errorCB(e);
269                         }
270                 }
271         }
272
273         function callMethodErrorCB(error) {
274                 cloudeebus.log("Error calling method: " + method + " on object: " + self.objectPath + " : " + error.desc);
275                 if (errorCB)
276                         errorCB(error.desc);
277         }
278
279         var arglist = [
280                 self.busConnection.name,
281                 self.busName,
282                 self.objectPath,
283                 ifName,
284                 method,
285                 JSON.stringify(args)
286         ];
287
288         // call dbusSend with bus type, destination, object, message and arguments
289         self.wampSession.call("dbusSend", arglist).then(callMethodSuccessCB, callMethodErrorCB);
290 };
291
292
293 cloudeebus.ProxyObject.prototype.connectToSignal = function(ifName, signal, successCB, errorCB) {
294         
295         var self = this; 
296
297         function signalHandler(id, data) {
298                 if (successCB) {
299                         try { // calling dbus hook object function for un-translated types
300                                 successCB.apply(self, eval(data));
301                         }
302                         catch (e) {
303                                 cloudeebus.log("Signal handler exception: " + e);
304                                 if (errorCB)
305                                         errorCB(e);
306                         }
307                 }
308         }
309         
310         function connectToSignalSuccessCB(str) {
311                 try {
312                         self.wampSession.subscribe(str, signalHandler);
313                 }
314                 catch (e) {
315                         cloudeebus.log("Subscribe error: " + e);
316                 }
317         }
318
319         function connectToSignalErrorCB(error) {
320                 cloudeebus.log("Error connecting to signal: " + signal + " on object: " + self.objectPath + " : " + error.desc);
321                 if (errorCB)
322                         errorCB(error.desc);
323         }
324
325         var arglist = [
326                 self.busConnection.name,
327                 self.busName,
328                 self.objectPath,
329                 ifName,
330                 signal
331         ];
332
333         // call dbusSend with bus type, destination, object, message and arguments
334         self.wampSession.call("dbusRegister", arglist).then(connectToSignalSuccessCB, connectToSignalErrorCB);
335 };
336
337
338 cloudeebus.ProxyObject.prototype.disconnectSignal = function(ifName, signal) {
339         try {
340                 this.wampSession.unsubscribe(this.busConnection.name + "#" + this.busName + "#" + this.objectPath + "#" + ifName + "#" + signal);
341         }
342         catch (e) {
343                 cloudeebus.log("Unsubscribe error: " + e);
344         }
345 };