downloadFile method

  1. @override
Future<String> downloadFile({
  1. required String remotePath,
  2. required String localPath,
})
override

Downloads a file from the cloud storage.

Implementation

@override
Future<String> downloadFile({
  required String remotePath,
  required String localPath,
}) async {
  _checkAuth();

  final file = await _getFileByPath(remotePath);
  if (file == null || file.id == null) {
    throw Exception('GoogleDriveProvider: File not found at $remotePath');
  }

  final output = File(localPath);
  final sink = output.openWrite();

  try {
    final media = await driveApi.files.get(
      file.id!,
      downloadOptions: drive.DownloadOptions.fullMedia,
    ) as drive.Media; // Cast is important here

    await media.stream.pipe(sink);
    await sink.close();
  } catch (e) {
    await sink.close(); // Ensure sink is closed on error
    // Delete partially downloaded file if an error occurs
    if (await output.exists()) {
      await output.delete();
    }
    debugPrint("Error downloading file: $e");
    if (e is drive.DetailedApiRequestError &&
        (e.status == 401 || e.status == 403)) {
      debugPrint(
          "Authentication error during download. The user may not have permission, or the token is invalid.");
      _isAuthenticated = false;
    }
    rethrow;
  }

  return localPath;
}