Files
react-native-background-dow…/lib/downloadTask.js
2022-12-23 09:09:32 +01:00

106 lines
2.6 KiB
JavaScript

import { NativeModules } from 'react-native'
const { RNBackgroundDownloader } = NativeModules
function validateHandler (handler) {
if (!(typeof handler === 'function'))
throw new TypeError(`[RNBackgroundDownloader] expected argument to be a function, got: ${typeof handler}`)
}
export default class DownloadTask {
state = 'PENDING'
percent = 0
bytesWritten = 0
totalBytes = 0
metadata = {}
constructor (taskInfo, originalTask) {
this.id = taskInfo.id
this.percent = taskInfo.percent ?? 0
this.bytesWritten = taskInfo.bytesWritten ?? 0
this.totalBytes = taskInfo.totalBytes ?? 0
if (this.#parseable(taskInfo.metadata))
this.metadata = JSON.parse(taskInfo.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 ({ expectedBytes, headers }) {
this.state = 'DOWNLOADING'
if (this._beginHandler)
this._beginHandler({ expectedBytes, headers })
}
_onProgress (percent, bytesWritten, totalBytes) {
this.percent = percent
this.bytesWritten = bytesWritten
this.totalBytes = totalBytes
if (this._progressHandler)
this._progressHandler(percent, bytesWritten, totalBytes)
}
_onDone ({ location }) {
this.state = 'DONE'
if (this._doneHandler)
this._doneHandler({ location })
}
_onError (error, errorCode) {
this.state = 'FAILED'
if (this._errorHandler)
this._errorHandler(error, errorCode)
}
pause () {
this.state = 'PAUSED'
RNBackgroundDownloader.pauseTask(this.id)
}
resume () {
this.state = 'DOWNLOADING'
RNBackgroundDownloader.resumeTask(this.id)
}
stop () {
this.state = 'STOPPED'
RNBackgroundDownloader.stopTask(this.id)
}
#parseable = (element) => {
try {
JSON.parse(element)
return true
} catch (err) {
return false
}
}
}