-
Notifications
You must be signed in to change notification settings - Fork 470
/
fsUtils.js
205 lines (186 loc) · 6.34 KB
/
fsUtils.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
'use strict';
const _ = require('lodash');
const RNFetchBlob = require('react-native-fetch-blob').default;
const {
fs
} = RNFetchBlob;
const activeDownloads = {};
function getDirPath(path) {
// if path is a file (has ext) remove it
if (path.charAt(path.length - 4) === '.' || path.charAt(path.length - 5) === '.') {
return _.initial(path.split('/')).join('/');
}
return path;
}
function ensurePath(path) {
const dirPath = getDirPath(path);
return fs.isDir(dirPath)
.then(isDir => {
if (!isDir) {
return fs.mkdir(dirPath)
// check if dir has indeed been created because
// there's no exception on incorrect user-defined paths (?)...
.then(() => fs.isDir(dirPath))
.then(isDir => {
if (!isDir) {
throw new Error('Invalid cacheLocation');
}
})
}
})
.catch(err => {
// ignore folder already exists errors
if (err.message.includes('folder already exists')) {
return;
}
throw err;
});
}
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 [];
});
}
/**
* wrapper around common filesystem actions
*/
module.exports = {
/**
* returns the local cache dir
* @returns {String}
*/
getCacheDir() {
return fs.dirs.CacheDir + '/imagesCacheDir';
},
/**
* 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 with headers to use when downloading the file
* @returns {Promise}
*/
downloadFile(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] = ensurePath(toFile)
.then(() => RNFetchBlob
.config({
path: tmpFile
})
.fetch('GET', fromUrl, headers)
.then(res => {
if (res.respInfo.status === 304) {
return Promise.resolve(toFile);
}
let status = Math.floor(res.respInfo.status / 100);
if (status !== 2) {
// TODO - log / return error?
return Promise.reject();
}
return RNFetchBlob.fs.stat(tmpFile)
.then(fileStats => {
// Verify if the content was fully downloaded!
if (res.respInfo.headers['Content-Length'] && res.respInfo.headers['Content-Length'] != fileStats.size) {
return Promise.reject();
}
// the download is complete and rename the temporary file
return fs.mv(tmpFile, toFile);
});
})
.catch(error => {
// cleanup. will try re-download on next CachedImage mount.
this.deleteFile(tmpFile);
delete activeDownloads[toFile];
return Promise.reject('Download failed');
})
.then(() => {
// cleanup
this.deleteFile(tmpFile);
delete activeDownloads[toFile];
return toFile;
})
);
}
return activeDownloads[toFile];
},
/**
* remove the file in filePath if it exists.
* this method always resolves
* @param filePath
* @returns {Promise}
*/
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
});
},
/**
* copy a file from fromFile to toFile
* @param fromFile
* @param toFile
* @returns {Promise}
*/
copyFile(fromFile, toFile) {
return ensurePath(toFile)
.then(() => fs.cp(fromFile, toFile));
},
/**
* remove the contents of dirPath
* @param dirPath
* @returns {Promise}
*/
cleanDir(dirPath) {
return fs.isDir(dirPath)
.then(isDir => isDir && fs.unlink(dirPath))
.catch(() => {})
.then(() => ensurePath(dirPath));
},
/**
* get info about files in a folder
* @param dirPath
* @returns {Promise.<{file:Array, size:Number}>}
*/
getDirInfo(dirPath) {
return fs.isDir(dirPath)
.then(isDir => {
if (isDir) {
return collectFilesInfo(dirPath);
} else {
throw new Error('Dir does not exists');
}
})
.then(filesInfo => {
const files = _.flattenDeep(filesInfo);
const size = _.sumBy(files, 'size');
return {
files,
size
};
});
},
exists(path) {
return fs.exists(path);
}
};