1 /* -----------------------------------------------------------------------
2 * Copyright (C) 2008 Georgia Public Library Service
3 * Bill Erickson <erickson@esilibrary.com>
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.
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 * ----------------------------------------------------------------------- */
17 var OSRF_APP_SESSION_CONNECTED = 0;
18 var OSRF_APP_SESSION_CONNECTING = 1;
19 var OSRF_APP_SESSION_DISCONNECTED = 2;
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 var OSRF_TRANSPORT_TYPE_WS_SHARED = 4;
28 var OSRF_MESSAGE_TYPE_REQUEST = 'REQUEST';
29 var OSRF_MESSAGE_TYPE_STATUS = 'STATUS';
30 var OSRF_MESSAGE_TYPE_RESULT = 'RESULT';
31 var OSRF_MESSAGE_TYPE_CONNECT = 'CONNECT';
32 var OSRF_MESSAGE_TYPE_DISCONNECT = 'DISCONNECT';
34 /* message statuses */
35 var OSRF_STATUS_CONTINUE = 100;
36 var OSRF_STATUS_OK = 200;
37 var OSRF_STATUS_ACCEPTED = 202;
38 var OSRF_STATUS_COMPLETE = 205;
39 var OSRF_STATUS_REDIRECTED = 307;
40 var OSRF_STATUS_BADREQUEST = 400;
41 var OSRF_STATUS_UNAUTHORIZED = 401;
42 var OSRF_STATUS_FORBIDDEN = 403;
43 var OSRF_STATUS_NOTFOUND = 404;
44 var OSRF_STATUS_NOTALLOWED = 405;
45 var OSRF_STATUS_TIMEOUT = 408;
46 var OSRF_STATUS_EXPFAILED = 417;
47 var OSRF_STATUS_INTERNALSERVERERROR = 500;
48 var OSRF_STATUS_NOTIMPLEMENTED = 501;
49 var OSRF_STATUS_VERSIONNOTSUPPORTED = 505;
51 // TODO: get path from ./configure prefix
52 var SHARED_WORKER_LIB = '/js/dojo/opensrf/opensrf_ws_shared.js';
54 /* The following classes map directly to network-serializable opensrf objects */
56 function osrfMessage(hash) {
59 this.hash.locale = OpenSRF.locale || 'en-US';
60 this._encodehash = true;
62 osrfMessage.prototype.threadTrace = function(d) {
63 if(arguments.length == 1)
64 this.hash.threadTrace = d;
65 return this.hash.threadTrace;
67 osrfMessage.prototype.type = function(d) {
68 if(arguments.length == 1)
70 return this.hash.type;
72 osrfMessage.prototype.payload = function(d) {
73 if(arguments.length == 1)
74 this.hash.payload = d;
75 return this.hash.payload;
77 osrfMessage.prototype.locale = function(d) {
78 if(arguments.length == 1)
80 return this.hash.locale;
82 osrfMessage.prototype.api_level = function(d) {
83 if(arguments.length == 1)
84 this.hash.api_level = d;
85 return this.hash.api_level;
87 osrfMessage.prototype.serialize = function() {
91 'threadTrace' : this.hash.threadTrace,
92 'type' : this.hash.type,
93 'payload' : (this.hash.payload) ? this.hash.payload.serialize() : 'null',
94 'locale' : this.hash.locale,
95 'api_level' : this.hash.api_level
100 function osrfMethod(hash) {
102 this._encodehash = true;
104 osrfMethod.prototype.method = function(d) {
105 if(arguments.length == 1)
106 this.hash.method = d;
107 return this.hash.method;
109 osrfMethod.prototype.params = function(d) {
110 if(arguments.length == 1)
111 this.hash.params = d;
112 return this.hash.params;
114 osrfMethod.prototype.serialize = function() {
118 'method' : this.hash.method,
119 'params' : this.hash.params
124 function osrfMethodException(hash) {
126 this._encodehash = true;
128 osrfMethodException.prototype.status = function(d) {
129 if(arguments.length == 1)
130 this.hash.status = d;
131 return this.hash.status;
133 osrfMethodException.prototype.statusCode = function(d) {
134 if(arguments.length == 1)
135 this.hash.statusCode = d;
136 return this.hash.statusCode;
138 function osrfConnectStatus(hash) {
140 this._encodehash = true;
142 osrfConnectStatus.prototype.status = function(d) {
143 if(arguments.length == 1)
144 this.hash.status = d;
145 return this.hash.status;
147 osrfConnectStatus.prototype.statusCode = function(d) {
148 if(arguments.length == 1)
149 this.hash.statusCode = d;
150 return this.hash.statusCode;
152 function osrfResult(hash) {
154 this._encodehash = true;
156 osrfResult.prototype.status = function(d) {
157 if(arguments.length == 1)
158 this.hash.status = d;
159 return this.hash.status;
161 osrfResult.prototype.statusCode = function(d) {
162 if(arguments.length == 1)
163 this.hash.statusCode = d;
164 return this.hash.statusCode;
166 osrfResult.prototype.content = function(d) {
167 if(arguments.length == 1)
168 this.hash.content = d;
169 return this.hash.content;
171 function osrfServerError(hash) {
173 this._encodehash = true;
175 osrfServerError.prototype.status = function(d) {
176 if(arguments.length == 1)
177 this.hash.status = d;
178 return this.hash.status;
180 osrfServerError.prototype.statusCode = function(d) {
181 if(arguments.length == 1)
182 this.hash.statusCode = d;
183 return this.hash.statusCode;
185 function osrfContinueStatus(hash) {
187 this._encodehash = true;
189 osrfContinueStatus.prototype.status = function(d) {
190 if(arguments.length == 1)
191 this.hash.status = d;
192 return this.hash.status;
194 osrfContinueStatus.prototype.statusCode = function(d) {
195 if(arguments.length == 1)
196 this.hash.statusCode = d;
197 return this.hash.statusCode;
201 OpenSRF.locale = null;
202 OpenSRF.api_level = 1;
204 /* makes cls a subclass of pcls */
205 OpenSRF.set_subclass = function(cls, pcls) {
206 var str = cls+'.prototype = new '+pcls+'();';
207 str += cls+'.prototype.constructor = '+cls+';';
208 str += cls+'.baseClass = '+pcls+'.prototype.constructor;';
209 str += cls+'.prototype["super"] = '+pcls+'.prototype;';
214 /* general session superclass */
215 OpenSRF.Session = function() {
216 this.remote_id = null;
217 this.state = OSRF_APP_SESSION_DISCONNECTED;
220 OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_XHR;
221 OpenSRF.Session.cache = {};
223 OpenSRF.Session.find_session = function(thread_trace) {
224 return OpenSRF.Session.cache[thread_trace];
226 OpenSRF.Session.prototype.cleanup = function() {
227 delete OpenSRF.Session.cache[this.thread];
230 OpenSRF.Session.prototype.send = function(osrf_msg, args) {
231 args = (args) ? args : {};
232 switch(OpenSRF.Session.transport) {
233 case OSRF_TRANSPORT_TYPE_WS:
234 return this.send_ws(osrf_msg);
235 case OSRF_TRANSPORT_TYPE_WS_SHARED:
236 return this.send_ws_shared(osrf_msg);
237 case OSRF_TRANSPORT_TYPE_XHR:
238 return this.send_xhr(osrf_msg, args);
239 case OSRF_TRANSPORT_TYPE_XMPP:
240 return this.send_xmpp(osrf_msg, args);
244 OpenSRF.Session.prototype.send_xhr = function(osrf_msg, args) {
245 args.thread = this.thread;
246 args.rcpt = this.remote_id;
247 args.rcpt_service = this.service;
248 new OpenSRF.XHRequest(osrf_msg, args).send();
251 OpenSRF.websocketConnected = function() {
252 return OpenSRF.sharedWebsocketConnected || (
253 OpenSRF.websocketConnection &&
254 OpenSRF.websocketConnection.connected()
258 OpenSRF.Session.prototype.send_ws = function(osrf_msg) {
260 if (typeof SharedWorker == 'function'
263 * https://bugzilla.mozilla.org/show_bug.cgi?id=504553#c73
264 * Firefox does not yet support WebSockets in worker threads
266 && !navigator.userAgent.match(/Firefox/)
268 // vanilla websockets requested, but this browser supports
269 // shared workers, so use those instead.
270 return this.send_ws_shared(osrf_msg);
273 // otherwise, use a per-tab connection
275 if (!OpenSRF.websocketConnection) {
276 this.setup_single_ws();
280 service : this.service,
281 thread : this.thread,
282 osrf_msg : [message.serialize()]
285 OpenSRF.websocketConnection.send(json);
288 OpenSRF.Session.prototype.setup_single_ws = function() {
289 OpenSRF.websocketConnection = new OpenSRF.WebSocket();
291 OpenSRF.websocketConnection.onmessage = function(msg) {
293 var msg = JSON2js(msg);
296 "Error parsing JSON in shared WS response: " + msg);
300 new OpenSRF.NetMessage(
301 null, null, msg.thread, null, msg.osrf_msg)
308 OpenSRF.Session.setup_shared_ws = function() {
309 OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_WS_SHARED;
311 OpenSRF.sharedWSWorker = new SharedWorker(SHARED_WORKER_LIB);
313 OpenSRF.sharedWSWorker.port.addEventListener('message', function(e) {
316 if (data.action == 'message') {
317 // pass all inbound message up the opensrf stack
319 OpenSRF.sharedWebsocketConnected = true;
322 msg = JSON2js(data.message);
325 "Error parsing JSON in shared WS response: " + msg);
329 new OpenSRF.NetMessage(
330 null, null, msg.thread, null, msg.osrf_msg)
337 if (data.action == 'event') {
338 if (data.type.match(/onclose|onerror/)) {
339 OpenSRF.sharedWebsocketConnected = false;
340 if (OpenSRF.onWebSocketClosed)
341 OpenSRF.onWebSocketClosed();
342 if (data.type.match(/onerror/))
343 throw new Error(data.message);
348 OpenSRF.sharedWSWorker.port.start();
351 OpenSRF.Session.prototype.send_ws_shared = function(message) {
353 if (!OpenSRF.sharedWSWorker)
354 OpenSRF.Session.setup_shared_ws();
357 service : this.service,
358 thread : this.thread,
359 osrf_msg : [message.serialize()]
362 OpenSRF.sharedWSWorker.port.postMessage({
364 // pass the thread additionally as a stand-alone value so the
365 // worker can more efficiently inspect it.
366 thread : this.thread,
372 OpenSRF.Session.prototype.send_xmpp = function(osrf_msg, args) {
373 alert('xmpp transport not implemented');
377 /* client sessions make requests */
378 OpenSRF.ClientSession = function(service) {
379 this.service = service;
380 this.remote_id = null;
381 this.locale = OpenSRF.locale || 'en-US';
384 this.onconnect = null;
385 this.thread = Math.random() + '' + new Date().getTime();
386 OpenSRF.Session.cache[this.thread] = this;
388 OpenSRF.set_subclass('OpenSRF.ClientSession', 'OpenSRF.Session');
391 OpenSRF.ClientSession.prototype.connect = function(args) {
392 args = (args) ? args : {};
393 this.remote_id = null;
395 if (this.state == OSRF_APP_SESSION_CONNECTED) {
396 if (args.onconnect) args.onconnect();
401 this.onconnect = args.onconnect;
404 /* if no handler is provided, make this a synchronous call */
405 this.timeout = (args.timeout) ? args.timeout : 5;
408 message = new osrfMessage({
409 'threadTrace' : this.last_id++,
410 'type' : OSRF_MESSAGE_TYPE_CONNECT
413 this.send(message, {'timeout' : this.timeout});
415 if(this.onconnect || this.state == OSRF_APP_SESSION_CONNECTED)
421 OpenSRF.ClientSession.prototype.disconnect = function(args) {
423 if (this.state == OSRF_APP_SESSION_CONNECTED) {
426 'threadTrace' : this.last_id++,
427 'type' : OSRF_MESSAGE_TYPE_DISCONNECT
432 this.remote_id = null;
433 this.state = OSRF_APP_SESSION_DISCONNECTED;
437 OpenSRF.ClientSession.prototype.request = function(args) {
439 if(this.state != OSRF_APP_SESSION_CONNECTED)
440 this.remote_id = null;
442 if(typeof args == 'string') {
444 for(var i = 1; i < arguments.length; i++)
445 params.push(arguments[i]);
452 if(typeof args == 'undefined')
456 var req = new OpenSRF.Request(this, this.last_id++, args);
457 this.requests.push(req);
461 OpenSRF.ClientSession.prototype.find_request = function(reqid) {
462 for(var i = 0; i < this.requests.length; i++) {
463 var req = this.requests[i];
464 if(req.reqid == reqid)
470 OpenSRF.Request = function(session, reqid, args) {
471 this.session = session;
475 this.onresponse = args.onresponse;
476 this.oncomplete = args.oncomplete;
477 this.onerror = args.onerror;
478 this.onmethoderror = args.onmethoderror;
479 this.ontransporterror = args.ontransporterror;
481 this.method = args.method;
482 this.params = args.params;
483 this.timeout = args.timeout;
484 this.api_level = args.api_level || OpenSRF.api_level;
485 this.response_queue = [];
486 this.complete = false;
489 OpenSRF.Request.prototype.peek_last = function(timeout) {
490 if(this.response_queue.length > 0) {
491 var x = this.response_queue.pop();
492 this.response_queue.push(x);
498 OpenSRF.Request.prototype.peek = function(timeout) {
499 if(this.response_queue.length > 0)
500 return this.response_queue[0];
504 OpenSRF.Request.prototype.recv = function(timeout) {
505 if(this.response_queue.length > 0)
506 return this.response_queue.shift();
510 OpenSRF.Request.prototype.send = function() {
511 method = new osrfMethod({'method':this.method, 'params':this.params});
512 message = new osrfMessage({
513 'threadTrace' : this.reqid,
514 'type' : OSRF_MESSAGE_TYPE_REQUEST,
516 'locale' : this.session.locale,
517 'api_level' : this.api_level
520 this.session.send(message, {
521 'timeout' : this.timeout,
522 'onresponse' : this.onresponse,
523 'oncomplete' : this.oncomplete,
524 'onerror' : this.onerror,
525 'onmethoderror' : this.onmethoderror,
526 'ontransporterror' : this.ontransporterror
530 OpenSRF.NetMessage = function(to, from, thread, body, osrf_msg) {
533 this.thread = thread;
535 this.osrf_msg = osrf_msg;
538 OpenSRF.Stack = function() {
541 // global inbound message queue
542 OpenSRF.Stack.queue = [];
547 dump(msg + '\n'); // xulrunner
553 // ses may be passed to us by the network handler
554 OpenSRF.Stack.push = function(net_msg, callbacks) {
555 var ses = OpenSRF.Session.find_session(net_msg.thread);
557 ses.remote_id = net_msg.from;
559 // NetMessage's from websocket connections are parsed before they get here
560 osrf_msgs = net_msg.osrf_msg;
565 osrf_msgs = JSON2js(net_msg.body);
567 // TODO: pretty sure we don't need this..
568 if (OpenSRF.Session.transport == OSRF_TRANSPORT_TYPE_WS) {
569 // WebSocketRequests wrap the content
570 osrf_msgs = osrf_msgs.osrf_msg;
574 log('Error parsing OpenSRF message body as JSON: ' + net_msg.body + '\n' + E);
577 * For unknown reasons, the Content-Type header will occasionally
578 * be included in the XHR.responseText for multipart/mixed messages.
579 * When this happens, strip the header and newlines from the message
582 net_msg.body = net_msg.body.replace(/^.*\n\n/, '');
583 log('Cleaning up and retrying...');
586 osrf_msgs = JSON2js(net_msg.body);
588 log('Unable to clean up message, giving up: ' + net_msg.body);
594 // push the latest responses onto the end of the inbound message queue
595 for(var i = 0; i < osrf_msgs.length; i++)
596 OpenSRF.Stack.queue.push({msg : osrf_msgs[i], ses : ses});
598 // continue processing responses, oldest to newest
599 while(OpenSRF.Stack.queue.length) {
600 var data = OpenSRF.Stack.queue.shift();
601 OpenSRF.Stack.handle_message(data.ses, data.msg);
605 OpenSRF.Stack.handle_message = function(ses, osrf_msg) {
607 var req = ses.find_request(osrf_msg.threadTrace());
609 if(osrf_msg.type() == OSRF_MESSAGE_TYPE_STATUS) {
611 var payload = osrf_msg.payload();
612 var status = payload.statusCode();
613 var status_text = payload.status();
615 if(status == OSRF_STATUS_COMPLETE) {
618 if(req.oncomplete && !req.oncomplete_called) {
619 req.oncomplete_called = true;
620 return req.oncomplete(req);
625 if(status == OSRF_STATUS_OK) {
626 ses.state = OSRF_APP_SESSION_CONNECTED;
628 /* call the connect callback */
629 if(ses.onconnect && !ses.onconnect_called) {
630 ses.onconnect_called = true;
631 return ses.onconnect();
635 if(status == OSRF_STATUS_NOTFOUND || status == OSRF_STATUS_INTERNALSERVERERROR) {
636 if(req && req.onmethoderror)
637 return req.onmethoderror(req, status, status_text);
641 if(osrf_msg.type() == OSRF_MESSAGE_TYPE_RESULT) {
643 req.response_queue.push(osrf_msg.payload());
645 return req.onresponse(req);