download-file.js 2.1 KB
Newer Older
Q
qiang 已提交
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
import {
  invoke
} from 'uni-core/service/bridge'

import {
  onMethod,
  invokeMethod
} from '../../platform'

class DownloadTask {
  constructor (downloadTaskId, callbackId) {
    this.id = downloadTaskId
    this._callbackId = callbackId
    this._callbacks = []
  }
  abort () {
    invokeMethod('operateRequestTask', {
      downloadTaskId: this.id,
      operationType: 'abort'
    })
  }
  onProgressUpdate (callback) {
    if (typeof callback !== 'function') {
      return
    }
    this._callbacks.push(callback)
  }
  onHeadersReceived () {

  }
  offProgressUpdate (callback) {
    const index = this._callbacks.indexOf(callback)
    if (index >= 0) {
      this._callbacks.splice(index, 1)
    }
  }
  offHeadersReceived () {

  }
}
const downloadTasks = Object.create(null)
onMethod('onDownloadTaskStateChange', ({
  downloadTaskId,
  state,
  tempFilePath,
  statusCode,
  progress,
  totalBytesWritten,
  totalBytesExpectedToWrite,
  errMsg
}) => {
  const downloadTask = downloadTasks[downloadTaskId]
  const callbackId = downloadTask._callbackId

  switch (state) {
    case 'progressUpdate':
      downloadTask._callbacks.forEach(callback => {
        callback({
          progress,
          totalBytesWritten,
          totalBytesExpectedToWrite
        })
      })
      break
    case 'success':
      invoke(callbackId, {
        tempFilePath,
        statusCode,
        errMsg: 'request:ok'
      })
      // eslint-disable-next-line no-fallthrough
    case 'fail':
      invoke(callbackId, {
        errMsg: 'request:fail ' + errMsg
      })
      // eslint-disable-next-line no-fallthrough
    default:
      // progressUpdate 可能晚于 success
      setTimeout(() => {
        delete downloadTasks[downloadTaskId]
      }, 100)
      break
  }
})
export function downloadFile (args, callbackId) {
  const {
    downloadTaskId
  } = invokeMethod('createDownloadTask', args)
  const task = new DownloadTask(downloadTaskId, callbackId)
  downloadTasks[downloadTaskId] = task
  return task
}