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 /* The following classes map directly to network-serializable opensrf objects */
53 function osrfMessage(hash) {
56 this.hash.locale = OpenSRF.locale || 'en-US';
57 this._encodehash = true;
59 osrfMessage.prototype.threadTrace = function(d) {
60 if(arguments.length == 1)
61 this.hash.threadTrace = d;
62 return this.hash.threadTrace;
64 osrfMessage.prototype.type = function(d) {
65 if(arguments.length == 1)
67 return this.hash.type;
69 osrfMessage.prototype.payload = function(d) {
70 if(arguments.length == 1)
71 this.hash.payload = d;
72 return this.hash.payload;
74 osrfMessage.prototype.locale = function(d) {
75 if(arguments.length == 1)
77 return this.hash.locale;
79 osrfMessage.prototype.serialize = function() {
83 'threadTrace' : this.hash.threadTrace,
84 'type' : this.hash.type,
85 'payload' : (this.hash.payload) ? this.hash.payload.serialize() : 'null',
86 'locale' : this.hash.locale
91 function osrfMethod(hash) {
93 this._encodehash = true;
95 osrfMethod.prototype.method = function(d) {
96 if(arguments.length == 1)
98 return this.hash.method;
100 osrfMethod.prototype.params = function(d) {
101 if(arguments.length == 1)
102 this.hash.params = d;
103 return this.hash.params;
105 osrfMethod.prototype.serialize = function() {
109 'method' : this.hash.method,
110 'params' : this.hash.params
115 function osrfMethodException(hash) {
117 this._encodehash = true;
119 osrfMethodException.prototype.status = function(d) {
120 if(arguments.length == 1)
121 this.hash.status = d;
122 return this.hash.status;
124 osrfMethodException.prototype.statusCode = function(d) {
125 if(arguments.length == 1)
126 this.hash.statusCode = d;
127 return this.hash.statusCode;
129 function osrfConnectStatus(hash) {
131 this._encodehash = true;
133 osrfConnectStatus.prototype.status = function(d) {
134 if(arguments.length == 1)
135 this.hash.status = d;
136 return this.hash.status;
138 osrfConnectStatus.prototype.statusCode = function(d) {
139 if(arguments.length == 1)
140 this.hash.statusCode = d;
141 return this.hash.statusCode;
143 function osrfResult(hash) {
145 this._encodehash = true;
147 osrfResult.prototype.status = function(d) {
148 if(arguments.length == 1)
149 this.hash.status = d;
150 return this.hash.status;
152 osrfResult.prototype.statusCode = function(d) {
153 if(arguments.length == 1)
154 this.hash.statusCode = d;
155 return this.hash.statusCode;
157 osrfResult.prototype.content = function(d) {
158 if(arguments.length == 1)
159 this.hash.content = d;
160 return this.hash.content;
162 function osrfServerError(hash) {
164 this._encodehash = true;
166 osrfServerError.prototype.status = function(d) {
167 if(arguments.length == 1)
168 this.hash.status = d;
169 return this.hash.status;
171 osrfServerError.prototype.statusCode = function(d) {
172 if(arguments.length == 1)
173 this.hash.statusCode = d;
174 return this.hash.statusCode;
176 function osrfContinueStatus(hash) {
178 this._encodehash = true;
180 osrfContinueStatus.prototype.status = function(d) {
181 if(arguments.length == 1)
182 this.hash.status = d;
183 return this.hash.status;
185 osrfContinueStatus.prototype.statusCode = function(d) {
186 if(arguments.length == 1)
187 this.hash.statusCode = d;
188 return this.hash.statusCode;
192 OpenSRF.locale = null;
194 /* makes cls a subclass of pcls */
195 OpenSRF.set_subclass = function(cls, pcls) {
196 var str = cls+'.prototype = new '+pcls+'();';
197 str += cls+'.prototype.constructor = '+cls+';';
198 str += cls+'.baseClass = '+pcls+'.prototype.constructor;';
199 str += cls+'.prototype["super"] = '+pcls+'.prototype;';
204 /* general session superclass */
205 OpenSRF.Session = function() {
206 this.remote_id = null;
207 this.state = OSRF_APP_SESSION_DISCONNECTED;
210 //OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_WS;
211 OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_XHR;
213 OpenSRF.Session.cache = {};
214 OpenSRF.Session.find_session = function(thread_trace) {
215 return OpenSRF.Session.cache[thread_trace];
217 OpenSRF.Session.prototype.cleanup = function() {
218 delete OpenSRF.Session.cache[this.thread];
221 OpenSRF.Session.prototype.send = function(osrf_msg, args) {
222 args = (args) ? args : {};
223 switch(OpenSRF.Session.transport) {
224 case OSRF_TRANSPORT_TYPE_WS:
225 return this.send_ws(osrf_msg);
226 case OSRF_TRANSPORT_TYPE_WS_SHARED:
227 return this.send_ws_shared(osrf_msg);
228 case OSRF_TRANSPORT_TYPE_XHR:
229 return this.send_xhr(osrf_msg, args);
230 case OSRF_TRANSPORT_TYPE_XMPP:
231 return this.send_xmpp(osrf_msg, args);
235 OpenSRF.Session.prototype.send_xhr = function(osrf_msg, args) {
236 args.thread = this.thread;
237 args.rcpt = this.remote_id;
238 args.rcpt_service = this.service;
239 new OpenSRF.XHRequest(osrf_msg, args).send();
242 OpenSRF.Session.prototype.send_ws = function(osrf_msg) {
243 new OpenSRF.WebSocketRequest(
245 function(wsreq) {wsreq.send(osrf_msg)} // onopen
249 OpenSRF.Session.setup_shared_ws = function() {
251 OpenSRF.sharedWSWorker = new SharedWorker('opensrf_ws_shared.js');
253 OpenSRF.sharedWSWorker.port.addEventListener('message', function(e) {
255 console.log('sharedWSWorker received message ' + data.action);
257 if (data.action == 'message') {
258 // pass all inbound message up the opensrf stack
260 var msg = JSON2js(data.message); // TODO: json error handling
262 new OpenSRF.NetMessage(
263 null, null, msg.thread, null, msg.osrf_msg)
269 if (data.action == 'error') {
270 throw new Error(data.message);
274 OpenSRF.sharedWSWorker.port.start();
277 OpenSRF.Session.prototype.send_ws_shared = function(message) {
279 if (!OpenSRF.sharedWSWorker)
280 OpenSRF.Session.setup_shared_ws();
283 service : this.service,
284 thread : this.thread,
285 osrf_msg : [message.serialize()]
288 OpenSRF.sharedWSWorker.port.postMessage({
290 // pass the thread additionally as a stand-alone value so the
291 // worker can more efficiently inspect it.
292 thread : this.thread,
298 OpenSRF.Session.prototype.send_xmpp = function(osrf_msg, args) {
299 alert('xmpp transport not implemented');
303 /* client sessions make requests */
304 OpenSRF.ClientSession = function(service) {
305 this.service = service;
306 this.remote_id = null;
307 this.locale = OpenSRF.locale || 'en-US';
310 this.onconnect = null;
311 this.thread = Math.random() + '' + new Date().getTime();
312 OpenSRF.Session.cache[this.thread] = this;
314 OpenSRF.set_subclass('OpenSRF.ClientSession', 'OpenSRF.Session');
317 OpenSRF.ClientSession.prototype.connect = function(args) {
318 args = (args) ? args : {};
319 this.remote_id = null;
321 if (this.state == OSRF_APP_SESSION_CONNECTED) {
322 if (args.onconnect) args.onconnect();
327 this.onconnect = args.onconnect;
330 /* if no handler is provided, make this a synchronous call */
331 this.timeout = (args.timeout) ? args.timeout : 5;
334 message = new osrfMessage({
335 'threadTrace' : this.last_id++,
336 'type' : OSRF_MESSAGE_TYPE_CONNECT
339 this.send(message, {'timeout' : this.timeout});
341 if(this.onconnect || this.state == OSRF_APP_SESSION_CONNECTED)
347 OpenSRF.ClientSession.prototype.disconnect = function(args) {
349 if (this.state == OSRF_APP_SESSION_CONNECTED) {
352 'threadTrace' : this.last_id++,
353 'type' : OSRF_MESSAGE_TYPE_DISCONNECT
358 this.remote_id = null;
359 this.state = OSRF_APP_SESSION_DISCONNECTED;
363 OpenSRF.ClientSession.prototype.request = function(args) {
365 if(this.state != OSRF_APP_SESSION_CONNECTED)
366 this.remote_id = null;
368 if(typeof args == 'string') {
370 for(var i = 1; i < arguments.length; i++)
371 params.push(arguments[i]);
378 if(typeof args == 'undefined')
382 var req = new OpenSRF.Request(this, this.last_id++, args);
383 this.requests.push(req);
387 OpenSRF.ClientSession.prototype.find_request = function(reqid) {
388 for(var i = 0; i < this.requests.length; i++) {
389 var req = this.requests[i];
390 if(req.reqid == reqid)
396 OpenSRF.Request = function(session, reqid, args) {
397 this.session = session;
401 this.onresponse = args.onresponse;
402 this.oncomplete = args.oncomplete;
403 this.onerror = args.onerror;
404 this.onmethoderror = args.onmethoderror;
405 this.ontransporterror = args.ontransporterror;
407 this.method = args.method;
408 this.params = args.params;
409 this.timeout = args.timeout;
410 this.response_queue = [];
411 this.complete = false;
414 OpenSRF.Request.prototype.peek_last = function(timeout) {
415 if(this.response_queue.length > 0) {
416 var x = this.response_queue.pop();
417 this.response_queue.push(x);
423 OpenSRF.Request.prototype.peek = function(timeout) {
424 if(this.response_queue.length > 0)
425 return this.response_queue[0];
429 OpenSRF.Request.prototype.recv = function(timeout) {
430 if(this.response_queue.length > 0)
431 return this.response_queue.shift();
435 OpenSRF.Request.prototype.send = function() {
436 method = new osrfMethod({'method':this.method, 'params':this.params});
437 message = new osrfMessage({
438 'threadTrace' : this.reqid,
439 'type' : OSRF_MESSAGE_TYPE_REQUEST,
441 'locale' : this.session.locale
444 this.session.send(message, {
445 'timeout' : this.timeout,
446 'onresponse' : this.onresponse,
447 'oncomplete' : this.oncomplete,
448 'onerror' : this.onerror,
449 'onmethoderror' : this.onmethoderror,
450 'ontransporterror' : this.ontransporterror
454 OpenSRF.NetMessage = function(to, from, thread, body, osrf_msg) {
457 this.thread = thread;
459 this.osrf_msg = osrf_msg;
462 OpenSRF.Stack = function() {
465 // global inbound message queue
466 OpenSRF.Stack.queue = [];
471 dump(msg + '\n'); // xulrunner
477 // ses may be passed to us by the network handler
478 OpenSRF.Stack.push = function(net_msg, callbacks) {
479 var ses = OpenSRF.Session.find_session(net_msg.thread);
481 ses.remote_id = net_msg.from;
483 // NetMessage's from websocket connections are parsed before they get here
484 osrf_msgs = net_msg.osrf_msg;
489 osrf_msgs = JSON2js(net_msg.body);
491 // TODO: pretty sure we don't need this..
492 if (OpenSRF.Session.transport == OSRF_TRANSPORT_TYPE_WS) {
493 // WebSocketRequests wrap the content
494 osrf_msgs = osrf_msgs.osrf_msg;
498 log('Error parsing OpenSRF message body as JSON: ' + net_msg.body + '\n' + E);
501 * For unknown reasons, the Content-Type header will occasionally
502 * be included in the XHR.responseText for multipart/mixed messages.
503 * When this happens, strip the header and newlines from the message
506 net_msg.body = net_msg.body.replace(/^.*\n\n/, '');
507 log('Cleaning up and retrying...');
510 osrf_msgs = JSON2js(net_msg.body);
512 log('Unable to clean up message, giving up: ' + net_msg.body);
518 // push the latest responses onto the end of the inbound message queue
519 for(var i = 0; i < osrf_msgs.length; i++)
520 OpenSRF.Stack.queue.push({msg : osrf_msgs[i], ses : ses});
522 // continue processing responses, oldest to newest
523 while(OpenSRF.Stack.queue.length) {
524 var data = OpenSRF.Stack.queue.shift();
525 OpenSRF.Stack.handle_message(data.ses, data.msg);
529 OpenSRF.Stack.handle_message = function(ses, osrf_msg) {
531 var req = ses.find_request(osrf_msg.threadTrace());
533 if(osrf_msg.type() == OSRF_MESSAGE_TYPE_STATUS) {
535 var payload = osrf_msg.payload();
536 var status = payload.statusCode();
537 var status_text = payload.status();
539 if(status == OSRF_STATUS_COMPLETE) {
542 if(req.oncomplete && !req.oncomplete_called) {
543 req.oncomplete_called = true;
544 return req.oncomplete(req);
549 if(status == OSRF_STATUS_OK) {
550 ses.state = OSRF_APP_SESSION_CONNECTED;
552 /* call the connect callback */
553 if(ses.onconnect && !ses.onconnect_called) {
554 ses.onconnect_called = true;
555 return ses.onconnect();
559 if(status == OSRF_STATUS_NOTFOUND || status == OSRF_STATUS_INTERNALSERVERERROR) {
560 if(req && req.onmethoderror)
561 return req.onmethoderror(req, status, status_text);
565 if(osrf_msg.type() == OSRF_MESSAGE_TYPE_RESULT) {
567 req.response_queue.push(osrf_msg.payload());
569 return req.onresponse(req);