]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/javascript/opensrf.js
LP#1268619: websocket JS additions
[OpenSRF.git] / src / javascript / opensrf.js
1 /* -----------------------------------------------------------------------
2  * Copyright (C) 2008  Georgia Public Library Service
3  * Bill Erickson <erickson@esilibrary.com>
4  *  
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * ----------------------------------------------------------------------- */
15
16 /* session states */
17 var OSRF_APP_SESSION_CONNECTED = 0;
18 var OSRF_APP_SESSION_CONNECTING = 1;
19 var OSRF_APP_SESSION_DISCONNECTED = 2;
20
21 /* types of transport layers */
22 var OSRF_TRANSPORT_TYPE_XHR = 1;
23 var OSRF_TRANSPORT_TYPE_XMPP = 2;
24 var OSRF_TRANSPORT_TYPE_WS = 3;
25
26 /* message types */
27 var OSRF_MESSAGE_TYPE_REQUEST = 'REQUEST';
28 var OSRF_MESSAGE_TYPE_STATUS = 'STATUS';
29 var OSRF_MESSAGE_TYPE_RESULT = 'RESULT';
30 var OSRF_MESSAGE_TYPE_CONNECT = 'CONNECT';
31 var OSRF_MESSAGE_TYPE_DISCONNECT = 'DISCONNECT';
32
33 /* message statuses */
34 var OSRF_STATUS_CONTINUE = 100;
35 var OSRF_STATUS_OK = 200;
36 var OSRF_STATUS_ACCEPTED = 202;
37 var OSRF_STATUS_COMPLETE = 205;
38 var OSRF_STATUS_REDIRECTED = 307;
39 var OSRF_STATUS_BADREQUEST = 400;
40 var OSRF_STATUS_UNAUTHORIZED = 401;
41 var OSRF_STATUS_FORBIDDEN = 403;
42 var OSRF_STATUS_NOTFOUND = 404;
43 var OSRF_STATUS_NOTALLOWED = 405;
44 var OSRF_STATUS_TIMEOUT = 408;
45 var OSRF_STATUS_EXPFAILED = 417;
46 var OSRF_STATUS_INTERNALSERVERERROR = 500;
47 var OSRF_STATUS_NOTIMPLEMENTED = 501;
48 var OSRF_STATUS_VERSIONNOTSUPPORTED = 505;
49
50 /* The following classes map directly to network-serializable opensrf objects */
51
52 function osrfMessage(hash) {
53     this.hash = hash;
54     if(!this.hash.locale)
55         this.hash.locale = OpenSRF.locale || 'en-US';
56     this._encodehash = true;
57 }
58 osrfMessage.prototype.threadTrace = function(d) { 
59     if(arguments.length == 1) 
60         this.hash.threadTrace = d; 
61     return this.hash.threadTrace; 
62 };
63 osrfMessage.prototype.type = function(d) { 
64     if(arguments.length == 1) 
65         this.hash.type = d; 
66     return this.hash.type; 
67 };
68 osrfMessage.prototype.payload = function(d) { 
69     if(arguments.length == 1) 
70         this.hash.payload = d; 
71     return this.hash.payload; 
72 };
73 osrfMessage.prototype.locale = function(d) { 
74     if(arguments.length == 1) 
75         this.hash.locale = d; 
76     return this.hash.locale; 
77 };
78 osrfMessage.prototype.serialize = function() {
79     return {
80         "__c":"osrfMessage",
81         "__p": {
82             'threadTrace' : this.hash.threadTrace,
83             'type' : this.hash.type,
84             'payload' : (this.hash.payload) ? this.hash.payload.serialize() : 'null',
85             'locale' : this.hash.locale
86         }
87     };
88 };
89
90 function osrfMethod(hash) {
91     this.hash = hash;
92     this._encodehash = true;
93 }
94 osrfMethod.prototype.method = function(d) {
95     if(arguments.length == 1) 
96         this.hash.method = d; 
97     return this.hash.method; 
98 };
99 osrfMethod.prototype.params = function(d) {
100     if(arguments.length == 1) 
101         this.hash.params = d; 
102     return this.hash.params; 
103 };
104 osrfMethod.prototype.serialize = function() {
105     return {
106         "__c":"osrfMethod",
107         "__p": {
108             'method' : this.hash.method,
109             'params' : this.hash.params
110         }
111     };
112 };
113
114 function osrfMethodException(hash) {
115     this.hash = hash;
116     this._encodehash = true;
117 }
118 osrfMethodException.prototype.status = function(d) {
119     if(arguments.length == 1) 
120         this.hash.status = d; 
121     return this.hash.status; 
122 };
123 osrfMethodException.prototype.statusCode = function(d) {
124     if(arguments.length == 1) 
125         this.hash.statusCode = d; 
126     return this.hash.statusCode; 
127 };
128 function osrfConnectStatus(hash) { 
129     this.hash = hash;
130     this._encodehash = true;
131 }
132 osrfConnectStatus.prototype.status = function(d) {
133     if(arguments.length == 1) 
134         this.hash.status = d; 
135     return this.hash.status; 
136 };
137 osrfConnectStatus.prototype.statusCode = function(d) {
138     if(arguments.length == 1) 
139         this.hash.statusCode = d; 
140     return this.hash.statusCode; 
141 };
142 function osrfResult(hash) {
143     this.hash = hash;
144     this._encodehash = true;
145 }
146 osrfResult.prototype.status = function(d) {
147     if(arguments.length == 1) 
148         this.hash.status = d; 
149     return this.hash.status; 
150 };
151 osrfResult.prototype.statusCode = function(d) {
152     if(arguments.length == 1) 
153         this.hash.statusCode = d; 
154     return this.hash.statusCode; 
155 };
156 osrfResult.prototype.content = function(d) {
157     if(arguments.length == 1) 
158         this.hash.content = d; 
159     return this.hash.content; 
160 };
161 function osrfServerError(hash) { 
162     this.hash = hash;
163     this._encodehash = true;
164 }
165 osrfServerError.prototype.status = function(d) {
166     if(arguments.length == 1) 
167         this.hash.status = d; 
168     return this.hash.status; 
169 };
170 osrfServerError.prototype.statusCode = function(d) {
171     if(arguments.length == 1) 
172         this.hash.statusCode = d; 
173     return this.hash.statusCode; 
174 };
175 function osrfContinueStatus(hash) { 
176     this.hash = hash;
177     this._encodehash = true;
178 }
179 osrfContinueStatus.prototype.status = function(d) {
180     if(arguments.length == 1) 
181         this.hash.status = d; 
182     return this.hash.status; 
183 };
184 osrfContinueStatus.prototype.statusCode = function(d) {
185     if(arguments.length == 1) 
186         this.hash.statusCode = d; 
187     return this.hash.statusCode; 
188 };
189
190 OpenSRF = {};
191 OpenSRF.locale = null;
192
193 /* makes cls a subclass of pcls */
194 OpenSRF.set_subclass = function(cls, pcls) {
195     var str = cls+'.prototype = new '+pcls+'();';
196     str += cls+'.prototype.constructor = '+cls+';';
197     str += cls+'.baseClass = '+pcls+'.prototype.constructor;';
198     str += cls+'.prototype["super"] = '+pcls+'.prototype;';
199     eval(str);
200 };
201
202
203 /* general session superclass */
204 OpenSRF.Session = function() {
205     this.remote_id = null;
206     this.state = OSRF_APP_SESSION_DISCONNECTED;
207 };
208
209 //OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_WS;
210 OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_XHR;
211
212 OpenSRF.Session.cache = {};
213 OpenSRF.Session.find_session = function(thread_trace) {
214     return OpenSRF.Session.cache[thread_trace];
215 };
216 OpenSRF.Session.prototype.cleanup = function() {
217     delete OpenSRF.Session.cache[this.thread];
218 };
219
220 OpenSRF.Session.prototype.send = function(osrf_msg, args) {
221     args = (args) ? args : {};
222     switch(OpenSRF.Session.transport) {
223         case OSRF_TRANSPORT_TYPE_WS:
224             return this.send_ws(osrf_msg);
225         case OSRF_TRANSPORT_TYPE_XHR:
226             return this.send_xhr(osrf_msg, args);
227         case OSRF_TRANSPORT_TYPE_XMPP:
228             return this.send_xmpp(osrf_msg, args);
229     }
230 };
231
232 OpenSRF.Session.prototype.send_xhr = function(osrf_msg, args) {
233     args.thread = this.thread;
234     args.rcpt = this.remote_id;
235     args.rcpt_service = this.service;
236     new OpenSRF.XHRequest(osrf_msg, args).send();
237 };
238
239 OpenSRF.Session.prototype.send_ws = function(osrf_msg) {
240     new OpenSRF.WebSocketRequest(
241         this, 
242         function(wsreq) {wsreq.send(osrf_msg)} // onopen
243     );
244 };
245
246 OpenSRF.Session.prototype.send_xmpp = function(osrf_msg, args) {
247     alert('xmpp transport not implemented');
248 };
249
250
251 /* client sessions make requests */
252 OpenSRF.ClientSession = function(service) {
253     this.service = service;
254     this.remote_id = null;
255     this.locale = OpenSRF.locale || 'en-US';
256     this.last_id = 0;
257     this.requests = [];
258     this.onconnect = null;
259     this.thread = Math.random() + '' + new Date().getTime();
260     OpenSRF.Session.cache[this.thread] = this;
261 };
262 OpenSRF.set_subclass('OpenSRF.ClientSession', 'OpenSRF.Session');
263
264
265 OpenSRF.ClientSession.prototype.connect = function(args) {
266     args = (args) ? args : {};
267     this.remote_id = null;
268
269     if (this.state == OSRF_APP_SESSION_CONNECTED) {
270         if (args.onconnect) args.onconnect();
271         return true;
272     }
273
274     if(args.onconnect) {
275         this.onconnect = args.onconnect;
276
277     } else {
278         /* if no handler is provided, make this a synchronous call */
279         this.timeout = (args.timeout) ? args.timeout : 5;
280     }
281
282     message = new osrfMessage({
283         'threadTrace' : this.last_id++, 
284         'type' : OSRF_MESSAGE_TYPE_CONNECT
285     });
286
287     this.send(message, {'timeout' : this.timeout});
288
289     if(this.onconnect || this.state == OSRF_APP_SESSION_CONNECTED)
290         return true;
291
292     return false;
293 };
294
295 OpenSRF.ClientSession.prototype.disconnect = function(args) {
296
297     if (this.state == OSRF_APP_SESSION_CONNECTED) {
298         this.send(
299             new osrfMessage({
300                 'threadTrace' : this.last_id++,
301                 'type' : OSRF_MESSAGE_TYPE_DISCONNECT
302             })
303         );
304     }
305
306     this.remote_id = null;
307     this.state = OSRF_APP_SESSION_DISCONNECTED;
308
309     if (this.websocket) {
310         this.websocket.close();
311         delete this.websocket;
312     }
313 };
314
315
316 OpenSRF.ClientSession.prototype.request = function(args) {
317     
318     if(this.state != OSRF_APP_SESSION_CONNECTED)
319         this.remote_id = null;
320         
321     if(typeof args == 'string') { 
322         params = [];
323         for(var i = 1; i < arguments.length; i++)
324             params.push(arguments[i]);
325
326         args = {
327             method : args, 
328             params : params
329         };
330     } else {
331         if(typeof args == 'undefined')
332             args = {};
333     }
334
335     var req = new OpenSRF.Request(this, this.last_id++, args);
336     this.requests.push(req);
337     return req;
338 };
339
340 OpenSRF.ClientSession.prototype.find_request = function(reqid) {
341     for(var i = 0; i < this.requests.length; i++) {
342         var req = this.requests[i];
343         if(req.reqid == reqid)
344             return req;
345     }
346     return null;
347 };
348
349 OpenSRF.Request = function(session, reqid, args) {
350     this.session = session;
351     this.reqid = reqid;
352
353     /* callbacks */
354     this.onresponse = args.onresponse;
355     this.oncomplete = args.oncomplete;
356     this.onerror = args.onerror;
357     this.onmethoderror = args.onmethoderror;
358     this.ontransporterror = args.ontransporterror;
359
360     this.method = args.method;
361     this.params = args.params;
362     this.timeout = args.timeout;
363     this.response_queue = [];
364     this.complete = false;
365 };
366
367 OpenSRF.Request.prototype.peek_last = function(timeout) {
368     if(this.response_queue.length > 0) {
369         var x = this.response_queue.pop();
370         this.response_queue.push(x);
371         return x;
372     }
373     return null;
374 };
375
376 OpenSRF.Request.prototype.peek = function(timeout) {
377     if(this.response_queue.length > 0)
378         return this.response_queue[0];
379     return null;
380 };
381
382 OpenSRF.Request.prototype.recv = function(timeout) {
383     if(this.response_queue.length > 0)
384         return this.response_queue.shift();
385     return null;
386 };
387
388 OpenSRF.Request.prototype.send = function() {
389     method = new osrfMethod({'method':this.method, 'params':this.params});
390     message = new osrfMessage({
391         'threadTrace' : this.reqid, 
392         'type' : OSRF_MESSAGE_TYPE_REQUEST, 
393         'payload' : method, 
394         'locale' : this.session.locale
395     });
396
397     this.session.send(message, {
398         'timeout' : this.timeout,
399         'onresponse' : this.onresponse,
400         'oncomplete' : this.oncomplete,
401         'onerror' : this.onerror,
402         'onmethoderror' : this.onmethoderror,
403         'ontransporterror' : this.ontransporterror
404     });
405 };
406
407 OpenSRF.NetMessage = function(to, from, thread, body, osrf_msg) {
408     this.to = to;
409     this.from = from;
410     this.thread = thread;
411     this.body = body;
412     this.osrf_msg = osrf_msg;
413 };
414
415 OpenSRF.Stack = function() {
416 };
417
418 // global inbound message queue
419 OpenSRF.Stack.queue = [];
420
421 // XXX testing
422 function log(msg) {
423     try {
424         dump(msg + '\n'); // xulrunner
425     } catch(E) {
426         console.log(msg);
427     }
428 }
429
430 // ses may be passed to us by the network handler
431 OpenSRF.Stack.push = function(net_msg, callbacks) {
432     var ses = OpenSRF.Session.find_session(net_msg.thread); 
433     if (!ses) return;
434     ses.remote_id = net_msg.from;
435
436     // NetMessage's from websocket connections are parsed before they get here
437     osrf_msgs = net_msg.osrf_msg;
438
439     if (!osrf_msgs) {
440
441         try {
442             osrf_msgs = JSON2js(net_msg.body);
443
444             if (OpenSRF.Session.transport == OSRF_TRANSPORT_TYPE_WS) {
445                 // WebSocketRequests wrap the content
446                 osrf_msgs = osrf_msgs.osrf_msg;
447             }
448
449         } catch(E) {
450             log('Error parsing OpenSRF message body as JSON: ' + net_msg.body + '\n' + E);
451
452             /** UGH
453               * For unknown reasons, the Content-Type header will occasionally
454               * be included in the XHR.responseText for multipart/mixed messages.
455               * When this happens, strip the header and newlines from the message
456               * body and re-parse.
457               */
458             net_msg.body = net_msg.body.replace(/^.*\n\n/, '');
459             log('Cleaning up and retrying...');
460
461             try {
462                 osrf_msgs = JSON2js(net_msg.body);
463             } catch(E2) {
464                 log('Unable to clean up message, giving up: ' + net_msg.body);
465                 return;
466             }
467         }
468     }
469
470     // push the latest responses onto the end of the inbound message queue
471     for(var i = 0; i < osrf_msgs.length; i++)
472         OpenSRF.Stack.queue.push({msg : osrf_msgs[i], ses : ses});
473
474     // continue processing responses, oldest to newest
475     while(OpenSRF.Stack.queue.length) {
476         var data = OpenSRF.Stack.queue.shift();
477         OpenSRF.Stack.handle_message(data.ses, data.msg);
478     }
479 };
480
481 OpenSRF.Stack.handle_message = function(ses, osrf_msg) {
482     
483     var req = ses.find_request(osrf_msg.threadTrace());
484
485     if(osrf_msg.type() == OSRF_MESSAGE_TYPE_STATUS) {
486
487         var payload = osrf_msg.payload();
488         var status = payload.statusCode();
489         var status_text = payload.status();
490
491         if(status == OSRF_STATUS_COMPLETE) {
492             if(req) {
493                 req.complete = true;
494                 if(req.oncomplete && !req.oncomplete_called) {
495                     req.oncomplete_called = true;
496                     return req.oncomplete(req);
497                 }
498             }
499         }
500
501         if(status == OSRF_STATUS_OK) {
502             ses.state = OSRF_APP_SESSION_CONNECTED;
503
504             /* call the connect callback */
505             if(ses.onconnect && !ses.onconnect_called) {
506                 ses.onconnect_called = true;
507                 return ses.onconnect();
508             }
509         }
510
511         if(status == OSRF_STATUS_NOTFOUND || status == OSRF_STATUS_INTERNALSERVERERROR) {
512             if(req && req.onmethoderror) 
513                 return req.onmethoderror(req, status, status_text);
514         }
515     }
516
517     if(osrf_msg.type() == OSRF_MESSAGE_TYPE_RESULT) {
518         if(req) {
519             req.response_queue.push(osrf_msg.payload());
520             if(req.onresponse) {
521                 return req.onresponse(req);
522             }
523         }
524     }
525 };
526
527