download method
Fetch id to disk, reporting progress until it is registered.
Emits a terminal DownloadFailed/DownloadCancelled event when the transfer fails or is cancelled; never fabricates a DownloadCompleted afterward.
Implementation
Stream<DownloadEvent> download(String id) async* {
final operationId = id;
var sequence = 0;
yield DownloadStarted(operationId, sequence: sequence++);
var extracting = false;
var verifying = false;
await for (final progress in RunAnywhereDownloads.shared.start(id)) {
switch (progress.state) {
case DownloadState.DOWNLOAD_STATE_FAILED:
yield DownloadFailed(
operationId,
progress.hasError()
? SDKException.downloadFailed(id, progress.error.message)
: SDKException.downloadFailed(id),
sequence: sequence++,
);
return;
case DownloadState.DOWNLOAD_STATE_CANCELLED:
yield DownloadCancelled(operationId, sequence: sequence++);
return;
case DownloadState.DOWNLOAD_STATE_COMPLETED:
final model = await get(id);
if (model == null) {
yield DownloadFailed(
operationId,
SDKException.modelNotFound(id),
sequence: sequence++,
);
return;
}
yield DownloadCompleted(operationId, model, sequence: sequence++);
return;
default:
// `DownloadStage` was deleted outright (idl/download_service.proto)
// — it duplicated `DownloadState`; `state` is the single phase
// field now.
if (progress.state == DownloadState.DOWNLOAD_STATE_VALIDATING) {
if (!verifying) {
verifying = true;
yield DownloadVerifying(operationId, sequence: sequence++);
}
} else if (progress.state == DownloadState.DOWNLOAD_STATE_EXTRACTING) {
if (!extracting) {
extracting = true;
yield DownloadExtracting(
operationId,
sequence: sequence++,
percent: progress.stageProgress > 0
? progress.stageProgress
: null,
);
}
} else {
yield DownloadProgressEvent(
operationId: operationId,
bytesDone: progress.bytesDownloaded.toInt(),
bytesTotal: progress.totalBytes.toInt(),
sequence: sequence++,
file: progress.hasCurrentFileName() &&
progress.currentFileName.isNotEmpty
? progress.currentFileName
: null,
overallProgress: progress.overallProgress > 0
? progress.overallProgress
: null,
);
}
}
}
}