cacheInspectionDocumentsForDownload function
Implementation
@visibleForTesting
Future<bool> cacheInspectionDocumentsForDownload(
InspectionLocation location, {
DownloadProgressSession? progressSession,
String? scope,
DocumentCacheLookup? readCachedDocument,
DocumentDownloadLookup? downloadDocument,
}) async {
final documents = location.dokuspaths ?? const [];
final effectiveScope = scope ?? API().local.scopeFor(location);
final readCached = readCachedDocument ??
(String path, String scope) =>
API().local.getDocument(path, scope: scope);
final download = downloadDocument ??
(String path, InspectionLocation owner, String scope) =>
API().getDocument(path, owner: owner, scope: scope);
var allSucceeded = true;
progressSession?.setStep(
InspectionDownloadSteps.documents,
label: InspectionDownloadSteps.documentsPrepareLabel,
);
if (documents.isEmpty) {
progressSession?.setStep(
InspectionDownloadSteps.documents,
label: InspectionDownloadSteps.noDocumentsLabel,
);
return true;
}
final validDocuments = <DocumentData>[];
for (final document in documents) {
final path = _downloadPathForDocument(document);
if (path.isEmpty) {
debugPrint('Dokument ohne gültigen Pfad gefunden');
allSucceeded = false;
continue;
}
validDocuments.add(document);
progressSession?.reserveTask(
'/doc/get|$path',
step: InspectionDownloadSteps.documents,
);
}
for (var index = 0; index < validDocuments.length; index++) {
final total = validDocuments.length;
final document = validDocuments[index];
final path = _downloadPathForDocument(document);
final current = index + 1;
DownloadTaskToken? token;
progressSession?.setStep(
InspectionDownloadSteps.documents,
label: InspectionDownloadSteps.documentCheckLabel(
current,
total,
),
);
token = progressSession?.beginTask(
InspectionDownloadSteps.documentCheckLabel(current, total),
key: '/doc/get|$path',
step: InspectionDownloadSteps.documents,
);
var isCached = false;
try {
final localFile = await readCached(path, effectiveScope);
isCached = localFile != null && await localFile.exists();
} catch (_) {}
if (isCached) {
if (token != null) progressSession?.endTask(token, success: true);
continue;
}
progressSession?.setStep(
InspectionDownloadSteps.documents,
label: InspectionDownloadSteps.documentLabel(
current,
total,
),
);
try {
final file = await download(path, location, effectiveScope);
final succeeded = file != null && await file.exists();
if (!succeeded) {
allSucceeded = false;
debugPrint(
'Dokument "${document.filename}" konnte nicht gespeichert werden',
);
}
if (token != null) progressSession?.endTask(token, success: succeeded);
} catch (error) {
allSucceeded = false;
if (token != null) progressSession?.endTask(token, success: false);
debugPrint(
'Dokument "${document.filename}" konnte nicht gespeichert werden: '
'$error',
);
}
}
return allSucceeded;
}