]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/hatch.js
LP#1646166 Hatch settings migration
[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 page body to indicate it's available.
127
128         if (!$window.document.body.getAttribute('hatch-is-open')) {
129             console.debug("Hatch is not available");
130             return;
131         }
132
133         $window.addEventListener("message", function(event) {
134             // We only accept messages from our own content script.
135             if (event.source != window) return;
136
137             // We only care about messages from the Hatch extension.
138             if (event.data && event.data.from == 'extension') {
139
140                 // Avoid logging full Hatch responses. they can get large.
141                 console.debug(
142                     'Hatch responded to message ID ' + event.data.msgid);
143
144                 service.resolveRequest(event.data);
145             }
146         }); 
147
148         service.hatchAvailable = true; // public flag
149     }
150
151     service.remotePrint = function(
152         context, contentType, content, withDialog) {
153
154         return service.getPrintConfig(context).then(
155             function(config) {
156                 // print configuration retrieved; print
157                 return service.attemptHatchDelivery({
158                     action : 'print',
159                     settings : config,
160                     content : content, 
161                     contentType : contentType,
162                     showDialog : withDialog,
163                 });
164             }
165         );
166     }
167
168     service.getPrintConfig = function(context) {
169         return service.getRemoteItem('eg.print.config.' + context);
170     }
171
172     service.setPrintConfig = function(context, config) {
173         return service.setRemoteItem('eg.print.config.' + context, config);
174     }
175
176     service.getPrinterOptions = function(name) {
177         return service.attemptHatchDelivery({
178             action : 'printer-options',
179             printer : name
180         });
181     }
182
183     service.getPrinters = function() {
184         if (service.printers) // cached printers
185             return $q.when(service.printers);
186
187         return service.attemptHatchDelivery({action : 'printers'}).then(
188
189             // we have remote printers; sort by name and return
190             function(printers) {
191                 service.printers = printers.sort(
192                     function(a,b) {return a.name < b.name ? -1 : 1});
193                 return service.printers;
194             },
195
196             // remote call failed and there is no such thing as local
197             // printers; return empty set.
198             function() { return [] } 
199         );
200     }
201
202     service.usePrinting = function() {
203         return service.getLocalItem('eg.hatch.enable.printing');
204     }
205
206     service.useSettings = function() {
207         return service.getLocalItem('eg.hatch.enable.settings');
208     }
209
210     service.useOffline = function() {
211         return service.getLocalItem('eg.hatch.enable.offline');
212     }
213
214     // get the value for a stored item
215     service.getItem = function(key) {
216
217         if (!service.useSettings())
218             return $q.when(service.getLocalItem(key));
219
220         if (service.hatchAvailable) 
221             return service.getRemoteItem(key);
222
223         if (service.keyIsOnCall(key)) {
224             console.warn("Unable to getItem from Hatch: " + key + 
225                 ". Retrieving item from local storage instead");
226
227             return $q.when(service.getLocalItem(key));
228         }
229
230         console.error("Unable to getItem from Hatch: " + key);
231         return $q.reject();
232     }
233
234     service.getRemoteItem = function(key) {
235         
236         if (service.keyCache[key] != undefined)
237             return $q.when(service.keyCache[key])
238
239         return service.attemptHatchDelivery({
240             key : key,
241             action : 'get'
242         }).then(function(content) {
243             return service.keyCache[key] = content;
244         });
245     }
246
247     service.getLocalItem = function(key) {
248         var val = $window.localStorage.getItem(key);
249         if (val == null) return;
250         try {
251             return JSON.parse(val);
252         } catch(E) {
253             console.error(
254                 "Deleting invalid JSON for localItem: " + key + " => " + val);
255             service.removeLocalItem(key);
256             return null;
257         }
258     }
259
260     service.getLoginSessionItem = function(key) {
261         var val = $cookies.get(key);
262         if (val == null) return;
263         return JSON.parse(val);
264     }
265
266     service.getSessionItem = function(key) {
267         var val = $window.sessionStorage.getItem(key);
268         if (val == null) return;
269         return JSON.parse(val);
270     }
271
272     /**
273      * @param tmp bool Store the value as a session cookie only.  
274      * tmp values are removed during logout or browser close.
275      */
276     service.setItem = function(key, value) {
277         if (!service.useSettings())
278             return $q.when(service.setLocalItem(key, value));
279
280         if (service.hatchAvailable)
281             return service.setRemoteItem(key, value);
282
283         if (service.keyIsOnCall(key)) {
284             console.warn("Unable to setItem in Hatch: " + 
285                 key + ". Setting in local storage instead");
286
287             return $q.when(service.setLocalItem(key, value));
288         }
289
290         console.error("Unable to setItem in Hatch: " + key);
291         return $q.reject();
292     }
293
294     // set the value for a stored or new item
295     service.setRemoteItem = function(key, value) {
296         service.keyCache[key] = value;
297         return service.attemptHatchDelivery({
298             key : key, 
299             content : value, 
300             action : 'set',
301         });
302     }
303
304     // Set the value for the given key.
305     // "Local" items persist indefinitely.
306     // If the value is raw, pass it as 'value'.  If it was
307     // externally JSONified, pass it via jsonified.
308     service.setLocalItem = function(key, value, jsonified) {
309         if (jsonified === undefined ) 
310             jsonified = JSON.stringify(value);
311         $window.localStorage.setItem(key, jsonified);
312     }
313
314     // Set the value for the given key.  
315     // "LoginSession" items are removed when the user logs out or the 
316     // browser is closed.
317     // If the value is raw, pass it as 'value'.  If it was
318     // externally JSONified, pass it via jsonified.
319     service.setLoginSessionItem = function(key, value, jsonified) {
320         service.addLoginSessionKey(key);
321         if (jsonified === undefined ) 
322             jsonified = JSON.stringify(value);
323         $cookies.put(key, jsonified);
324     }
325
326     // Set the value for the given key.  
327     // "Session" items are browser tab-specific and are removed when the
328     // tab is closed.
329     // If the value is raw, pass it as 'value'.  If it was
330     // externally JSONified, pass it via jsonified.
331     service.setSessionItem = function(key, value, jsonified) {
332         if (jsonified === undefined ) 
333             jsonified = JSON.stringify(value);
334         $window.sessionStorage.setItem(key, jsonified);
335     }
336
337     // remove a stored item
338     service.removeItem = function(key) {
339         if (!service.useSettings())
340             return $q.when(service.removeLocalItem(key));
341
342         if (service.hatchAvailable) 
343             return service.removeRemoteItem(key);
344
345         if (service.keyIsOnCall(key)) {
346             console.warn("Unable to removeItem from Hatch: " + key + 
347                 ". Removing item from local storage instead");
348
349             return $q.when(service.removeLocalItem(key));
350         }
351
352         console.error("Unable to removeItem from Hatch: " + key);
353         return $q.reject();
354     }
355
356     service.removeRemoteItem = function(key) {
357         delete service.keyCache[key];
358         return service.attemptHatchDelivery({
359             key : key,
360             action : 'remove'
361         });
362     }
363
364     service.removeLocalItem = function(key) {
365         $window.localStorage.removeItem(key);
366     }
367
368     service.removeLoginSessionItem = function(key) {
369         service.removeLoginSessionKey(key);
370         $cookies.remove(key);
371     }
372
373     service.removeSessionItem = function(key) {
374         $window.sessionStorage.removeItem(key);
375     }
376
377     /**
378      * Remove all "LoginSession" items.
379      */
380     service.clearLoginSessionItems = function() {
381         angular.forEach(service.getLoginSessionKeys(), function(key) {
382             service.removeLoginSessionItem(key);
383         });
384
385         // remove the keys cache.
386         service.removeLocalItem('eg.hatch.login_keys');
387     }
388
389     // if set, prefix limits the return set to keys starting with 'prefix'
390     service.getKeys = function(prefix) {
391         if (service.useSettings()) 
392             return service.getRemoteKeys(prefix);
393         return $q.when(service.getLocalKeys(prefix));
394     }
395
396     service.getRemoteKeys = function(prefix) {
397         return service.attemptHatchDelivery({
398             key : prefix,
399             action : 'keys'
400         });
401     }
402
403     service.getLocalKeys = function(prefix) {
404         var keys = [];
405         var idx = 0;
406         while ( (k = $window.localStorage.key(idx++)) !== null) {
407             // key prefix match test
408             if (prefix && k.substr(0, prefix.length) != prefix) continue; 
409             keys.push(k);
410         }
411         return keys;
412     }
413
414
415     /**
416      * Array of "LoginSession" keys.
417      * Note we have to store these as "Local" items so browser tabs can
418      * share them.  We could store them as cookies, but it's more data
419      * that has to go back/forth to the server.  A "LoginSession" key name is
420      * not private, though, so it's OK if they are left in localStorage
421      * until the next login.
422      */
423     service.getLoginSessionKeys = function(prefix) {
424         var keys = [];
425         var idx = 0;
426         var login_keys = service.getLocalItem('eg.hatch.login_keys') || [];
427         angular.forEach(login_keys, function(k) {
428             // key prefix match test
429             if (prefix && k.substr(0, prefix.length) != prefix) return;
430             keys.push(k);
431         });
432         return keys;
433     }
434
435     service.addLoginSessionKey = function(key) {
436         var keys = service.getLoginSessionKeys();
437         if (keys.indexOf(key) < 0) {
438             keys.push(key);
439             service.setLocalItem('eg.hatch.login_keys', keys);
440         }
441     }
442
443     service.removeLoginSessionKey = function(key) {
444         var keys = service.getLoginSessionKeys().filter(function(k) {
445             return k != key;
446         });
447         service.setLocalItem('eg.hatch.login_keys', keys);
448     }
449
450     // Copy all stored settings from localStorage to Hatch.
451     // If 'move' is true, delete the local settings once cloned.
452     service.copySettingsToHatch = function(move) {
453         var deferred = $q.defer();
454         var keys = service.getLocalKeys();
455
456         angular.forEach(keys, function(key) {
457
458             // Hatch keys are local-only
459             if (key.match(/^eg.hatch/)) return;
460
461             console.debug("Copying to Hatch Storage: " + key);
462             service.setRemoteItem(key, service.getLocalItem(key))
463             .then(function() { // key successfully cloned.
464
465                 // delete the local copy if requested.
466                 if (move) service.removeLocalItem(key);
467
468                 // resolve the promise after processing the last key.
469                 if (key == keys[keys.length-1]) 
470                     deferred.resolve();
471             });
472         });
473
474         return deferred.promise;
475     }
476
477     // Copy all stored settings from Hatch to localStorage.
478     // If 'move' is true, delete the Hatch settings once cloned.
479     service.copySettingsToLocal = function(move) {
480         var deferred = $q.defer();
481
482         service.getRemoteKeys().then(function(keys) {
483             angular.forEach(keys, function(key) {
484                 service.getRemoteItem(key).then(function(val) {
485
486                     console.debug("Copying to Local Storage: " + key);
487                     service.setLocalItem(key, val);
488
489                     // delete the remote copy if requested.
490                     if (move) service.removeRemoteItem(key);
491
492                     // resolve the promise after processing the last key.
493                     if (key == keys[keys.length-1]) 
494                         deferred.resolve();
495                 });
496             });
497         });
498
499         return deferred.promise;
500     }
501
502     // The only requirement for opening Hatch is that the DOM be loaded.
503     // Open the connection now so its state will be immediately available.
504     service.openHatch();
505
506     return service;
507 }])
508