download method

dynamic download(
  1. DownloadRequest request, {
  2. OnStart? onStart,
  3. OnProgress? onProgress,
  4. OnSuccess? onSuccess,
  5. OnFailure? onFailure,
})

Implementation

download(DownloadRequest request,
    {OnStart? onStart,
    OnProgress? onProgress,
    OnSuccess? onSuccess,
    OnFailure? onFailure}) async {
  String urlPath = request.path;
  String savePath = request.savePath;
  String? md5Str = request.md5;
  MyLog.i("准备下载 url=$urlPath; savePath=$savePath; md5=$md5Str");
  if (_isTaskExists(urlPath)) {
    MyLog.d("当前文件正在下载中: $savePath");
    onFailure?.call(-1, "当前文件正在下载中", savePath);
    return;
  }
  MyLog.i("检测是否已下载 url=$urlPath; savePath=$savePath;");
  File saveFile = File(savePath);

  if (saveFile.existsSync() &&
      (md5Str != null && md5Str == Md5.md5Str(savePath))) {
    MyLog.i("下载文件已存在: $savePath");
    onSuccess?.call(savePath);
    return;
  }
  // _addDownloadTask(url);
  var response = await dioRequest.download(request, onStart: (total) {
    MyLog.i("开始下载: $urlPath; $total");
    onStart?.call(total);
  }, onProgress: (count, total, speed) {
    MyLog.d("onProgress: $urlPath; $count/$total; $speed/s");
    onProgress?.call(count, total, speed);
  });
  //
  if (response.isSuccess()) {
    var value = await Md5.md5File(savePath);
    if (md5Str == null || value == md5Str) {
      MyLog.i("下载完成 url=$savePath; savePath=$savePath;");
      onSuccess?.call(savePath);
    } else {
      MyLog.e("md5校验失败 url=$urlPath; savePath=$savePath;");
      onFailure?.call(-1, "md5校验失败", savePath);
    }
    onSuccess?.call(request.savePath);
  } else {
    MyLog.e(
        "下载失败-$urlPath(${response.statusCode}):${response.response}; url=$urlPath; savePath=$savePath;");
    onFailure?.call(
        -1,
        "下载失败-$urlPath(${response.statusCode}):${response.response}",
        savePath);
  }
}