downloadWithProgress method

  1. @override
Stream<int> downloadWithProgress(
  1. String url,
  2. String targetPath, {
  3. String? token,
  4. int maxRetries = 10,
})
override

Downloads a file with progress tracking

Returns a stream of progress percentages (0-100)

Parameters:

  • url: Source URL
  • targetPath: Destination path
  • token: Optional auth token
  • maxRetries: Max retry attempts for transient errors (default: 10) Note: Auth errors (401/403/404) fail after 1 attempt regardless of this value

Example:

await for (final progress in downloader.downloadWithProgress(...)) {
  print('Progress: $progress%');
}

Implementation

@override
Stream<int> downloadWithProgress(
  String url,
  String targetPath, {
  String? token,
  int maxRetries = 10,
}) async* {
  if (token == null) {
    // PUBLIC PATH: Direct URL registration
    try {
      final uri = Uri.tryParse(url);
      if (uri == null || (!uri.isScheme('HTTP') && !uri.isScheme('HTTPS'))) {
        throw ArgumentError('Invalid URL: $url. Must be HTTP or HTTPS.');
      }

      debugPrint('WebDownloadService: Registering public URL for $targetPath');

      // Register direct URL
      _fileSystem.registerUrl(targetPath, url);

      // Simulate progress
      const totalSteps = 20;
      const stepDelay = Duration(milliseconds: 50);

      for (int i = 0; i <= totalSteps; i++) {
        final progress = (i * 100 ~/ totalSteps).clamp(0, 100);
        yield progress;

        if (i < totalSteps) {
          await Future.delayed(stepDelay);
        }
      }

      debugPrint('WebDownloadService: Completed registration for $targetPath');

    } catch (e) {
      debugPrint('WebDownloadService: Registration failed for $targetPath: $e');
      if (e is ArgumentError) {
        rethrow;
      }
      throw DownloadException(
        DownloadError.unknown('Failed to register model URL: $e'),
      );
    }
  } else {
    // PRIVATE PATH: Fetch with auth
    debugPrint('WebDownloadService: Starting authenticated download for $targetPath');

    yield* _downloadWithAuth(url, targetPath, token);
  }
}