downloadFile method

  1. @override
Future<List<File>> downloadFile(
  1. String transferId,
  2. String sharedByAtSign, {
  3. String? downloadPath,
})
override

Downloads the list of files for a given transferId shared by sharedByAtSign Optionally you can pass downloadPath to download the files.

Implementation

@override
Future<List<File>> downloadFile(String transferId, String sharedByAtSign,
    {String? downloadPath}) async {
  downloadPath ??= preference!.downloadPath;
  if (downloadPath == null) {
    throw Exception('downloadPath not found');
  }
  var atKey = AtKey()
    ..key = transferId
    ..sharedBy = sharedByAtSign;
  var result = await get(atKey);
  FileTransferObject fileTransferObject;
  try {
    if (FileTransferObject.fromJson(jsonDecode(result.value)) == null) {
      _logger.severe("FileTransferObject is null");
      throw AtClientException(
          error_codes['AtClientException'], 'FileTransferObject is null');
    }
    fileTransferObject =
        FileTransferObject.fromJson(jsonDecode(result.value))!;
  } on Exception catch (e) {
    throw Exception('json decode exception in download file ${e.toString()}');
  }
  var downloadedFiles = <File>[];
  var fileDownloadResponse = await FileTransferService()
      .downloadFromFileBin(fileTransferObject, downloadPath);
  if (fileDownloadResponse.isError) {
    throw Exception('download fail');
  }
  var encryptedFileList =
      Directory(fileDownloadResponse.filePath!).listSync();
  try {
    for (var encryptedFile in encryptedFileList) {
      var decryptedFile = await _encryptionService!.decryptFileInChunks(
          File(encryptedFile.path),
          fileTransferObject.fileEncryptionKey,
          _preference!.fileEncryptionChunkSize,
          ivBase64: fileTransferObject.ivBase64);
      decryptedFile.copySync(downloadPath +
          Platform.pathSeparator +
          encryptedFile.path.split(Platform.pathSeparator).last);
      downloadedFiles.add(File(downloadPath +
          Platform.pathSeparator +
          encryptedFile.path.split(Platform.pathSeparator).last));
      decryptedFile.deleteSync();
    }
    // deleting temp directory
    Directory(fileDownloadResponse.filePath!).deleteSync(recursive: true);
    return downloadedFiles;
  } catch (e) {
    print('error in downloadFile: $e');
    return [];
  }
}