-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathCacheHelper.js
More file actions
353 lines (321 loc) · 8.96 KB
/
CacheHelper.js
File metadata and controls
353 lines (321 loc) · 8.96 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
import {AsyncStorage, DeviceEventEmitter} from "react-native";
import CryptoJS from 'crypto-js'
import RNFetchBlob from 'rn-fetch-blob'
const STORAGE_KEY = 'cache-image-entity'
const TOTAL_DIRECTORYS = 17
const {fs} = RNFetchBlob
const cacheEntity = {
cacheMap: {},
latest: false
}
// download image tasks
const taskList = {}
/**
* urls of downloading
* {'url':{ing:true, notify:true}}
*/
const downloading = {}
const config = {
overwrite: false,
dirsQuantity: TOTAL_DIRECTORYS
}
/**
* 加法hash算法
* @param value md5字符串
* @returns {number} 获得值为[0, dirsQuantity - 1]
*/
const additiveHash = value => {
let hash = 0
const chars = value.match(/./g)
for (let v of chars) {
hash += parseInt(`0x${v}`, 16)
}
return hash % config.dirsQuantity
}
/**
* 图片存储的基本目录
* @returns {string}
*/
const getImagesCacheDirectory = () => `${fs.dirs.CacheDir}/cache-images`
const getEncryptedInfo = fileOriginalName => {
const filename = CryptoJS.MD5(fileOriginalName).toString()
const directory = additiveHash(filename)
return {filename, directory}
}
/**
* 图片存储临时目录
* @returns {string}
*/
const getTmpDir = () => `${getImagesCacheDirectory()}/tmp`
/**
* get the final image local path
* @param originalUri
* @returns {Promise<*>}
*/
const getImagePath = async (originalUri) => {
if (!originalUri) return
await _syncStorage2CacheEntity()
let {cacheMap = {}} = cacheEntity
const cachePath = cacheMap[originalUri]
if (cachePath) {
const exists = await fs.exists(cachePath).catch(e => printLog(e))
if (exists) return `file://${cachePath}`
else return await _fetchImage(originalUri).catch(e => printLog(e))
}
return await _fetchImage(originalUri).catch(e => printLog(e))
}
/**
* fetch image data from newwork and update cache map
* @param originalUri
* @returns {Promise<string>}
* @private
*/
const _fetchImage = async (originalUri) => {
if (!downloading[originalUri]) {
downloading[originalUri] = {ing: true}
} else {
downloading[originalUri].notify = true
return
}
const {filename, directory} = getEncryptedInfo(originalUri)
const taskId = `${filename}${parseInt(Math.random(100) * 100)}${new Date().getMilliseconds()}`
const tmpPath = `${getTmpDir()}/${taskId}`
const task = RNFetchBlob.config({
path: tmpPath
}).fetch('GET', originalUri).catch(e => printLog(e))
taskList[taskId] = task
const response = await task.catch(e => printLog(e))
delete taskList[taskId]
printLog(response)
if (!response) return
const imageExtension = _getImageExtension(response)
const cacheDir = `${getImagesCacheDirectory()}/${directory}`
const cachePath = `${cacheDir}/${filename}.${imageExtension}`
const existsImage = await _moveImage(cacheDir, tmpPath, cachePath).catch(e => printLog(e))
await _saveCacheKey(originalUri, cachePath).catch(e => printLog(e))
if (existsImage) {
response.flush()
}
const downloadInfo = downloading[originalUri]
delete downloading[originalUri]
if (downloadInfo && downloadInfo.notify) {
DeviceEventEmitter.emit(event.render, originalUri, `file://${cachePath}`)
}
return `file://${cachePath}`
}
/**
* create tmp dir just once
* @returns {Promise<void>}
* @private
*/
const _createTmpDir = async () => {
const rootDir = getImagesCacheDirectory()
const tmpDir = getTmpDir()
const isRootDirExists = await fs.isDir(rootDir).catch(e => printLog(e))
if (!isRootDirExists) await fs.mkdir(rootDir).catch(e => printLog(e))
const isTmpDirExists = await fs.isDir(tmpDir).catch(e => printLog(e))
if (!isTmpDirExists) await fs.mkdir(tmpDir).catch(e => printLog(e))
}
/**
* move the tmp image file to final local path
* @param toDir
* @param from
* @param to
* @returns {Promise<void>}
* @private
*/
const _moveImage = async (toDir, from, to) => {
const exists = await fs.exists(to).catch(e => printLog(e))
if (exists) {
if (config.overwrite) {
await fs.unlink(to)
} else {
return true
}
}
const isDir = await fs.isDir(toDir).catch(e => printLog(e))
if (!isDir) {
await fs.mkdir(toDir).catch(e => printLog(e))
}
await fs.mv(from, to).catch(e => console.log(e))
return false
}
/**
* get the latest CacheEntity
* @returns {Promise<{update: boolean, map: {}, latest: boolean}>}
* @private
*/
const _syncStorage2CacheEntity = async () => {
if (!cacheEntity || !cacheEntity.latest) {
let entity = await AsyncStorage.getItem(STORAGE_KEY).catch(e => printLog(e))
if (entity) {
try {
entity = JSON.parse(entity)
} catch (e) {
entity = {}
}
} else {
entity = {}
}
Object.assign(cacheEntity, entity, {latest: true})
}
}
/**
* save the pair of original-image-uri and final-cache-path
* @param originalUri
* @param cachePath
* @returns {Promise<void>}
* @private
*/
const _saveCacheKey = async (originalUri, cachePath) => {
await _syncStorage2CacheEntity().catch(e => printLog(e))
const {cacheMap = {}} = cacheEntity
cacheMap[originalUri] = cachePath
await _syncCacheEntity2Storage().catch(e => printLog(e))
}
/**
* sync save CacheEntity to storage
* @returns {Promise<void>}
* @private
*/
const _syncCacheEntity2Storage = async () => {
if (cacheEntity) {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(cacheEntity)).catch(e => printLog(e))
}
}
/**
* get image type
* @param response
* @returns {string}
* @private
*/
const _getImageExtension = (response) => {
const info = response.info() || {}
const contentType = info.headers['Content-Type'] || ''
const matchResult = contentType.match(/image\/(png|jpg|jpeg|bmp|gif|webp|psd);/i)
return matchResult && matchResult.length >= 2 ? matchResult[1] : 'png'
}
/**
* register cache image service
* @returns {Promise<void>}
*/
const register = async (cacheConfig) => {
_createTmpDir().then().catch(e => printLog(e))
Object.assign(config, cacheConfig || {})
let entity = await AsyncStorage.getItem(STORAGE_KEY).catch(e => printLog(e))
if (entity) {
try {
entity = JSON.parse(entity)
} catch (e) {
entity = {}
}
} else {
entity = {}
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(entity)).catch(e => printLog(e))
}
Object.assign(cacheEntity, entity, {latest: true})
}
const unregister = async () => {
for (let key in taskList) {
try {
taskList[key].cancel()
} catch (e) {
printLog(e)
}
}
}
/**
* get all files Recursively
* @param path
* @returns {Promise<*>}
*/
const getFiles = async (path) => {
const exists = await fs.exists(path).catch(() => [])
if (!exists) return []
const isDir = await fs.isDir(path).catch(() => false)
if (isDir) {
const files = await fs.lstat(path)
if (!files || files.length === 0) return []
const tasks = []
for (const file of files) {
if (file.type === 'file') {
tasks.push(file)
} else {
tasks.push(getFiles(file.path))
}
}
const filesArr = await Promise.all(tasks)
let allfiles = []
for (const f of filesArr) {
allfiles = allfiles.concat(f)
}
return allfiles
} else {
return [await fs.stat(path)]
}
}
/**
* get the cache size. unit:bytes
* @returns {Promise<number>}
*/
const getCacheSize = async () => {
const path = getImagesCacheDirectory()
const files = await getFiles(path)
if (!files || files.length === 0) return 0
let size = 0
for (let file of files) {
size += parseInt(file.size)
}
return size
}
/**
* get cache size with format
* @returns {Promise<string>}
*/
const getCacheSizeFormat = async () => {
const size = await getCacheSize()
if (size < 1024 * 1024) {
return `${parseInt(size / 1024)}KB`
} else {
return `${Number(size / (1024 * 1024)).toFixed(2)}MB`
}
}
/**
* clear cache
* @returns {Promise<void>}
*/
const clearCache = async () => {
const path = getImagesCacheDirectory()
await fs.unlink(path).catch(e => printLog(e))
await fs.mkdir(path).catch(e => printLog(e))
cacheEntity.latest = true
cacheEntity.cacheMap = {}
try {
for (let key in downloading) {
delete downloading[key]
}
} catch (e) {
printLog(e)
}
await _syncCacheEntity2Storage().catch(e => printLog(e))
}
const event = {
render: 'cacheimage_event_render_image',
}
const pattern = {
remoteUri: /^(http[s]?)/i
}
const printLog = (v) => {
if (process.env.NODE_ENV !== 'production') console.log(v)
}
export default {
register,
unregister,
getCacheSize,
getCacheSizeFormat,
clearCache,
getImagePath,
event,
pattern,
printLog,
}