download method

Future<ProcessState> download({
  1. OnPercentage? onPercentage,
})

Implementation

Future<ProcessState> download({OnPercentage? onPercentage}) async {
  _onPercentage = onPercentage;
  final req = await client.headUrl(Uri.parse(state.url));
  final resp = await req.close();

  if (!await _isRangeSupported(resp)) {
    throw UnsupportedException();
  }

  final contentLength = resp.headers['content-length'];
  if (contentLength == null || contentLength.isEmpty) {
    throw DownloadFailureException();
  }

  final fileSize = int.parse(contentLength.first);
  state.init(fileSize);
  final indexies = List<int>.generate(processors, (i) => i);
  fetching = true;
  final futures = indexies
      .map((pid) => processor(state, pid, processors));
  await Future.wait(futures);
  fetching = false;
  if (savePath != null) {
    final file = File(savePath!);
    final raf = file.openSync(mode: FileMode.write);
    for (var ck in state.chunks) {
      final chunkFile = File(_chunkFilePath(ck.partNumber));
      if (chunkFile.existsSync()) {
        raf.writeFromSync(chunkFile.readAsBytesSync());
        chunkFile.deleteSync();
      }
    }
    raf.closeSync();
  }
  return state;
}