download method

Future<HTTPResult> download(
  1. String url,
  2. String destinationPath, {
  3. void onProgress(
    1. int downloaded,
    2. int total
    )?,
  4. Duration? timeout,
})

Stream a file from url into destinationPath. On non-2xx responses the file is left untouched and a failure result is returned. onProgress is best-effort (the blocking request does not chunk-report; the hook is invoked with the final size when the download completes).

Implementation

Future<HTTPResult> download(
  String url,
  String destinationPath, {
  void Function(int downloaded, int total)? onProgress,
  Duration? timeout,
}) async {
  try {
    final resolved = url.startsWith('http') ? url : '$_baseURL$url';
    final extraHeaders = <String, String>{};
    if (_accessToken != null) {
      extraHeaders['Authorization'] = 'Bearer $_accessToken';
    }

    final response = await HTTPClientAdapter.shared.rawRequest(
      method: 'GET',
      url: resolved,
      headers: extraHeaders,
      timeoutMs: (timeout ?? const Duration(seconds: 30)).inMilliseconds,
      followRedirects: extraHeaders.isEmpty,
    );

    if (!response.isSuccess) {
      return HTTPResult(
        isSuccess: false,
        statusCode: response.statusCode,
        error: 'Download failed with status ${response.statusCode}',
      );
    }

    final file = File(destinationPath);
    await file.parent.create(recursive: true);
    await file.writeAsBytes(response.bodyBytes, flush: true);
    onProgress?.call(response.bodyBytes.length, response.bodyBytes.length);

    return HTTPResult.success(
      statusCode: response.statusCode,
      body: destinationPath,
    );
  } catch (_) {
    return HTTPResult.failure('Download failed');
  }
}