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