downloadFile function
Future<void>
downloadFile(
- HttpClient client,
- RemoteFile file,
- String path, {
- void onBytes(
- int bytes
- bool cancelled()?,
Downloads file to path, reusing an existing file only after checking
its pinned size and SHA-256. Bytes arrive in
[path].part, which a later call resumes with a Range request; only a
file of the right size and SHA-256 is renamed to path. onBytes sees
how many bytes of the file are on disk; cancelled is polled between
chunks and stops the download, keeping the part.
Throws ModelDownloadException when the server refuses the file or it does not match (the part is deleted then), and lets I/O errors through for the caller to retry.
Implementation
Future<void> downloadFile(
HttpClient client,
RemoteFile file,
String path, {
void Function(int bytes)? onBytes,
bool Function()? cancelled,
}) async {
final existing = File(path);
if (existing.existsSync()) {
var matches = existing.lengthSync() == file.size;
if (matches) {
final digest = _Digest();
final hash = sha256.startChunkedConversion(digest);
if (!await _feed(existing, hash, cancelled)) return;
hash.close();
matches = digest.value.toString() == file.sha256;
}
if (cancelled?.call() ?? false) return;
if (matches) {
onBytes?.call(file.size);
return;
}
existing.deleteSync();
}
final part = File('$path.part');
var have = part.existsSync() ? part.lengthSync() : 0;
if (have > file.size) {
part.deleteSync();
have = 0;
}
final response = have == file.size
? null
: await _get(client, Uri.parse(file.url), from: have);
final digest = _Digest();
final hash = sha256.startChunkedConversion(digest);
switch (response?.statusCode) {
case null || HttpStatus.partialContent:
// Resuming: the hash first covers what is already on disk.
if (response != null && !_startsAt(response, have)) {
await response.drain<void>();
throw ModelDownloadException('${file.url}: unexpected content range');
}
if (!await _feed(part, hash, cancelled)) {
// Unread, the response would keep its connection open.
await response?.listen(null).cancel();
return;
}
case HttpStatus.ok:
have = 0; // the server sent the whole file
case final status:
await response!.drain<void>();
throw ModelDownloadException('${file.url}: HTTP $status');
}
var got = have;
if (response != null) {
final sink = part.openWrite(
mode: have > 0 ? FileMode.writeOnlyAppend : FileMode.writeOnly,
);
var reported = got;
try {
await for (final chunk in response) {
sink.add(chunk);
hash.add(chunk);
got += chunk.length;
if (got - reported >= 1 << 20) {
reported = got;
onBytes?.call(got);
}
if (cancelled?.call() ?? false) break;
}
} finally {
await sink.close();
}
if (cancelled?.call() ?? false) return;
}
hash.close();
if (got != file.size || digest.value.toString() != file.sha256) {
part.deleteSync();
throw ModelDownloadException(
'${file.name} arrived as $got bytes with SHA-256 ${digest.value}, '
'expected ${file.size} bytes with ${file.sha256}',
);
}
part.renameSync(path);
onBytes?.call(got);
}