]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/hatch.js
4fee7cb5c99c2a4478d707994925c0296329bc90
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / hatch.js
1 /**
2  * Core Service - egHatch
3  *
4  * Dispatches print and data storage requests to the appropriate handler.
5  *
6  * If Hatch is configured to honor the request -- current request types
7  * are 'settings', 'offline', and 'printing' -- the request will be
8  * relayed to the Hatch service.  Otherwise, the request is handled
9  * locally.
10  *
11  * Most handlers also provide direct remote and local variants to the
12  * application can decide to which to use as needed.
13  *
14  * Local storage requests are handled by $window.localStorage.
15  *
16  * Note that all top-level and remote requests return promises.  All
17  * local requests return immediate values, since local requests are
18  * never asynchronous.
19  *
20  * BEWARE: never store "fieldmapper" objects, since their structure
21  * may change over time as the IDL changes.  Always flatten objects
22  * into key/value pairs before calling set*Item()
23  *
24  */
25 angular.module('egCoreMod')
26
27 .factory('egHatch',
28            ['$q','$window','$timeout','$interpolate','$http','$cookies',
29     function($q , $window , $timeout , $interpolate , $http , $cookies) {
30
31     var service = {};
32     service.msgId = 1;
33     service.messages = {};
34     service.hatchAvailable = false;
35
36     // key/value cache -- avoid unnecessary Hatch extension requests.
37     // Only affects *RemoteItem calls.
38     service.keyCache = {}; 
39
40     /**
41      * List string prefixes for On-Call storage keys. On-Call keys
42      * are those that can be set/get/remove'd from localStorage when
43      * Hatch is not avaialable, even though Hatch is configured as the
44      * primary storage location for the key in question.  On-Call keys
45      * are those that allow the user to login and perform basic admin
46      * tasks (like disabling Hatch) even when Hatch is down.
47      * AKA Browser Staff Run Level 3.
48      * Note that no attempt is made to synchronize data between Hatch
49      * and localStorage for On-Call keys.  Only one destation is active 
50      * at a time and each maintains its own data separately.
51      */
52     service.onCallPrefixes = ['eg.workstation'];
53
54     // Returns true if the key can be set/get in localStorage even when 
55     // Hatch is not available.
56     service.keyIsOnCall = function(key) {
57         var oncall = false;
58         angular.forEach(service.onCallPrefixes, function(pfx) {
59             if (key.match(new RegExp('^' + pfx))) 
60                 oncall = true;
61         });
62         return oncall;
63     }
64
65     // write a message to the Hatch port
66     service.sendToHatch = function(msg) {
67         var msg2 = {};
68
69         // shallow copy and scrub msg before sending
70         angular.forEach(msg, function(val, key) {
71             if (key.match(/deferred/)) return;
72             msg2[key] = val;
73         });
74
75         console.debug("sending to Hatch: " + JSON.stringify(msg2));
76
77         msg2.from = 'page';
78         $window.postMessage(msg2, $window.location.origin);
79     }
80
81     // Send request to Hatch or reject if Hatch is unavailable
82     service.attemptHatchDelivery = function(msg) {
83         msg.msgid = service.msgId++;
84         msg.deferred = $q.defer();
85
86         if (service.hatchAvailable) {
87             service.messages[msg.msgid] = msg;
88             service.sendToHatch(msg);
89
90         } else {
91             console.error(
92                 'Hatch request attempted but Hatch is not available');
93             msg.deferred.reject(msg);
94         }
95
96         return msg.deferred.promise;
97     }
98
99
100     // resolve the promise on the given request and remove
101     // it from our tracked requests.
102     service.resolveRequest = function(msg) {
103
104         if (!service.messages[msg.msgid]) {
105             console.error('no cached message for id = ' + msg.msgid);
106             return;
107         }
108
109         // for requests sent through Hatch, only the cached 
110         // request will have the original promise attached
111         msg.deferred = service.messages[msg.msgid].deferred;
112         delete service.messages[msg.msgid]; // un-cache
113
114         if (msg.status == 200) {
115             msg.deferred.resolve(msg.content);
116         } else {
117             console.warn("Hatch command failed with status=" 
118                 + msg.status + " and message=" + msg.message);
119             msg.deferred.reject();
120         }
121     }
122
123     service.openHatch = function() {
124
125         // When the Hatch extension loads, it tacks an attribute onto
126         // the top-level documentElement to indicate it's available.
127         if (!$window.document.documentElement.getAttribute('hatch-is-open')) {
128             console.debug("Hatch is not available");
129             return;
130         }
131
132         $window.addEventListener("message", function(event) {
133             // We only accept messages from our own content script.
134             if (event.source != window) return;
135
136             // We only care about messages from the Hatch extension.
137             if (event.data && event.data.from == 'extension') {
138
139                 // Avoid logging full Hatch responses. they can get large.
140                 console.debug(
141                     'Hatch responded to message ID ' + event.data.msgid);
142
143                 service.resolveRequest(event.data);
144             }
145         }); 
146
147         service.hatchAvailable = true; // public flag
148     }
149
150     service.remotePrint = function(
151         context, contentType, content, withDialog) {
152
153         return service.getPrintConfig(context).then(
154             function(config) {
155                 // print configuration retrieved; print
156                 return service.attemptHatchDelivery({
157                     action : 'print',
158                     settings : config,
159                     content : content, 
160                     contentType : contentType,
161                     showDialog : withDialog,
162                 });
163             }
164         );
165     }
166
167     service.getPrintConfig = function(context) {
168         return service.getRemoteItem('eg.print.config.' + context);
169     }
170
171     service.setPrintConfig = function(context, config) {
172         return service.setRemoteItem('eg.print.config.' + context, config);
173     }
174
175     service.getPrinterOptions = function(name) {
176         return service.attemptHatchDelivery({
177             action : 'printer-options',
178             printer : name
179         });
180     }
181
182     service.getPrinters = function() {
183         if (service.printers) // cached printers
184             return $q.when(service.printers);
185
186         return service.attemptHatchDelivery({action : 'printers'}).then(
187
188             // we have remote printers; sort by name and return
189             function(printers) {
190                 service.printers = printers.sort(
191                     function(a,b) {return a.name < b.name ? -1 : 1});
192                 return service.printers;
193             },
194
195             // remote call failed and there is no such thing as local
196             // printers; return empty set.
197             function() { return [] } 
198         );
199     }
200
201     service.usePrinting = function() {
202         return service.getLocalItem('eg.hatch.enable.printing');
203     }
204
205     service.useSettings = function() {
206         return service.getLocalItem('eg.hatch.enable.settings');
207     }
208
209     service.useOffline = function() {
210         return service.getLocalItem('eg.hatch.enable.offline');
211     }
212
213     // get the value for a stored item
214     service.getItem = function(key) {
215
216         if (!service.useSettings())
217             return $q.when(service.getLocalItem(key));
218
219         if (service.hatchAvailable) 
220             return service.getRemoteItem(key);
221
222         if (service.keyIsOnCall(key)) {
223             console.warn("Unable to getItem from Hatch: " + key + 
224                 ". Retrieving item from local storage instead");
225
226             return $q.when(service.getLocalItem(key));
227         }
228
229         console.error("Unable to getItem from Hatch: " + key);
230         return $q.reject();
231     }
232
233     service.getRemoteItem = function(key) {
234         
235         if (service.keyCache[key] != undefined)
236             return $q.when(service.keyCache[key])
237
238         return service.attemptHatchDelivery({
239             key : key,
240             action : 'get'
241         }).then(function(content) {
242             return service.keyCache[key] = content;
243         });
244     }
245
246     service.getLocalItem = function(key) {
247         var val = $window.localStorage.getItem(key);
248         if (val == null) return;
249         try {
250             return JSON.parse(val);
251         } catch(E) {
252             console.error(
253                 "Deleting invalid JSON for localItem: " + key + " => " + val);
254             service.removeLocalItem(key);
255             return null;
256         }
257     }
258
259     service.getLoginSessionItem = function(key) {
260         var val = $cookies.get(key);
261         if (val == null) return;
262         return JSON.parse(val);
263     }
264
265     service.getSessionItem = function(key) {
266         var val = $window.sessionStorage.getItem(key);
267         if (val == null) return;
268         return JSON.parse(val);
269     }
270
271     /**
272      * @param tmp bool Store the value as a session cookie only.  
273      * tmp values are removed during logout or browser close.
274      */
275     service.setItem = function(key, value) {
276         if (!service.useSettings())
277             return $q.when(service.setLocalItem(key, value));
278
279         if (service.hatchAvailable)
280             return service.setRemoteItem(key, value);
281
282         if (service.keyIsOnCall(key)) {
283             console.warn("Unable to setItem in Hatch: " + 
284                 key + ". Setting in local storage instead");
285
286             return $q.when(service.setLocalItem(key, value));
287         }
288
289         console.error("Unable to setItem in Hatch: " + key);
290         return $q.reject();
291     }
292
293     // set the value for a stored or new item
294     service.setRemoteItem = function(key, value) {
295         service.keyCache[key] = value;
296         return service.attemptHatchDelivery({
297             key : key, 
298             content : value, 
299             action : 'set',
300         });
301     }
302
303     // Set the value for the given key.
304     // "Local" items persist indefinitely.
305     // If the value is raw, pass it as 'value'.  If it was
306     // externally JSONified, pass it via jsonified.
307     service.setLocalItem = function(key, value, jsonified) {
308         if (jsonified === undefined ) 
309             jsonified = JSON.stringify(value);
310         $window.localStorage.setItem(key, jsonified);
311     }
312
313     // Set the value for the given key.  
314     // "LoginSession" items are removed when the user logs out or the 
315     // browser is closed.
316     // If the value is raw, pass it as 'value'.  If it was
317     // externally JSONified, pass it via jsonified.
318     service.setLoginSessionItem = function(key, value, jsonified) {
319         service.addLoginSessionKey(key);
320         if (jsonified === undefined ) 
321             jsonified = JSON.stringify(value);
322         $cookies.put(key, jsonified);
323     }
324
325     // Set the value for the given key.  
326     // "Session" items are browser tab-specific and are removed when the
327     // tab is closed.
328     // If the value is raw, pass it as 'value'.  If it was
329     // externally JSONified, pass it via jsonified.
330     service.setSessionItem = function(key, value, jsonified) {
331         if (jsonified === undefined ) 
332             jsonified = JSON.stringify(value);
333         $window.sessionStorage.setItem(key, jsonified);
334     }
335
336     // remove a stored item
337     service.removeItem = function(key) {
338         if (!service.useSettings())
339             return $q.when(service.removeLocalItem(key));
340
341         if (service.hatchAvailable) 
342             return service.removeRemoteItem(key);
343
344         if (service.keyIsOnCall(key)) {
345             console.warn("Unable to removeItem from Hatch: " + key + 
346                 ". Removing item from local storage instead");
347
348             return $q.when(service.removeLocalItem(key));
349         }
350
351         console.error("Unable to removeItem from Hatch: " + key);
352         return $q.reject();
353     }
354
355     service.removeRemoteItem = function(key) {
356         delete service.keyCache[key];
357         return service.attemptHatchDelivery({
358             key : key,
359             action : 'remove'
360         });
361     }
362
363     service.removeLocalItem = function(key) {
364         $window.localStorage.removeItem(key);
365     }
366
367     service.removeLoginSessionItem = function(key) {
368         service.removeLoginSessionKey(key);
369         $cookies.remove(key);
370     }
371
372     service.removeSessionItem = function(key) {
373         $window.sessionStorage.removeItem(key);
374     }
375
376     /**
377      * Remove all "LoginSession" items.
378      */
379     service.clearLoginSessionItems = function() {
380         angular.forEach(service.getLoginSessionKeys(), function(key) {
381             service.removeLoginSessionItem(key);
382         });
383
384         // remove the keys cache.
385         service.removeLocalItem('eg.hatch.login_keys');
386     }
387
388     // if set, prefix limits the return set to keys starting with 'prefix'
389     service.getKeys = function(prefix) {
390         if (service.useSettings()) 
391             return service.getRemoteKeys(prefix);
392         return $q.when(service.getLocalKeys(prefix));
393     }
394
395     service.getRemoteKeys = function(prefix) {
396         return service.attemptHatchDelivery({
397             key : prefix,
398             action : 'keys'
399         });
400     }
401
402     service.getLocalKeys = function(prefix) {
403         var keys = [];
404         var idx = 0;
405         while ( (k = $window.localStorage.key(idx++)) !== null) {
406             // key prefix match test
407             if (prefix && k.substr(0, prefix.length) != prefix) continue; 
408             keys.push(k);
409         }
410         return keys;
411     }
412
413
414     /**
415      * Array of "LoginSession" keys.
416      * Note we have to store these as "Local" items so browser tabs can
417      * share them.  We could store them as cookies, but it's more data
418      * that has to go back/forth to the server.  A "LoginSession" key name is
419      * not private, though, so it's OK if they are left in localStorage
420      * until the next login.
421      */
422     service.getLoginSessionKeys = function(prefix) {
423         var keys = [];
424         var idx = 0;
425         var login_keys = service.getLocalItem('eg.hatch.login_keys') || [];
426         angular.forEach(login_keys, function(k) {
427             // key prefix match test
428             if (prefix && k.substr(0, prefix.length) != prefix) return;
429             keys.push(k);
430         });
431         return keys;
432     }
433
434     service.addLoginSessionKey = function(key) {
435         var keys = service.getLoginSessionKeys();
436         if (keys.indexOf(key) < 0) {
437             keys.push(key);
438             service.setLocalItem('eg.hatch.login_keys', keys);
439         }
440     }
441
442     service.removeLoginSessionKey = function(key) {
443         var keys = service.getLoginSessionKeys().filter(function(k) {
444             return k != key;
445         });
446         service.setLocalItem('eg.hatch.login_keys', keys);
447     }
448
449     // Copy all stored settings from localStorage to Hatch.
450     // If 'move' is true, delete the local settings once cloned.
451     service.copySettingsToHatch = function(move) {
452         var deferred = $q.defer();
453         var keys = service.getLocalKeys();
454
455         angular.forEach(keys, function(key) {
456
457             // Hatch keys are local-only
458             if (key.match(/^eg.hatch/)) return;
459
460             console.debug("Copying to Hatch Storage: " + key);
461             service.setRemoteItem(key, service.getLocalItem(key))
462             .then(function() { // key successfully cloned.
463
464                 // delete the local copy if requested.
465                 if (move) service.removeLocalItem(key);
466
467                 // resolve the promise after processing the last key.
468                 if (key == keys[keys.length-1]) 
469                     deferred.resolve();
470             });
471         });
472
473         return deferred.promise;
474     }
475
476     // Copy all stored settings from Hatch to localStorage.
477     // If 'move' is true, delete the Hatch settings once cloned.
478     service.copySettingsToLocal = function(move) {
479         var deferred = $q.defer();
480
481         service.getRemoteKeys().then(function(keys) {
482             angular.forEach(keys, function(key) {
483                 service.getRemoteItem(key).then(function(val) {
484
485                     console.debug("Copying to Local Storage: " + key);
486                     service.setLocalItem(key, val);
487
488                     // delete the remote copy if requested.
489                     if (move) service.removeRemoteItem(key);
490
491                     // resolve the promise after processing the last key.
492                     if (key == keys[keys.length-1]) 
493                         deferred.resolve();
494                 });
495             });
496         });
497
498         return deferred.promise;
499     }
500
501     // The only requirement for opening Hatch is that the DOM be loaded.
502     // Open the connection now so its state will be immediately available.
503     service.openHatch();
504
505     return service;
506 }])
507