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;
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';
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;
50 /* The following classes map directly to network-serializable opensrf objects */
52 function osrfMessage(hash) {
55 this.hash.locale = OpenSRF.locale || 'en-US';
56 this._encodehash = true;
58 osrfMessage.prototype.threadTrace = function(d) {
59 if(arguments.length == 1)
60 this.hash.threadTrace = d;
61 return this.hash.threadTrace;
63 osrfMessage.prototype.type = function(d) {
64 if(arguments.length == 1)
66 return this.hash.type;
68 osrfMessage.prototype.payload = function(d) {
69 if(arguments.length == 1)
70 this.hash.payload = d;
71 return this.hash.payload;
73 osrfMessage.prototype.locale = function(d) {
74 if(arguments.length == 1)
76 return this.hash.locale;
78 osrfMessage.prototype.serialize = function() {
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
90 function osrfMethod(hash) {
92 this._encodehash = true;
94 osrfMethod.prototype.method = function(d) {
95 if(arguments.length == 1)
97 return this.hash.method;
99 osrfMethod.prototype.params = function(d) {
100 if(arguments.length == 1)
101 this.hash.params = d;
102 return this.hash.params;
104 osrfMethod.prototype.serialize = function() {
108 'method' : this.hash.method,
109 'params' : this.hash.params
114 function osrfMethodException(hash) {
116 this._encodehash = true;
118 osrfMethodException.prototype.status = function(d) {
119 if(arguments.length == 1)
120 this.hash.status = d;
121 return this.hash.status;
123 osrfMethodException.prototype.statusCode = function(d) {
124 if(arguments.length == 1)
125 this.hash.statusCode = d;
126 return this.hash.statusCode;
128 function osrfConnectStatus(hash) {
130 this._encodehash = true;
132 osrfConnectStatus.prototype.status = function(d) {
133 if(arguments.length == 1)
134 this.hash.status = d;
135 return this.hash.status;
137 osrfConnectStatus.prototype.statusCode = function(d) {
138 if(arguments.length == 1)
139 this.hash.statusCode = d;
140 return this.hash.statusCode;
142 function osrfResult(hash) {
144 this._encodehash = true;
146 osrfResult.prototype.status = function(d) {
147 if(arguments.length == 1)
148 this.hash.status = d;
149 return this.hash.status;
151 osrfResult.prototype.statusCode = function(d) {
152 if(arguments.length == 1)
153 this.hash.statusCode = d;
154 return this.hash.statusCode;
156 osrfResult.prototype.content = function(d) {
157 if(arguments.length == 1)
158 this.hash.content = d;
159 return this.hash.content;
161 function osrfServerError(hash) {
163 this._encodehash = true;
165 osrfServerError.prototype.status = function(d) {
166 if(arguments.length == 1)
167 this.hash.status = d;
168 return this.hash.status;
170 osrfServerError.prototype.statusCode = function(d) {
171 if(arguments.length == 1)
172 this.hash.statusCode = d;
173 return this.hash.statusCode;
175 function osrfContinueStatus(hash) {
177 this._encodehash = true;
179 osrfContinueStatus.prototype.status = function(d) {
180 if(arguments.length == 1)
181 this.hash.status = d;
182 return this.hash.status;
184 osrfContinueStatus.prototype.statusCode = function(d) {
185 if(arguments.length == 1)
186 this.hash.statusCode = d;
187 return this.hash.statusCode;
191 OpenSRF.locale = null;
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;';
203 /* general session superclass */
204 OpenSRF.Session = function() {
205 this.remote_id = null;
206 this.state = OSRF_APP_SESSION_DISCONNECTED;
209 //OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_WS;
210 OpenSRF.Session.transport = OSRF_TRANSPORT_TYPE_XHR;
212 OpenSRF.Session.cache = {};
213 OpenSRF.Session.find_session = function(thread_trace) {
214 return OpenSRF.Session.cache[thread_trace];
216 OpenSRF.Session.prototype.cleanup = function() {
217 delete OpenSRF.Session.cache[this.thread];
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);
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();
239 OpenSRF.Session.prototype.send_ws = function(osrf_msg) {
240 new OpenSRF.WebSocketRequest(
242 function(wsreq) {wsreq.send(osrf_msg)} // onopen
246 OpenSRF.Session.prototype.send_xmpp = function(osrf_msg, args) {
247 alert('xmpp transport not implemented');
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';
258 this.onconnect = null;
259 this.thread = Math.random() + '' + new Date().getTime();
260 OpenSRF.Session.cache[this.thread] = this;
262 OpenSRF.set_subclass('OpenSRF.ClientSession', 'OpenSRF.Session');
265 OpenSRF.ClientSession.prototype.connect = function(args) {
266 args = (args) ? args : {};
267 this.remote_id = null;
269 if (this.state == OSRF_APP_SESSION_CONNECTED) {
270 if (args.onconnect) args.onconnect();
275 this.onconnect = args.onconnect;
278 /* if no handler is provided, make this a synchronous call */
279 this.timeout = (args.timeout) ? args.timeout : 5;
282 message = new osrfMessage({
283 'threadTrace' : this.last_id++,
284 'type' : OSRF_MESSAGE_TYPE_CONNECT
287 this.send(message, {'timeout' : this.timeout});
289 if(this.onconnect || this.state == OSRF_APP_SESSION_CONNECTED)
295 OpenSRF.ClientSession.prototype.disconnect = function(args) {
297 if (this.state == OSRF_APP_SESSION_CONNECTED) {
300 'threadTrace' : this.last_id++,
301 'type' : OSRF_MESSAGE_TYPE_DISCONNECT
306 this.remote_id = null;
307 this.state = OSRF_APP_SESSION_DISCONNECTED;
311 OpenSRF.ClientSession.prototype.request = function(args) {
313 if(this.state != OSRF_APP_SESSION_CONNECTED)
314 this.remote_id = null;
316 if(typeof args == 'string') {
318 for(var i = 1; i < arguments.length; i++)
319 params.push(arguments[i]);
326 if(typeof args == 'undefined')
330 var req = new OpenSRF.Request(this, this.last_id++, args);
331 this.requests.push(req);
335 OpenSRF.ClientSession.prototype.find_request = function(reqid) {
336 for(var i = 0; i < this.requests.length; i++) {
337 var req = this.requests[i];
338 if(req.reqid == reqid)
344 OpenSRF.Request = function(session, reqid, args) {
345 this.session = session;
349 this.onresponse = args.onresponse;
350 this.oncomplete = args.oncomplete;
351 this.onerror = args.onerror;
352 this.onmethoderror = args.onmethoderror;
353 this.ontransporterror = args.ontransporterror;
355 this.method = args.method;
356 this.params = args.params;
357 this.timeout = args.timeout;
358 this.response_queue = [];
359 this.complete = false;
362 OpenSRF.Request.prototype.peek_last = function(timeout) {
363 if(this.response_queue.length > 0) {
364 var x = this.response_queue.pop();
365 this.response_queue.push(x);
371 OpenSRF.Request.prototype.peek = function(timeout) {
372 if(this.response_queue.length > 0)
373 return this.response_queue[0];
377 OpenSRF.Request.prototype.recv = function(timeout) {
378 if(this.response_queue.length > 0)
379 return this.response_queue.shift();
383 OpenSRF.Request.prototype.send = function() {
384 method = new osrfMethod({'method':this.method, 'params':this.params});
385 message = new osrfMessage({
386 'threadTrace' : this.reqid,
387 'type' : OSRF_MESSAGE_TYPE_REQUEST,
389 'locale' : this.session.locale
392 this.session.send(message, {
393 'timeout' : this.timeout,
394 'onresponse' : this.onresponse,
395 'oncomplete' : this.oncomplete,
396 'onerror' : this.onerror,
397 'onmethoderror' : this.onmethoderror,
398 'ontransporterror' : this.ontransporterror
402 OpenSRF.NetMessage = function(to, from, thread, body, osrf_msg) {
405 this.thread = thread;
407 this.osrf_msg = osrf_msg;
410 OpenSRF.Stack = function() {
413 // global inbound message queue
414 OpenSRF.Stack.queue = [];
419 dump(msg + '\n'); // xulrunner
425 // ses may be passed to us by the network handler
426 OpenSRF.Stack.push = function(net_msg, callbacks) {
427 var ses = OpenSRF.Session.find_session(net_msg.thread);
429 ses.remote_id = net_msg.from;
431 // NetMessage's from websocket connections are parsed before they get here
432 osrf_msgs = net_msg.osrf_msg;
437 osrf_msgs = JSON2js(net_msg.body);
439 if (OpenSRF.Session.transport == OSRF_TRANSPORT_TYPE_WS) {
440 // WebSocketRequests wrap the content
441 osrf_msgs = osrf_msgs.osrf_msg;
445 log('Error parsing OpenSRF message body as JSON: ' + net_msg.body + '\n' + E);
448 * For unknown reasons, the Content-Type header will occasionally
449 * be included in the XHR.responseText for multipart/mixed messages.
450 * When this happens, strip the header and newlines from the message
453 net_msg.body = net_msg.body.replace(/^.*\n\n/, '');
454 log('Cleaning up and retrying...');
457 osrf_msgs = JSON2js(net_msg.body);
459 log('Unable to clean up message, giving up: ' + net_msg.body);
465 // push the latest responses onto the end of the inbound message queue
466 for(var i = 0; i < osrf_msgs.length; i++)
467 OpenSRF.Stack.queue.push({msg : osrf_msgs[i], ses : ses});
469 // continue processing responses, oldest to newest
470 while(OpenSRF.Stack.queue.length) {
471 var data = OpenSRF.Stack.queue.shift();
472 OpenSRF.Stack.handle_message(data.ses, data.msg);
476 OpenSRF.Stack.handle_message = function(ses, osrf_msg) {
478 var req = ses.find_request(osrf_msg.threadTrace());
480 if(osrf_msg.type() == OSRF_MESSAGE_TYPE_STATUS) {
482 var payload = osrf_msg.payload();
483 var status = payload.statusCode();
484 var status_text = payload.status();
486 if(status == OSRF_STATUS_COMPLETE) {
489 if(req.oncomplete && !req.oncomplete_called) {
490 req.oncomplete_called = true;
491 return req.oncomplete(req);
496 if(status == OSRF_STATUS_OK) {
497 ses.state = OSRF_APP_SESSION_CONNECTED;
499 /* call the connect callback */
500 if(ses.onconnect && !ses.onconnect_called) {
501 ses.onconnect_called = true;
502 return ses.onconnect();
506 if(status == OSRF_STATUS_NOTFOUND || status == OSRF_STATUS_INTERNALSERVERERROR) {
507 if(req && req.onmethoderror)
508 return req.onmethoderror(req, status, status_text);
512 if(osrf_msg.type() == OSRF_MESSAGE_TYPE_RESULT) {
514 req.response_queue.push(osrf_msg.payload());
516 return req.onresponse(req);