forked from kfiroo/react-native-cached-image
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageCacheProvider.js
More file actions
363 lines (326 loc) · 10.4 KB
/
ImageCacheProvider.js
File metadata and controls
363 lines (326 loc) · 10.4 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
'use strict';
const _ = require('lodash');
const RNFetchBlob = require('react-native-fetch-blob').default;
const {
fs
} = RNFetchBlob;
const LOCATION = {
CACHE: fs.dirs.CacheDir + '/imagesCacheDir',
BUNDLE: fs.dirs.MainBundleDir + '/imagesCacheDir'
};
const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');
const defaultHeaders = {};
const defaultImageTypes = ['png', 'jpeg', 'jpg', 'gif', 'bmp', 'tiff', 'tif'];
const defaultResolveHeaders = _.constant(defaultHeaders);
const defaultOptions = {
useQueryParamsInCacheKey: false,
cacheLocation: LOCATION.CACHE
};
const activeDownloads = {};
function serializeObjectKeys(obj) {
return _(obj)
.toPairs()
.sortBy(a => a[0])
.map(a => a[1])
.value();
}
function getQueryForCacheKey(url, useQueryParamsInCacheKey) {
if (_.isArray(useQueryParamsInCacheKey)) {
return serializeObjectKeys(_.pick(url.query, useQueryParamsInCacheKey));
}
if (useQueryParamsInCacheKey) {
return serializeObjectKeys(url.query);
}
return '';
}
function generateCacheKey(url, options) {
const parsedUrl = new URL(url, null, true);
const pathParts = parsedUrl.pathname.split('/');
// last path part is the file name
const fileName = pathParts.pop();
const filePath = pathParts.join('/');
const parts = fileName.split('.');
const fileType = parts.length > 1 ? _.toLower(parts.pop()) : '';
const type = defaultImageTypes.includes(fileType) ? fileType : 'jpg';
const cacheable = filePath + fileName + type + getQueryForCacheKey(parsedUrl, options.useQueryParamsInCacheKey);
return SHA1(cacheable) + '.' + type;
}
function getBaseDir(cacheLocation) {
return cacheLocation || LOCATION.CACHE;
}
function getCachePath(url, options) {
if (options.cacheGroup) {
return options.cacheGroup;
}
const {
host
} = new URL(url);
return host.replace(/[^a-z0-9]/gi, '').toLowerCase();
}
function getCachedImageFilePath(url, options) {
const cachePath = getCachePath(url, options);
const cacheKey = generateCacheKey(url, options);
return `${getBaseDir(options.cacheLocation)}/${cachePath}/${cacheKey}`;
}
function deleteFile(filePath) {
return fs.stat(filePath)
.then(res => res && res.type === 'file')
.then(exists => exists && fs.unlink(filePath))
.catch((err) => {
// swallow error to always resolve
});
}
function getDirPath(filePath) {
return _.initial(filePath.split('/')).join('/');
}
function ensurePath(dirPath) {
return fs.isDir(dirPath)
.then(isDir => {
if (!isDir) {
return fs.mkdir(dirPath)
.then(() => fs.exists(dirPath).then(exists => {
// Check if dir has indeed been created because
// there's no exception on incorrect user-defined paths (?)...
if (!exists) throw new Error('Invalid cacheLocation');
}))
}
})
.catch(err => {
// swallow folder already exists errors
if (err.message.includes('folder already exists')) {
return;
}
throw err;
});
}
/**
* returns a promise that is resolved when the download of the requested file
* is complete and the file is saved.
* if the download fails, or was stopped the partial file is deleted, and the
* promise is rejected
* @param fromUrl String source url
* @param toFile String destination path
* @param headers Object headers to use when downloading the file
* @returns {Promise}
*/
function downloadImage(fromUrl, toFile, headers = {}) {
// use toFile as the key as is was created using the cacheKey
if (!_.has(activeDownloads, toFile)) {
//Using a temporary file, if the download is accidentally interrupted, it will not produce a disabled file
const tmpFile = toFile + '.tmp';
// create an active download for this file
activeDownloads[toFile] = new Promise((resolve, reject) => {
RNFetchBlob
.config({path: tmpFile})
.fetch('GET', fromUrl, headers)
.then(res => {
if (Math.floor(res.respInfo.status / 100) !== 2) {
throw new Error('Failed to successfully download image');
}
//The download is complete and rename the temporary file
return fs.mv(tmpFile, toFile);
})
.then(() => resolve(toFile))
.catch(err => {
return deleteFile(tmpFile)
.then(() => reject(err));
})
.finally(() => {
// cleanup
delete activeDownloads[toFile];
});
});
}
return activeDownloads[toFile];
}
function createPrefetcer(list) {
const urls = _.clone(list);
return {
next() {
return urls.shift();
}
};
}
function runPrefetchTask(prefetcher, options) {
const url = prefetcher.next();
if (!url) {
return Promise.resolve();
}
// if url is cacheable - cache it
if (isCacheable(url)) {
// check cache
return getCachedImagePath(url, options)
// if not found download
.catch(() => cacheImage(url, options))
// allow prefetch task to fail without terminating other prefetch tasks
.catch(_.noop)
// then run next task
.then(() => runPrefetchTask(prefetcher, options));
}
// else get next
return runPrefetchTask(prefetcher, options);
}
function collectFilesInfo(basePath) {
return fs.stat(basePath)
.then((info) => {
if (info.type === 'file') {
return [info];
}
return fs.ls(basePath)
.then(files => {
const promises = _.map(files, file => {
return collectFilesInfo(`${basePath}/${file}`);
});
return Promise.all(promises);
});
})
.catch(err => {
return [];
});
}
// API
/**
* Check whether a url is cacheable.
* Takes an image source and if it's a valid url return `true`
* @param url
* @returns {boolean}
*/
function isCacheable(url) {
return _.isString(url) && (_.startsWith(url.toLowerCase(), 'http://') || _.startsWith(url.toLowerCase(), 'https://'));
}
/**
* Get the local path corresponding to the given url and options.
* @param url
* @param options
* @returns {Promise.<String>}
*/
function getCachedImagePath(url, options = defaultOptions) {
const filePath = getCachedImageFilePath(url, options);
return fs.stat(filePath)
.then(res => {
if (res.type !== 'file') {
// reject the promise if res is not a file
throw new Error('Failed to get image from cache');
}
if (!res.size) {
// something went wrong with the download, file size is 0, remove it
return deleteFile(filePath)
.then(() => {
throw new Error('Failed to get image from cache');
});
}
return filePath;
})
.catch(err => {
throw err;
})
}
/**
* Download the image to the cache and return the local file path.
* @param url
* @param options
* @param resolveHeaders
* @returns {Promise.<String>}
*/
function cacheImage(url, options = defaultOptions, resolveHeaders = defaultResolveHeaders) {
const filePath = getCachedImageFilePath(url, options);
const dirPath = getDirPath(filePath);
return ensurePath(dirPath)
.then(() => resolveHeaders())
.then(headers => downloadImage(url, filePath, headers));
}
/**
* Delete the cached image corresponding to the given url and options.
* @param url
* @param options
* @returns {Promise}
*/
function deleteCachedImage(url, options = defaultOptions) {
const filePath = getCachedImageFilePath(url, options);
return deleteFile(filePath);
}
/**
* Cache an array of urls.
* Usually used to prefetch images.
* @param urls
* @param options
* @returns {Promise}
*/
function cacheMultipleImages(urls, options = defaultOptions) {
const prefetcher = createPrefetcer(urls);
const numberOfWorkers = urls.length;
const promises = _.times(numberOfWorkers, () =>
runPrefetchTask(prefetcher, options)
);
return Promise.all(promises);
}
/**
* Delete an array of cached images by their urls.
* Usually used to clear the prefetched images.
* @param urls
* @param options
* @returns {Promise}
*/
function deleteMultipleCachedImages(urls, options = defaultOptions) {
return _.reduce(urls, (p, url) =>
p.then(() => deleteCachedImage(url, options)),
Promise.resolve()
);
}
/**
* Seed the cache of a specified url with a local image
* Handy if you have a local copy of a remote image, e.g. you just uploaded local to url.
* @param local
* @param url
* @param options
* @returns {Promise}
*/
function seedCache(local, url, options = defaultOptions) {
const filePath = getCachedImageFilePath(url, options);
const dirPath = getDirPath(filePath);
return ensurePath(dirPath)
.then(() => fs.cp(local, filePath))
}
/**
* Clear the entire cache.
* @param options
* @returns {Promise}
*/
function clearCache(options = defaultOptions) {
return fs.unlink(getBaseDir(options.cacheLocation))
.catch(() => {
// swallow exceptions if path doesn't exist
})
.then(() => ensurePath(getBaseDir(options.cacheLocation)));
}
/**
* Return info about the cache, list of files and the total size of the cache.
* @param options
* @returns {Promise.<{size}>}
*/
function getCacheInfo(options = defaultOptions) {
return ensurePath(getBaseDir(options.cacheLocation))
.then(() => collectFilesInfo(getBaseDir(options.cacheLocation)))
.then(cache => {
const files = _.flattenDeep(cache);
const size = _.sumBy(files, 'size');
return {
files,
size
};
});
}
module.exports = {
isCacheable,
getCachedImageFilePath,
getCachedImagePath,
cacheImage,
deleteCachedImage,
cacheMultipleImages,
deleteMultipleCachedImages,
clearCache,
seedCache,
getCacheInfo,
LOCATION
};