forked from jayesbe/react-native-cacheable-image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.js
314 lines (268 loc) · 10.5 KB
/
image.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import React from 'react';
import PropTypes from 'prop-types';
import { Image, ActivityIndicator, NetInfo, Platform } from 'react-native';
import RNFS, { DocumentDirectoryPath } from 'react-native-fs';
import ResponsiveImage from 'react-native-responsive-image';
const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');
export default
class CacheableImage extends React.Component {
constructor(props) {
super(props)
this.imageDownloadBegin = this.imageDownloadBegin.bind(this);
this.imageDownloadProgress = this.imageDownloadProgress.bind(this);
this._handleConnectivityChange = this._handleConnectivityChange.bind(this);
this._stopDownload = this._stopDownload.bind(this);
this.state = {
isRemote: false,
cachedImagePath: null,
cacheable: true
};
this.networkAvailable = props.networkAvailable;
this.downloading = false;
this.jobId = null;
};
componentWillReceiveProps(nextProps) {
if (nextProps.source != this.props.source || nextProps.networkAvailable != this.networkAvailable) {
this.networkAvailable = nextProps.networkAvailable;
this._processSource(nextProps.source);
}
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState === this.state && nextProps === this.props) {
return false;
}
return true;
}
async imageDownloadBegin(info) {
switch (info.statusCode) {
case 404:
case 403:
break;
default:
this.downloading = true;
this.jobId = info.jobId;
}
}
async imageDownloadProgress(info) {
if ((info.contentLength / info.bytesWritten) == 1) {
this.downloading = false;
this.jobId = null;
}
}
async checkImageCache(imageUri, cachePath, cacheKey) {
const dirPath = DocumentDirectoryPath+'/'+cachePath;
const filePath = dirPath+'/'+cacheKey;
RNFS
.stat(filePath)
.then((res) => {
if (res.isFile() && res.size > 0) {
// It's possible the component has already unmounted before setState could be called.
// It happens when the defaultSource and source have both been cached.
// An attempt is made to display the default however it's instantly removed since source is available
// means file exists, ie, cache-hit
this.setState({cacheable: true, cachedImagePath: filePath});
}
else {
throw Error("CacheableImage: Invalid file in checkImageCache()");
}
})
.catch((err) => {
// means file does not exist
// first make sure network is available..
// if (! this.state.networkAvailable) {
if (! this.networkAvailable) {
return;
}
// then make sure directory exists.. then begin download
// The NSURLIsExcludedFromBackupKey property can be provided to set this attribute on iOS platforms.
// Apple will reject apps for storing offline cache data that does not have this attribute.
// https://github.com/johanneslumpe/react-native-fs#mkdirfilepath-string-options-mkdiroptions-promisevoid
RNFS
.mkdir(dirPath, {NSURLIsExcludedFromBackupKey: true})
.then(() => {
// before we change the cachedImagePath.. if the previous cachedImagePath was set.. remove it
if (this.state.cacheable && this.state.cachedImagePath) {
let delImagePath = this.state.cachedImagePath;
this._deleteFilePath(delImagePath);
}
// If already downloading, cancel the job
if (this.jobId) {
this._stopDownload();
}
let downloadOptions = {
fromUrl: imageUri,
toFile: filePath,
background: this.props.downloadInBackground,
begin: this.imageDownloadBegin,
progress: this.imageDownloadProgress
};
// directory exists.. begin download
let download = RNFS
.downloadFile(downloadOptions);
this.downloading = true;
this.jobId = download.jobId;
download.promise
.then((res) => {
this.downloading = false;
this.jobId = null;
switch (res.statusCode) {
case 404:
case 403:
this.setState({cacheable: false, cachedImagePath: null});
break;
default:
this.setState({cacheable: true, cachedImagePath: filePath});
}
})
.catch((err) => {
// error occurred while downloading or download stopped.. remove file if created
this._deleteFilePath(filePath);
// If there was no in-progress job, it may have been cancelled already (and this component may be unmounted)
if (this.downloading) {
this.downloading = false;
this.jobId = null;
this.setState({cacheable: false, cachedImagePath: null});
}
});
})
.catch((err) => {
this._deleteFilePath(filePath);
this.setState({cacheable: false, cachedImagePath: null});
});
});
}
_deleteFilePath(filePath) {
RNFS
.exists(filePath)
.then((res) => {
if (res) {
RNFS
.unlink(filePath)
.catch((err) => {});
}
});
}
_processSource(source, skipSourceCheck) {
if (source !== null
&& source != ''
&& typeof source === "object"
&& source.hasOwnProperty('uri')
&& (
skipSourceCheck ||
typeof skipSourceCheck === 'undefined' ||
(!skipSourceCheck && source != this.props.source)
)
)
{ // remote
if (this.jobId) { // sanity
this._stopDownload();
}
const url = new URL(source.uri, null, true);
// handle query params for cache key
let cacheable = url.pathname;
if (Array.isArray(this.props.useQueryParamsInCacheKey)) {
this.props.useQueryParamsInCacheKey.forEach(function(k) {
if (url.query.hasOwnProperty(k)) {
cacheable = cacheable.concat(url.query[k]);
}
});
}
else if (this.props.useQueryParamsInCacheKey) {
cacheable = cacheable.concat(url.query);
}
const type = url.pathname.replace(/.*\.(.*)/, '$1');
const cacheKey = SHA1(cacheable) + (type.length < url.pathname.length ? '.' + type : '');
this.checkImageCache(source.uri, url.host, cacheKey);
this.setState({isRemote: true});
}
else {
this.setState({isRemote: false});
}
}
_stopDownload() {
if (!this.jobId) return;
this.downloading = false;
RNFS.stopDownload(this.jobId);
this.jobId = null;
}
componentWillMount() {
if (this.props.checkNetwork) {
NetInfo.isConnected.addEventListener('change', this._handleConnectivityChange);
// componentWillUnmount unsets this._handleConnectivityChange in case the component unmounts before this fetch resolves
NetInfo.isConnected.fetch().done(this._handleConnectivityChange);
}
this._processSource(this.props.source, true);
}
componentWillUnmount() {
if (this.props.checkNetwork) {
NetInfo.isConnected.removeEventListener('change', this._handleConnectivityChange);
this._handleConnectivityChange = null;
}
if (this.downloading && this.jobId) {
this._stopDownload();
}
}
async _handleConnectivityChange(isConnected) {
this.networkAvailable = isConnected;
};
render() {
if (!this.state.isRemote && !this.props.defaultSource) {
return this.renderLocal();
}
if (this.state.cacheable && this.state.cachedImagePath) {
return this.renderCache();
}
if (this.props.defaultSource) {
return this.renderDefaultSource();
}
return (
<ActivityIndicator {...this.props.activityIndicatorProps} />
);
}
renderCache() {
const { children, defaultSource, checkNetwork, networkAvailable, downloadInBackground, activityIndicatorProps, ...props } = this.props;
return (
<ResponsiveImage {...props} source={{uri: 'file://'+this.state.cachedImagePath}}>
{children}
</ResponsiveImage>
);
}
renderLocal() {
const { children, defaultSource, checkNetwork, networkAvailable, downloadInBackground, activityIndicatorProps, ...props } = this.props;
return (
<ResponsiveImage {...props}>
{children}
</ResponsiveImage>
);
}
renderDefaultSource() {
const { children, defaultSource, checkNetwork, networkAvailable, ...props } = this.props;
return (
<CacheableImage {...props} source={defaultSource} checkNetwork={false} networkAvailable={this.networkAvailable} >
{children}
</CacheableImage>
);
}
}
CacheableImage.propTypes = {
activityIndicatorProps: PropTypes.object,
defaultSource: Image.propTypes.source,
useQueryParamsInCacheKey: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.array
]),
checkNetwork: PropTypes.bool,
networkAvailable: PropTypes.bool,
downloadInBackground: PropTypes.bool
};
CacheableImage.defaultProps = {
style: { backgroundColor: 'transparent' },
activityIndicatorProps: {
style: { backgroundColor: 'transparent', flex: 1 }
},
useQueryParamsInCacheKey: false, // bc
checkNetwork: true,
networkAvailable: false,
downloadInBackground: (Platform.OS === 'ios') ? false : true
};