2 * Core Service - egHatch
4 * Dispatches print and data storage requests to the appropriate handler.
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
11 * Most handlers also provide direct remote and local variants to the
12 * application can decide to which to use as needed.
14 * Local storage requests are handled by $window.localStorage.
16 * Note that all top-level and remote requests return promises. All
17 * local requests return immediate values, since local requests are
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()
25 angular.module('egCoreMod')
28 ['$q','$window','$timeout','$interpolate','$http','$cookies',
29 function($q , $window , $timeout , $interpolate , $http , $cookies) {
33 service.messages = {};
34 service.hatchAvailable = false;
36 // key/value cache -- avoid unnecessary Hatch extension requests.
37 // Only affects *RemoteItem calls.
38 service.keyCache = {};
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.
52 service.onCallPrefixes = ['eg.workstation'];
54 // Returns true if the key can be set/get in localStorage even when
55 // Hatch is not available.
56 service.keyIsOnCall = function(key) {
58 angular.forEach(service.onCallPrefixes, function(pfx) {
59 if (key.match(new RegExp('^' + pfx)))
65 // write a message to the Hatch port
66 service.sendToHatch = function(msg) {
69 // shallow copy and scrub msg before sending
70 angular.forEach(msg, function(val, key) {
71 if (key.match(/deferred/)) return;
75 console.debug("sending to Hatch: " + JSON.stringify(msg2));
78 $window.postMessage(msg2, $window.location.origin);
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();
86 if (service.hatchAvailable) {
87 service.messages[msg.msgid] = msg;
88 service.sendToHatch(msg);
92 'Hatch request attempted but Hatch is not available');
93 msg.deferred.reject(msg);
96 return msg.deferred.promise;
100 // resolve the promise on the given request and remove
101 // it from our tracked requests.
102 service.resolveRequest = function(msg) {
104 if (!service.messages[msg.msgid]) {
105 console.error('no cached message for id = ' + msg.msgid);
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
114 if (msg.status == 200) {
115 msg.deferred.resolve(msg.content);
117 console.warn("Hatch command failed with status="
118 + msg.status + " and message=" + msg.message);
119 msg.deferred.reject();
123 service.openHatch = function() {
125 // When the Hatch extension loads, it tacks an attribute onto
126 // the page body to indicate it's available.
128 if (!$window.document.body.getAttribute('hatch-is-open')) {
129 console.debug("Hatch is not available");
133 $window.addEventListener("message", function(event) {
134 // We only accept messages from our own content script.
135 if (event.source != window) return;
137 // We only care about messages from the Hatch extension.
138 if (event.data && event.data.from == 'extension') {
140 // Avoid logging full Hatch responses. they can get large.
142 'Hatch responded to message ID ' + event.data.msgid);
144 service.resolveRequest(event.data);
148 service.hatchAvailable = true; // public flag
151 service.remotePrint = function(
152 context, contentType, content, withDialog) {
154 return service.getPrintConfig(context).then(
156 // print configuration retrieved; print
157 return service.attemptHatchDelivery({
161 contentType : contentType,
162 showDialog : withDialog,
168 service.getPrintConfig = function(context) {
169 return service.getRemoteItem('eg.print.config.' + context);
172 service.setPrintConfig = function(context, config) {
173 return service.setRemoteItem('eg.print.config.' + context, config);
176 service.getPrinterOptions = function(name) {
177 return service.attemptHatchDelivery({
178 action : 'printer-options',
183 service.getPrinters = function() {
184 if (service.printers) // cached printers
185 return $q.when(service.printers);
187 return service.attemptHatchDelivery({action : 'printers'}).then(
189 // we have remote printers; sort by name and return
191 service.printers = printers.sort(
192 function(a,b) {return a.name < b.name ? -1 : 1});
193 return service.printers;
196 // remote call failed and there is no such thing as local
197 // printers; return empty set.
198 function() { return [] }
202 service.usePrinting = function() {
203 return service.getLocalItem('eg.hatch.enable.printing');
206 service.useSettings = function() {
207 return service.getLocalItem('eg.hatch.enable.settings');
210 service.useOffline = function() {
211 return service.getLocalItem('eg.hatch.enable.offline');
214 // get the value for a stored item
215 service.getItem = function(key) {
217 if (!service.useSettings())
218 return $q.when(service.getLocalItem(key));
220 if (service.hatchAvailable)
221 return service.getRemoteItem(key);
223 if (service.keyIsOnCall(key)) {
224 console.warn("Unable to getItem from Hatch: " + key +
225 ". Retrieving item from local storage instead");
227 return $q.when(service.getLocalItem(key));
230 console.error("Unable to getItem from Hatch: " + key);
234 service.getRemoteItem = function(key) {
236 if (service.keyCache[key] != undefined)
237 return $q.when(service.keyCache[key])
239 return service.attemptHatchDelivery({
242 }).then(function(content) {
243 return service.keyCache[key] = content;
247 service.getLocalItem = function(key) {
248 var val = $window.localStorage.getItem(key);
249 if (val == null) return;
251 return JSON.parse(val);
254 "Deleting invalid JSON for localItem: " + key + " => " + val);
255 service.removeLocalItem(key);
260 service.getLoginSessionItem = function(key) {
261 var val = $cookies.get(key);
262 if (val == null) return;
263 return JSON.parse(val);
266 service.getSessionItem = function(key) {
267 var val = $window.sessionStorage.getItem(key);
268 if (val == null) return;
269 return JSON.parse(val);
273 * @param tmp bool Store the value as a session cookie only.
274 * tmp values are removed during logout or browser close.
276 service.setItem = function(key, value) {
277 if (service.useSettings())
278 return $q.when(service.setLocalItem(key, value));
280 if (service.hatchAvailable)
281 return service.setRemoteItem(key, value);
283 if (service.keyIsOnCall(key)) {
284 console.warn("Unable to setItem in Hatch: " +
285 key + ". Setting in local storage instead");
287 return $q.when(service.setLocalItem(key, value));
290 console.error("Unable to setItem in Hatch: " + key);
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({
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);
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);
326 // Set the value for the given key.
327 // "Session" items are browser tab-specific and are removed when the
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);
337 // remove a stored item
338 service.removeItem = function(key) {
339 if (!service.useSettings())
340 return $q.when(service.removeLocalItem(key));
342 if (service.hatchAvailable)
343 return service.removeRemoteItem(key);
345 if (service.keyIsOnCall(key)) {
346 console.warn("Unable to removeItem from Hatch: " + key +
347 ". Removing item from local storage instead");
349 return $q.when(service.removeLocalItem(key));
352 console.error("Unable to removeItem from Hatch: " + key);
356 service.removeRemoteItem = function(key) {
357 delete service.keyCache[key];
358 return service.attemptHatchDelivery({
364 service.removeLocalItem = function(key) {
365 $window.localStorage.removeItem(key);
368 service.removeLoginSessionItem = function(key) {
369 service.removeLoginSessionKey(key);
370 $cookies.remove(key);
373 service.removeSessionItem = function(key) {
374 $window.sessionStorage.removeItem(key);
378 * Remove all "LoginSession" items.
380 service.clearLoginSessionItems = function() {
381 angular.forEach(service.getLoginSessionKeys(), function(key) {
382 service.removeLoginSessionItem(key);
385 // remove the keys cache.
386 service.removeLocalItem('eg.hatch.login_keys');
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));
396 service.getRemoteKeys = function(prefix) {
397 return service.attemptHatchDelivery({
403 service.getLocalKeys = function(prefix) {
406 while ( (k = $window.localStorage.key(idx++)) !== null) {
407 // key prefix match test
408 if (prefix && k.substr(0, prefix.length) != prefix) continue;
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.
423 service.getLoginSessionKeys = function(prefix) {
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;
435 service.addLoginSessionKey = function(key) {
436 var keys = service.getLoginSessionKeys();
437 if (keys.indexOf(key) < 0) {
439 service.setLocalItem('eg.hatch.login_keys', keys);
443 service.removeLoginSessionKey = function(key) {
444 var keys = service.getLoginSessionKeys().filter(function(k) {
447 service.setLocalItem('eg.hatch.login_keys', keys);
450 // The only requirement for opening Hatch is that the DOM be loaded.
451 // Open the connection now so its state will be immediately available.