downChunk method
Implementation
Future<ProcessState> downChunk(ProcessState state, int idx, {int retry = 3}) async {
Chunk ck = state.chunks[idx];
for (int attempt = 0; attempt < retry; attempt++) {
try {
HttpClient c = HttpClient();
c.connectionTimeout = const Duration(seconds: 10);
final req = await c.getUrl(Uri.parse(state.url));
req.headers.add('Range', 'bytes=${ck.startOffset}-${ck.endOffset - 1}');
final resp = await req.close();
if (resp.statusCode >= 200 && resp.statusCode < 300) {
if (savePath != null) {
final chunkFile = File(_chunkFilePath(ck.partNumber));
final sink = chunkFile.openWrite();
await for (var ls in resp) {
sink.add(ls);
}
await sink.close();
ck.data = <int>[];
} else {
for (var ls in await resp.toList()) {
ck.data.addAll(ls);
}
}
} else {
throw DownloadFailureException();
}
state.successCount++;
return state;
} catch (e) {
if (attempt == retry - 1) {
print('Download chunk error (final):$e');
throw DownloadFailureException();
} else {
print('Download chunk error, retrying ($attempt):$e');
await Future.delayed(const Duration(milliseconds: 500));
}
}
}
throw DownloadFailureException();
}