-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
100 lines (87 loc) · 3 KB
/
index.js
File metadata and controls
100 lines (87 loc) · 3 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
import PropTypes from 'prop-types';
import React from 'react';
import RNFS, { DocumentDirectoryPath, CachesDirectoryPath, MainBundlePath } from 'react-native-fs';
const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');
function deleteCache(filePath) {
RNFS
.exists(filePath)
.then((res) => {
if (res) {
RNFS
.unlink(filePath)
.catch((err) => {});
}
});
}
function processSource(source) {
if (source !== null && source != '') {
const url = new URL(source, null, true);
let cacheable = source;
const type = url.pathname.replace(/.*\.(.*)/, '$1');
let ext;
if (type === '/') {
if (source.match('.png')) {
ext = '.png';
} else if (source.match('.jpg')) {
ext = '.jpg';
} else if (source.match('.jpeg')) {
ext = '.jpeg';
}
}
let cacheKey;
if (ext) {
cacheKey = `${SHA1(cacheable)}${ext}`;
} else {
cacheKey = SHA1(cacheable) + (type.length < url.pathname.length ? '.' + type : '');
}
cacheable = cacheable.concat(url.query);
return checkImageCache(source, url.host, cacheKey);
}
return Promise.reject('No source');
}
function checkImageCache(imageUri, cachePath, cacheKey) {
const dirPath = `${CachesDirectoryPath}/${cachePath}`;
const filePath = `${dirPath}/${cacheKey}`;
return RNFS
.stat(filePath)
.then((res) => {
if (res.isFile() && res.size > 0) {
return filePath;
} else {
throw Error("Invalid file");
}
})
.catch((err) => {
return RNFS
.mkdir(dirPath, { NSURLIsExcludedFromBackupKey: true })
.then(() => {
let downloadOptions = {
fromUrl: imageUri,
toFile: filePath,
background: true
};
let download = RNFS.downloadFile(downloadOptions);
return download.promise
.then((res) => {
switch (res.statusCode) {
case 404:
case 403:
return Promise.reject();
break;
default:
return filePath;
}
})
.catch((err) => {
deleteCache(filePath);
return Promise.reject(`Err downloading image ${err}`);
});
})
.catch((err) => {
deleteCache(filePath);
return Promise.reject(`Err mkdir ${err}`);
});
});
}
export default { deleteCache, processSource };