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);
  late var fileTransferObject;
  try {
    fileTransferObject =
        FileTransferObject.fromJson(jsonDecode(result.value));
  } on Exception catch (e) {
    throw Exception('json decode exception in download file ${e.toString()}');
  }
  var downloadedFiles = <File>[];
  var fileDownloadReponse = await FileTransferService()
      .downloadFromFileBin(fileTransferObject, downloadPath);
  if (fileDownloadReponse.isError) {
    throw Exception('download fail');
  }
  var encryptedFileList = Directory(fileDownloadReponse.filePath!).listSync();
  try {
    for (var encryptedFile in encryptedFileList) {
      var decryptedFile = _encryptionService!.decryptFile(
          File(encryptedFile.path).readAsBytesSync(),
          fileTransferObject.fileEncryptionKey);
      var downloadedFile =
          File(downloadPath + '/' + encryptedFile.path.split('/').last);
      downloadedFile.writeAsBytesSync(decryptedFile);
      downloadedFiles.add(downloadedFile);
    }
    // deleting temp directory
    Directory(fileDownloadReponse.filePath!).deleteSync(recursive: true);
    return downloadedFiles;
  } catch (e) {
    print('error in downloadFile: $e');
    return [];
  }
}