]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/opac/common/js/RemoteRequest.js
ae43f114027d620050a3bde96a83a1ef511bb07b
[working/Evergreen.git] / Open-ILS / web / opac / common / js / RemoteRequest.js
1 var XML_HTTP_GATEWAY = "osrf-gateway-v1";
2 var XML_HTTP_SERVER = "";
3
4
5 /* This object is thrown when network failures occur */
6 function NetworkFailure(stat, url) { 
7         this._status = stat; 
8         this._url = url;
9 }
10
11 NetworkFailure.prototype.status = function() { return this._status; }
12 NetworkFailure.prototype.url = function() { return this._url; }
13 NetworkFailure.prototype.toString = function() { 
14         return "Network Failure: status = " + this.status() +'\n'+this.url(); 
15 }
16
17
18
19 function isXUL() { try { if(IAMXUL) return true;}catch(e){return false;}; }
20 var _allrequests = {};
21
22 // If the legacy JSON gateway is needed by the staff client, uncomment this
23 /* 
24 if(isXUL()) {
25     XML_HTTP_GATEWAY = 'gateway';
26 }
27 */
28
29 function cleanRemoteRequests() {
30         for( var i in _allrequests ) 
31                 destroyRequest(_allrequests[i]);
32 }
33
34 function abortAllRequests() {
35         for( var i in _allrequests ) {
36                 var r = _allrequests[i];
37                 if(r) { 
38                         r.abort();
39                         destroyRequest(r);
40                 }
41         }
42 }
43
44 function destroyRequest(r) {
45         if(r == null) return;
46
47         if( r.xmlhttp ) {
48                 r.xmlhttp.onreadystatechange = function(){};
49                 r.xmlhttp = null;
50         }
51
52         r.callback                              = null;
53         r.userdata                              = null;
54         _allrequests[r.id]      = null;
55 }
56
57 /* ----------------------------------------------------------------------- */
58 /* Request object */
59 var rrId = 0;
60 function RemoteRequest( service, method ) {
61
62         /* dojo is currently only available in the OPAC */
63         try {
64                 /* We want OpenSRF.locale for xx-YY format */
65                 this.locale     = OpenSRF.locale;
66         }
67         catch (e) {
68                 this.locale = null;
69         }
70         this.service    = service;
71         this.method             = method;
72         this.xmlhttp    = false;
73         this.name               = null;
74         this.alertEvent = true; /* only used when isXUL is false */
75
76         this.type               = "POST"; /* default */
77         this.id                 = rrId++;
78         this.cancelled = false;
79
80         this.setSecure(false);
81         if(isXUL()) this.setSecure(true);
82
83         _allrequests[this.id] = this;
84
85         var i = 2;
86         this.params = ""; 
87
88         while(i < arguments.length) {
89                 var object = js2JSON(arguments[i++]);
90                 this.params += "&param=" + encodeURIComponent(object);
91         }
92
93         if(!this.params) { this.params = ""; }
94
95         this.param_string = "service=" + service + "&method=" + method + this.params;
96         if (this.locale != null) {
97                 this.param_string = this.param_string + "&locale=" + this.locale;
98         }
99         if( this.buildXMLRequest() == null ) alert("Browser is not supported!");
100
101 }
102
103
104 RemoteRequest.prototype.timeout = function(t) {
105         t *= 1000
106         var req = this;
107         req.timeoutFunc = setTimeout(
108                 function() {
109                         if( req && req.xmlhttp ) {
110                                 req.cancelled = true;
111                                 req.abort();
112                                 if( req.abtCallback ) {
113                                         req.abtCallback(req);
114                                 }
115                         }
116                 },
117                 t
118         );
119 }
120
121 RemoteRequest.prototype.abortCallback = function(func) {
122         this.abtCallback = func;
123 }
124
125 RemoteRequest.prototype.event = function(evt) {
126         if( arguments.length > 0 )
127                 this.evt = evt;
128         return this.evt;
129 }
130
131 RemoteRequest.prototype.abort = function() {
132         if( this.xmlhttp ) {
133                 /* this has to come before abort() or IE will puke on you */
134                 this.xmlhttp.onreadystatechange = function(){};
135                 this.xmlhttp.abort();
136         }
137 }
138
139 /* constructs our XMLHTTPRequest object */
140 RemoteRequest.prototype.buildXMLRequest = function() {
141         this.xmlhttp = buildXMLRequest();
142         return true;
143 }
144
145
146 function buildXMLRequest() {
147     try {
148             return new XMLHttpRequest();
149     } catch(e) {
150             try { 
151                     return new ActiveXObject("Msxml2.XMLHTTP"); 
152             } catch (e2) {
153                     try { 
154                             return new ActiveXObject("Microsoft.XMLHTTP"); 
155                     } catch (e3) {
156                         alert("NEEDS NEWER JAVASCRIPT for XMLHTTPRequest()");
157                 return null;
158                     }
159             }
160     }
161 }
162
163
164 function _remoteRequestCallback(id) {
165
166         var object = _allrequests[id];
167         if(object.cancelled) return;
168
169         if( object.xmlhttp.readyState == 4 ) {
170
171         try {
172             object.duration = new Date().getTime() - object.sendTime;
173             dump('request ' + object.id + ': duration = ' + object.duration + ' ms\n');
174         } catch(ee){}
175
176                 try {
177                         object.callback(object);
178                 } catch(E) {
179             throw E
180                 } finally { 
181                         destroyRequest(object); 
182                         object = null; 
183                 }  
184         }
185 }
186
187
188 /* define the callback we use when this request has received
189         all of its data */
190 RemoteRequest.prototype.setCompleteCallback = function(callback) {
191         if(this.cancelled) return;
192         this.callback = callback;
193         var id = this.id;
194         this.xmlhttp.onreadystatechange = function() { _remoteRequestCallback(id); }
195 }
196
197
198 /* http by default.  This makes it https. *ONLY works when
199         embedded in a XUL app. */
200 RemoteRequest.prototype.setSecure = function(bool) {
201         this.secure = bool; 
202 }
203
204 RemoteRequest.prototype.send = function(blocking) {
205
206         if(this.cancelled) return;
207
208         /* determine the xmlhttp server dynamically */
209         var url = location.protocol + "//" + location.host + "/" + XML_HTTP_GATEWAY;
210
211         if(isXUL()) {
212                 if( XML_HTTP_SERVER ) 
213                         url = 'http://'+XML_HTTP_SERVER+'/'+XML_HTTP_GATEWAY;
214
215                 if( url.match(/^http:/) && 
216                                 (this.secure || location.href.match(/^https:/) || location.href.match(/^chrome:/) ) ) {
217                         netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
218                         url = url.replace(/^http:/, 'https:');
219                 }
220         }
221
222         var data = null;
223         if( this.type == 'GET' ) url +=  "?" + this.param_string; 
224
225         this.url = url;
226
227    //if( isXUL() ) dump('request URL = ' + url + '?' + this.param_string + '\n');
228
229         try {
230
231                 if(blocking) this.xmlhttp.open(this.type, url, false);
232                 else this.xmlhttp.open(this.type, url, true);
233                 
234         } catch(E) {
235                 alert("Fatal error opening XMLHTTPRequest for URL:\n" + url + '\n' + E);
236                 return;
237         }
238
239         if( this.type == 'POST' ) {
240                 data = this.param_string;
241                 this.xmlhttp.setRequestHeader('Content-Type',
242                                 'application/x-www-form-urlencoded');
243         }
244
245         try {
246                 var auth;
247                 try { dojo.require('dojo.cookie'); auth = dojo.cookie(COOKIE_SES) } catch(ee) {}
248                 if( isXUL() ) auth = fetchXULStash().session.key;
249                 if( auth ) 
250                         this.xmlhttp.setRequestHeader('X-OILS-Authtoken', auth);
251
252         } catch(e) {}
253
254         if(data && data.match(/param=undefined/)) {
255                 /* we get a bogus param .. replace with NULL */
256                 try{dump('!+! UNDEFINED PARAM IN QUERY: ' + this.service + ' : ' + this.method+'\n');}catch(r){}
257                 data = data.replace(/param=undefined/g,'param=null');
258         }
259
260
261     this.sendTime = new Date().getTime();
262         try{ this.xmlhttp.send( data ); } catch(e){}
263
264         return this;
265 }
266
267 /* returns the actual response text from the request */
268 RemoteRequest.prototype.getText = function() {
269         return this.xmlhttp.responseText;
270 }
271
272 RemoteRequest.prototype.isReady = function() {
273         return this.xmlhttp.readyState == 4;
274 }
275
276
277 /* returns the JSON->js result object  */
278 RemoteRequest.prototype.getResultObject = function() {
279
280         if(this.cancelled) return null;
281         if(!this.xmlhttp) return null;
282
283         var failed = false;
284         var status = null;
285         this.event(null);
286
287         /*
288         try {
289                 dump(this.url + '?' + this.param_string + '\n' +
290                         'Returned with \n\tstatus = ' + this.xmlhttp.status + 
291                         '\n\tpayload= ' + this.xmlhttp.responseText + '\n');
292         } catch(e) {}
293         */
294
295         try {
296                 status = this.xmlhttp.status;
297                 if( status != 200 ) failed = true;
298         } catch(e) { failed = true; }
299
300         if( failed ) {
301                 if(!status) status = '<unknown>';
302                 try{dump('! NETWORK FAILURE.  HTTP STATUS = ' +status+'\n'+this.param_string+'\n');}catch(e){}
303                 if(isXUL()) 
304                         throw new NetworkFailure(status, this.param_string);
305                 else return null;
306         }
307
308         var text = this.xmlhttp.responseText;
309
310         //try{if(getDebug()) _debug('response: ' + text + '\n')}catch(e){}
311
312         if(text == "" || text == " " || text == null) {
313                 try { dump('dbg: Request returned no text!\n'); } catch(E) {}
314                 if(isXUL()) 
315                         throw new NetworkFailure(status, this.param_string);
316                 return null;
317         }
318
319         var obj = JSON2js(text);
320         if(!obj) return null;
321
322         if( obj.status != 200 ) {
323
324                 var str = 'A server error occurred. Debug information follows: ' +
325                                         '\ncode = '             + obj.status + 
326                                         '\ndebug: '             + obj.debug + 
327                                         '\npayload: '   + js2JSON(obj.payload); 
328
329                 if(isXUL()) {
330                         dump(str);
331                         throw obj;
332
333                 } else {
334                         _debug(str);
335                         throw str;
336                 }
337         }
338
339         var payload = obj.payload;
340         if(!payload || payload.length == 0) return null;
341         payload = (payload.length == 1) ? payload[0] : payload;
342
343         if(!isXUL()) {
344                 if( checkILSEvent(payload) ) {
345                         this.event(payload);
346                         if( this.alertEvent ) {
347                                 alertILSEvent(payload);
348                                 return null;
349                         }
350                 } 
351         }
352
353         return payload;
354 }
355
356 /* adds a new parameter to the request */
357 RemoteRequest.prototype.addParam = function(param) {
358         var string = encodeURIComponent(js2JSON(param));
359         this.param_string += "&param=" + string;
360 }
361
362 function fetchXULStash() {
363         if( isXUL() ) {
364                 try {
365                         netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
366                         var __OILS = new Components.Constructor("@mozilla.org/openils_data_cache;1", "nsIOpenILS");
367                         var data_cache = new __OILS( );
368                         return data_cache.wrappedJSObject.OpenILS.prototype.data;
369         
370                 } catch(E) {
371                         _debug('Error in OpenILS.data._debug_stash(): ' + js2JSON(E) );
372                 }
373         }
374         return {};
375 }
376
377