-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathDownloadTask.ts
116 lines (94 loc) · 2.46 KB
/
DownloadTask.ts
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
import { NativeModules } from 'react-native'
import { TaskInfo } from '..'
const { RNBackgroundDownloader } = NativeModules
function validateHandler (handler) {
const type = typeof handler
if (type !== 'function')
throw new TypeError(`[RNBackgroundDownloader] expected argument to be a function, got: ${type}`)
}
export default class DownloadTask {
id = ''
state = 'PENDING'
metadata = {}
bytesDownloaded = 0
bytesTotal = 0
beginHandler
progressHandler
doneHandler
errorHandler
constructor (taskInfo: TaskInfo, originalTask?: TaskInfo) {
this.id = taskInfo.id
this.bytesDownloaded = taskInfo.bytesDownloaded ?? 0
this.bytesTotal = taskInfo.bytesTotal ?? 0
const metadata = this.tryParseJson(taskInfo.metadata)
if (metadata)
this.metadata = metadata
if (originalTask) {
this.beginHandler = originalTask.beginHandler
this.progressHandler = originalTask.progressHandler
this.doneHandler = originalTask.doneHandler
this.errorHandler = originalTask.errorHandler
}
}
begin (handler) {
validateHandler(handler)
this.beginHandler = handler
return this
}
progress (handler) {
validateHandler(handler)
this.progressHandler = handler
return this
}
done (handler) {
validateHandler(handler)
this.doneHandler = handler
return this
}
error (handler) {
validateHandler(handler)
this.errorHandler = handler
return this
}
onBegin (params) {
this.state = 'DOWNLOADING'
this.beginHandler?.(params)
}
onProgress ({ bytesDownloaded, bytesTotal }) {
this.bytesDownloaded = bytesDownloaded
this.bytesTotal = bytesTotal
this.progressHandler?.({ bytesDownloaded, bytesTotal })
}
onDone (params) {
this.state = 'DONE'
this.bytesDownloaded = params.bytesDownloaded
this.bytesTotal = params.bytesTotal
this.doneHandler?.(params)
}
onError (params) {
this.state = 'FAILED'
this.errorHandler?.(params)
}
pause () {
this.state = 'PAUSED'
RNBackgroundDownloader.pauseTask(this.id)
}
resume () {
this.state = 'DOWNLOADING'
RNBackgroundDownloader.resumeTask(this.id)
}
stop () {
this.state = 'STOPPED'
RNBackgroundDownloader.stopTask(this.id)
}
tryParseJson (element) {
try {
if (typeof element === 'string')
element = JSON.parse(element)
return element
} catch (e) {
console.warn('DownloadTask tryParseJson', e)
return null
}
}
}