getDocument method

Future<File?> getDocument(
  1. String path, {
  2. Data? owner,
  3. String? scope,
})

Implementation

Future<File?> getDocument(String path, {Data? owner, String? scope}) async {
  final requestType = Helper.SimulatedRequestType.GET;
  final effectiveScope = (scope != null && scope.isNotEmpty)
      ? scope
      : (owner != null ? local.scopeFor(owner) : null);

  try {
    return await local.getDocument(path, scope: effectiveScope);
  } catch (_) {}

  final key = '${effectiveScope ?? ''}|$path';
  final existing = _inflightDocumentFetches[key];
  if (existing != null) return existing;

  Future<File?> fetchRemote() async {
    final progressSession = DownloadProgress.instance.active;
    final progressToken = progressSession?.beginTask(
      '',
      key: '/doc/get|$path',
      step: InspectionDownloadSteps.documents,
    );
    try {
      await tryNetwork(requestType: requestType);
      final request = remote.getDocument(path, scope: effectiveScope);
      final response = await remote.postJSON(request.rd);
      if (response == null) {
        if (progressToken != null) {
          progressSession?.endTask(progressToken, success: false);
        }
        return null;
      }
      final document = await request.parser(response);
      if (progressToken != null) {
        progressSession?.endTask(progressToken, success: document != null);
      }
      return document;
    } catch (_) {
      if (progressToken != null) {
        progressSession?.endTask(progressToken, success: false);
      }
      try {
        return await local.getDocument(path, scope: effectiveScope);
      } catch (_) {
        return null;
      }
    }
  }

  Future<File?> fetch() async {
    final session = DownloadProgress.instance.active;
    if (session == null) return fetchRemote();
    return session.enqueueDownload(fetchRemote);
  }

  final future = fetch();
  _inflightDocumentFetches[key] = future;
  try {
    return await future;
  } finally {
    _inflightDocumentFetches.remove(key);
  }
}