-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular-xhr-src.js
292 lines (237 loc) · 7 KB
/
angular-xhr-src.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/* global window, chrome */
(function(global, debug) {
'use strict';
var debugRequestTimeSpanFirst,
debugRequestTimeSpanLast,
debugItemCount;
function xhrSrc($http, $window, xhrSrcCacheService) {
var directive = {
restrict: 'A',
scope: true,
template: '',
replace: true,
link: linkFunction
};
return directive;
function linkFunction(scope, element, attrs) {
var elt = element[0];
attrs.$observe('xhrSrc', sourceAttributeObserver);
attrs.$observe('xhrHref', sourceAttributeObserver);
function sourceAttributeObserver(source) {
if (source !== undefined) {
// as chrome.storage deals with primitive types and not blobs, only cache
// in local cache hash object
xhrSrcCacheService.retrieveFileCacheHash(source, function(cachedFileObject) {
if (cachedFileObject !== undefined) {
// cache hit, use it
debugLog('found in the cache');
elementAssignResource(elt, $window.URL.createObjectURL(cachedFileObject));
updateDebug();
return;
}
else {
// not a cache hit, request it
debugLog('NOT found in the cache, retrieving from XHR');
$http.get(source, {responseType: 'blob'})
.then(
function(response) {
// received response, use it
elementAssignResource(elt, $window.URL.createObjectURL(response.data));
// and cache it
xhrSrcCacheService.storeFileCacheHash(source, response.data);
updateDebug();
},
logXHRError
);
}
});
}
}
}
}
function xhrArrayBufferSrc($http, xhrSrcCacheService) {
var directive = {
restrict: 'A',
scope: true,
template: '',
replace: true,
link: linkFunction
};
return directive;
function linkFunction(scope, element, attrs) {
var elt = element[0];
attrs.$observe('xhrArrayBufferSrc', sourceAttributeObserver);
attrs.$observe('xhrArrayBufferHref', sourceAttributeObserver);
function sourceAttributeObserver(source) {
if (source !== undefined) {
xhrSrcCacheService.retrieve(source, function(cachedFileObject) {
if (cachedFileObject !== undefined) {
// cache hit, use it
debugLog('found in the cache');
elementAssignResource(elt, cachedFileObject);
updateDebug();
return;
}
else {
debugLog('NOT found in the cache, retrieving from XHR');
$http.get(source, {responseType: 'arraybuffer'})
.then(
function(response) {
var base64 = getBase64Content(response.data),
dataUrl = getDataUrl(source, elt.tagName, base64);
elementAssignResource(elt, dataUrl);
// received response, cache it
xhrSrcCacheService.store(source, dataUrl);
updateDebug();
},
logXHRError
);
}
});
}
}
}
function getBase64Content(responseData) {
var uInt8Array = new Uint8Array(responseData);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--)
{
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
return window.btoa(data);
}
function getDataUrl(source, tagName, base64Content) {
var lowercaseSource = source.toLowerCase(),
imageType;
if (tagName === 'LINK' && lowercaseSource.indexOf('.css')) {
return 'data:text/css;base64,' + base64Content;
}
else if (tagName === 'IMG') {
if (lowercaseSource.indexOf('.jpg') !== -1) {
imageType = 'image/jpg';
}
else if (lowercaseSource.indexOf('.gif') !== -1) {
imageType = 'image/gif';
}
else {
imageType = 'image/png';
}
return 'data:' + imageType + ';base64,' + base64Content;
}
return '';
}
}
function elementAssignResource(element, resource) {
if (element.tagName === 'LINK') {
element.href = resource;
}
else if (element.tagName === 'IMG') {
element.src = resource;
}
else {
throw new Error('xhrSrc directive only supports setting LINK href and IMG src');
}
}
function logXHRError(result) {
var resource = result.config.url;
var data = typeof(result.data) === "object" ? JSON.stringify(result.data) : result.data;
var resultMessage = 'status code: ' + result.status + ' status: ' + result.statusText + ' data: ' + data;
throw new Error('Result retrieving resource ' + resource + ': ' + resultMessage);
}
/*******************************************************/
function xhrSrcCacheService() {
var service = {
'store': store,
'retrieve': retrieve,
'storeFileCacheHash': storeFileCacheHash,
'retrieveFileCacheHash': retrieveFileCacheHash
},
fileCache = {};
return service;
function useChromeStorage() {
return chrome !== undefined &&
chrome.storage !== undefined &&
chrome.storage.local !== undefined;
}
function store(key, fileObject) {
if (useChromeStorage()) {
storeChromeStorage(key, fileObject);
}
else {
storeFileCacheHash(key, fileObject);
}
}
function storeFileCacheHash(key, fileObject) {
fileCache[key] = fileObject;
}
function storeChromeStorage(key, fileObject) {
var valueToSet = {};
valueToSet[key] = fileObject;
chrome.storage.local.set(valueToSet, function () {
if (chrome.runtime.lastError !== undefined) {
throw new Error('Error caching file object results: ' + chrome.runtime.lastError.message);
}
});
}
function retrieve(key, callback) {
if (useChromeStorage()) {
retrieveChromeStorage(key, callback);
}
else {
retrieveFileCacheHash(key, callback);
}
}
function retrieveFileCacheHash(key, callback) {
callback(fileCache[key]);
}
function retrieveChromeStorage(key, callback) {
chrome.storage.local.get(key, function(items) {
callback(items[key]);
});
}
}
/*******************************************************/
// Debug helpers
if (debug) {
// put on global scope so we can get time from console
global.xhrSrcShowTime = function() {
console.log((debugRequestTimeSpanLast - debugRequestTimeSpanFirst) / 1000);
debugItemCount = 0;
debugRequestTimeSpanFirst = debugRequestTimeSpanLast = undefined;
};
}
function updateDebug() {
if (debug) {
if (debugItemCount === undefined) {
debugItemCount = 0;
}
if (debugItemCount === 0) {
debugRequestTimeSpanFirst = debugRequestTimeSpanLast = +(new Date());
debugItemCount++;
}
else {
debugRequestTimeSpanLast = +(new Date());
debugItemCount++;
}
}
}
function debugLog(message) {
if (debug) {
console.log(message);
}
}
/*******************************************************/
// Angular registrations
angular.module('xhrSrc', []);
angular.module('xhrSrc')
.factory('xhrSrcCacheService', xhrSrcCacheService)
.directive('xhrSrc', xhrSrc)
.directive('xhrHref', xhrSrc);
angular.module('xhrArrayBufferSrc', []);
angular.module('xhrArrayBufferSrc')
.factory('xhrSrcCacheService', xhrSrcCacheService)
.directive('xhrArrayBufferSrc', xhrArrayBufferSrc)
.directive('xhrArrayBufferHref', xhrArrayBufferSrc);
})(window, false);