@kesha-antonov/react-native-background-downloader 4.6.4 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +95 -30
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +18 -2
  3. package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
  4. package/android/src/main/java/com/eko/Downloader.kt +37 -9
  5. package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
  6. package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +36 -1
  7. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +243 -117
  8. package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
  9. package/android/src/main/java/com/eko/ResumableDownloader.kt +109 -16
  10. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
  11. package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +134 -17
  12. package/android/src/main/java/com/eko/UploadEventEmitter.kt +26 -1
  13. package/android/src/main/java/com/eko/Uploader.kt +202 -28
  14. package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
  15. package/android/src/main/java/com/eko/handlers/OnProgress.kt +1 -1
  16. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
  17. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
  18. package/android/src/main/java/com/eko/utils/HeaderUtils.kt +9 -0
  19. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +32 -12
  20. package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
  21. package/android/src/test/java/com/eko/DownloadCompleteReceiverTest.kt +57 -0
  22. package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
  23. package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
  24. package/android/src/test/java/com/eko/ResumableDownloaderRedirectTest.kt +77 -0
  25. package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
  26. package/android/src/test/java/com/eko/UnmeteredNetworkGateTest.kt +248 -0
  27. package/android/src/test/java/com/eko/UploadPartRangesTest.kt +33 -0
  28. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +93 -0
  29. package/android/src/test/java/com/eko/UploaderPartsTest.kt +222 -0
  30. package/android/src/test/java/com/eko/UploaderResponseTest.kt +26 -0
  31. package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
  32. package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
  33. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +133 -0
  34. package/ios/RNBGDTaskConfig.h +2 -0
  35. package/ios/RNBGDTaskConfig.mm +6 -0
  36. package/ios/RNBGDUploadTaskConfig.h +26 -0
  37. package/ios/RNBGDUploadTaskConfig.mm +69 -3
  38. package/ios/RNBackgroundDownloader.mm +1203 -133
  39. package/lib/DownloadTask.d.ts +2 -0
  40. package/lib/DownloadTask.js +17 -1
  41. package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
  42. package/lib/UploadTask.d.ts +7 -1
  43. package/lib/UploadTask.js +38 -4
  44. package/lib/index.d.ts +1 -1
  45. package/lib/index.js +105 -61
  46. package/lib/types.d.ts +33 -2
  47. package/package.json +14 -11
  48. package/plugin/build/index.d.ts +1 -0
  49. package/plugin/build/index.js +18 -10
  50. package/react-native-background-downloader.podspec +8 -0
  51. package/src/DownloadTask.ts +18 -1
  52. package/src/NativeRNBackgroundDownloader.ts +23 -0
  53. package/src/UploadTask.ts +41 -2
  54. package/src/index.ts +131 -66
  55. package/src/types.ts +42 -2
@@ -9,10 +9,10 @@ import android.media.MediaScannerConnection
9
9
  import android.net.Uri
10
10
  import android.os.Build
11
11
  import android.util.Log
12
- import android.webkit.MimeTypeMap
13
12
  import com.eko.handlers.OnBegin
14
13
  import com.eko.handlers.OnProgress
15
14
  import com.eko.handlers.OnProgressState
15
+ import com.eko.interfaces.BeginCallback
16
16
  import com.eko.utils.HeaderUtils
17
17
  import com.eko.utils.ReadableConverters
18
18
  import com.eko.utils.RedirectResolver
@@ -46,6 +46,10 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
46
46
 
47
47
  private val sharedLock = Any()
48
48
 
49
+ // Signature permission held by DownloadProvider, the only legitimate sender
50
+ // of DOWNLOAD_COMPLETE
51
+ private const val DOWNLOAD_COMPLETE_PERMISSION = "android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS"
52
+
49
53
  // Controls whether debug logs are enabled
50
54
  @Volatile
51
55
  private var isLogsEnabled = false
@@ -154,6 +158,11 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
154
158
  return configIdToIsAllowedOverMetered[configId] ?: persistedValue ?: true
155
159
  }
156
160
 
161
+ // DownloadManager ids whose end was already reported. A failure is broadcast twice (by the
162
+ // progress loop and by DownloadManager), and the task is only cleaned up after the media
163
+ // scanner, so the second broadcast would report it again.
164
+ private val endedDownloadIds = mutableSetOf<Long>()
165
+
157
166
  // Last time (ms) a recovery snapshot was persisted for a resumable download,
158
167
  // used to throttle snapshot writes from the frequent progress callbacks.
159
168
  private val configIdToLastSnapshotMs = mutableMapOf<String, Long>()
@@ -216,6 +225,11 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
216
225
  headersMap.putString(key, value)
217
226
  }
218
227
  onBeginDownload(id, headersMap, expectedBytes)
228
+ // Save the size now: the first progress snapshot comes only after the throttle
229
+ // interval, and a download recovered after a force-stop before it had no total
230
+ if (expectedBytes > 0) {
231
+ maybeSnapshotActiveResumable(id, 0, expectedBytes, force = true)
232
+ }
219
233
  }
220
234
 
221
235
  override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) {
@@ -386,56 +400,75 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
386
400
 
387
401
  downloadReceiver = object : BroadcastReceiver() {
388
402
  override fun onReceive(context: Context, intent: Intent) {
389
- val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
403
+ handleDownloadEnded(context, intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1))
404
+ }
405
+ }
406
+ downloader.downloadEndedHandler = { downloadId -> handleDownloadEnded(reactContext, downloadId) }
390
407
 
391
- // Check if this download is being intentionally cancelled (paused or stopped)
392
- val cancelIntent = downloader.getCancelIntent(downloadId)
393
- if (cancelIntent != null) {
394
- downloader.clearCancelIntent(downloadId)
395
- logD(NAME, "Ignoring broadcast for ${cancelIntent.name.lowercase()} download: $downloadId")
396
- return
397
- }
408
+ // DOWNLOAD_COMPLETE isn't a protected broadcast on every Android version, and
409
+ // the receiver has to be exported for DownloadManager to reach it. Requiring
410
+ // DownloadProvider's signature permission keeps other apps from sending a fake
411
+ // one, which would end (and remove) a download that is still running.
412
+ compatRegisterReceiver(reactContext, downloadReceiver!!, filter, true, DOWNLOAD_COMPLETE_PERMISSION)
413
+ isReceiverRegistered = true
414
+ }
398
415
 
399
- val config = downloadIdToConfig[downloadId]
416
+ private fun handleDownloadEnded(context: Context, downloadId: Long) {
417
+ // Check if this download is being intentionally cancelled (paused or stopped)
418
+ val cancelIntent = downloader.getCancelIntent(downloadId)
419
+ if (cancelIntent != null) {
420
+ downloader.clearCancelIntent(downloadId)
421
+ logD(NAME, "Ignoring broadcast for ${cancelIntent.name.lowercase()} download: $downloadId")
422
+ return
423
+ }
400
424
 
401
- if (config != null) {
402
- val downloadStatus = downloader.checkDownloadStatus(downloadId)
403
- val status = downloadStatus.getInt("status")
404
- val localUri = downloadStatus.getString("localUri")
425
+ val config = downloadIdToConfig[downloadId]
405
426
 
406
- stopTaskProgress(config.id)
427
+ if (config != null) {
428
+ if (!synchronized(sharedLock) { endedDownloadIds.add(downloadId) }) {
429
+ logD(NAME, "Ignoring repeated broadcast for download: $downloadId")
430
+ return
431
+ }
432
+ val downloadStatus = downloader.checkDownloadStatus(downloadId)
433
+ val status = downloadStatus.getInt("status")
434
+ val localUri = downloadStatus.getString("localUri")
407
435
 
408
- synchronized(sharedLock) {
409
- // Drop any buffered progress that slipped past stopTaskProgress's clearPendingReport
410
- // (the polling thread may have re-added it between clearPendingReport and this lock)
411
- progressReporter.clearPendingReport(config.id)
412
- when (status) {
413
- DownloadManager.STATUS_SUCCESSFUL -> {
414
- onSuccessfulDownload(config, downloadStatus)
415
- }
416
- DownloadManager.STATUS_FAILED -> {
417
- onFailedDownload(config, downloadStatus)
418
- }
419
- }
436
+ stopTaskProgress(config.id)
420
437
 
421
- if (localUri != null) {
422
- // Prevent memory leaks from MediaScanner.
423
- // Download successful, clean task after media scanning.
424
- val paths = arrayOf(localUri)
425
- MediaScannerConnection.scanFile(context, paths, null) { _, _ ->
426
- stopTask(config.id)
427
- }
438
+ synchronized(sharedLock) {
439
+ // Drop any buffered progress that slipped past stopTaskProgress's clearPendingReport
440
+ // (the polling thread may have re-added it between clearPendingReport and this lock)
441
+ progressReporter.clearPendingReport(config.id)
442
+ when (status) {
443
+ DownloadManager.STATUS_SUCCESSFUL -> {
444
+ onSuccessfulDownload(config, downloadStatus)
445
+ }
446
+ DownloadManager.STATUS_FAILED -> {
447
+ onFailedDownload(config, downloadStatus)
448
+ }
449
+ }
450
+
451
+ if (localUri != null) {
452
+ // Prevent memory leaks from MediaScanner.
453
+ // Download successful, clean task after media scanning.
454
+ val paths = arrayOf(localUri)
455
+ MediaScannerConnection.scanFile(context, paths, null) { _, _ ->
456
+ if (status == DownloadManager.STATUS_SUCCESSFUL) {
457
+ // Not stopTask: DownloadManager.remove() deletes the downloaded file too
458
+ releaseCompletedTask(config.id)
428
459
  } else {
429
- // Download failed, clean task.
430
460
  stopTask(config.id)
431
461
  }
462
+ // Cleaned up: a later broadcast finds no config
463
+ synchronized(sharedLock) { endedDownloadIds.remove(downloadId) }
432
464
  }
465
+ } else {
466
+ // Download failed, clean task.
467
+ stopTask(config.id)
468
+ endedDownloadIds.remove(downloadId)
433
469
  }
434
470
  }
435
471
  }
436
-
437
- compatRegisterReceiver(reactContext, downloadReceiver!!, filter, true)
438
- isReceiverRegistered = true
439
472
  }
440
473
 
441
474
  // TAKEN FROM
@@ -444,20 +477,24 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
444
477
  context: Context,
445
478
  receiver: BroadcastReceiver,
446
479
  filter: IntentFilter,
447
- exported: Boolean
480
+ exported: Boolean,
481
+ broadcastPermission: String? = null
448
482
  ) {
449
483
  if (Build.VERSION.SDK_INT >= 34 && context.applicationInfo.targetSdkVersion >= 34) {
450
484
  context.registerReceiver(
451
485
  receiver,
452
486
  filter,
487
+ broadcastPermission,
488
+ null,
453
489
  if (exported) Context.RECEIVER_EXPORTED else Context.RECEIVER_NOT_EXPORTED
454
490
  )
455
491
  } else {
456
- context.registerReceiver(receiver, filter)
492
+ context.registerReceiver(receiver, filter, broadcastPermission, null)
457
493
  }
458
494
  }
459
495
 
460
496
  private fun unregisterDownloadReceiver() {
497
+ downloader.downloadEndedHandler = null
461
498
  downloadReceiver?.let {
462
499
  try {
463
500
  reactContext.unregisterReceiver(it)
@@ -469,6 +506,10 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
469
506
  }
470
507
  }
471
508
 
509
+ // False once the download was paused, stopped or finished: all of them remove it
510
+ private fun isTracked(downloadId: Long, config: RNBGDTaskConfig): Boolean =
511
+ synchronized(sharedLock) { downloadIdToConfig[downloadId] === config }
512
+
472
513
  private fun resumeTasks(downloadId: Long, config: RNBGDTaskConfig) {
473
514
  Thread {
474
515
  try {
@@ -476,14 +517,28 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
476
517
  var bytesTotal: Long = 0
477
518
 
478
519
  if (!config.reportedBegin) {
479
- val onBeginCallable = OnBegin(config, this::onBeginDownload)
480
- val onBeginFuture = cachedExecutorPool.submit(onBeginCallable)
481
- val onBeginState = onBeginFuture.get()
482
- bytesTotal = onBeginState.expectedBytes
520
+ val requestHeaders = synchronized(sharedLock) { configIdToHeaders[config.id] } ?: emptyMap()
521
+ // The HEAD request can take a while; a download that ended meanwhile gets no begin
522
+ val onBegin = BeginCallback { configId, headers, expectedBytes ->
523
+ if (isTracked(downloadId, config)) onBeginDownload(configId, headers, expectedBytes)
524
+ }
525
+ val onBeginCallable = OnBegin(config, onBegin, requestHeaders)
526
+ try {
527
+ bytesTotal = cachedExecutorPool.submit(onBeginCallable).get().expectedBytes
528
+ } catch (e: Exception) {
529
+ // The HEAD request is only for the size; some servers reject it (e.g. presigned
530
+ // GET URLs). Report begin with an unknown size and still track progress.
531
+ logW(NAME, "resumeTasks: HEAD request failed for ${config.id}: ${e.message}")
532
+ bytesTotal = -1
533
+ onBegin.onBegin(config.id, Arguments.createMap(), -1)
534
+ }
483
535
 
484
- config.reportedBegin = true
485
- downloadIdToConfig[downloadId] = config
486
- saveDownloadIdToConfigMap()
536
+ synchronized(sharedLock) {
537
+ // Writing it back would list a stopped or finished download again on every launch
538
+ if (downloadIdToConfig[downloadId] !== config) return@Thread
539
+ config.reportedBegin = true
540
+ saveDownloadIdToConfigMap()
541
+ }
487
542
  }
488
543
 
489
544
  val onProgressCallable = OnProgress(
@@ -494,8 +549,10 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
494
549
  bytesTotal,
495
550
  this::onProgressDownload
496
551
  )
497
- val onProgressFuture = cachedExecutorPool.submit(onProgressCallable)
498
- configIdToProgressFuture[config.id] = onProgressFuture
552
+ synchronized(sharedLock) {
553
+ if (downloadIdToConfig[downloadId] !== config) return@Thread
554
+ configIdToProgressFuture[config.id] = cachedExecutorPool.submit(onProgressCallable)
555
+ }
499
556
  } catch (e: Exception) {
500
557
  logE(NAME, "resumeTasks: ${Log.getStackTraceString(e)}")
501
558
  }
@@ -554,45 +611,49 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
554
611
  * If the app is force-stopped, restoreRecoverableDownloads() uses this snapshot to
555
612
  * surface the download again via getExistingDownloadTasks.
556
613
  */
557
- private fun maybeSnapshotActiveResumable(configId: String, bytesDownloaded: Long, bytesTotal: Long) {
558
- val now = System.currentTimeMillis()
559
- val last = configIdToLastSnapshotMs[configId] ?: 0L
560
- if (now - last < DownloadConstants.RECOVERY_SNAPSHOT_INTERVAL_MS) {
561
- return
562
- }
563
- configIdToLastSnapshotMs[configId] = now
564
-
565
- // The active state lives in the foreground-service ResumableDownloader (Android < 14)
566
- // or, on Android 14+, in the UIDT job. Check both so force-stop recovery works on
567
- // every supported version.
568
- val state = downloader.getActiveResumableDownloads()[configId]
569
- ?: (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
570
- UIDTDownloadJobService.getJobDownloadState(configId)
571
- else null)
572
- ?: return
573
- val headers = configIdToHeaders[configId] ?: state.headers
574
- val metadata = configIdToMetadata[configId] ?: "{}"
575
- // Persisted fallback: the UIDT job extras survive process death for jobs the
576
- // JobScheduler restarted in a fresh process; the download state carries the
577
- // flag on the foreground-service path.
578
- val persistedIsAllowedOverMetered =
579
- (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
580
- UIDTDownloadJobService.getJobIsAllowedOverMetered(configId)
581
- else null)
582
- ?: state.isAllowedOverMetered
583
-
584
- downloader.saveActiveDownloadSnapshot(
585
- Downloader.PausedDownloadInfo(
586
- configId = configId,
587
- url = state.url,
588
- destination = state.destination,
589
- headers = headers,
590
- bytesDownloaded = bytesDownloaded,
591
- bytesTotal = bytesTotal,
592
- metadata = metadata,
593
- isAllowedOverMetered = resolveIsAllowedOverMetered(configId, persistedIsAllowedOverMetered)
614
+ private fun maybeSnapshotActiveResumable(configId: String, bytesDownloaded: Long, bytesTotal: Long, force: Boolean = false) {
615
+ // Runs on download threads: the maps and the load-modify-save of the snapshot
616
+ // store must not interleave with another download's save or a cleanup
617
+ synchronized(sharedLock) {
618
+ val now = System.currentTimeMillis()
619
+ val last = configIdToLastSnapshotMs[configId] ?: 0L
620
+ if (!force && now - last < DownloadConstants.RECOVERY_SNAPSHOT_INTERVAL_MS) {
621
+ return
622
+ }
623
+ configIdToLastSnapshotMs[configId] = now
624
+
625
+ // The active state lives in the foreground-service ResumableDownloader (Android < 14)
626
+ // or, on Android 14+, in the UIDT job. Check both so force-stop recovery works on
627
+ // every supported version.
628
+ val state = downloader.getActiveResumableDownloads()[configId]
629
+ ?: (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
630
+ UIDTDownloadJobService.getJobDownloadState(configId)
631
+ else null)
632
+ ?: return
633
+ val headers = configIdToHeaders[configId] ?: state.headers
634
+ val metadata = configIdToMetadata[configId] ?: "{}"
635
+ // Persisted fallback: the UIDT job extras survive process death for jobs the
636
+ // JobScheduler restarted in a fresh process; the download state carries the
637
+ // flag on the foreground-service path.
638
+ val persistedIsAllowedOverMetered =
639
+ (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
640
+ UIDTDownloadJobService.getJobIsAllowedOverMetered(configId)
641
+ else null)
642
+ ?: state.isAllowedOverMetered
643
+
644
+ downloader.saveActiveDownloadSnapshot(
645
+ Downloader.PausedDownloadInfo(
646
+ configId = configId,
647
+ url = state.url,
648
+ destination = state.destination,
649
+ headers = headers,
650
+ bytesDownloaded = bytesDownloaded,
651
+ bytesTotal = bytesTotal,
652
+ metadata = metadata,
653
+ isAllowedOverMetered = resolveIsAllowedOverMetered(configId, persistedIsAllowedOverMetered)
654
+ )
594
655
  )
595
- )
656
+ }
596
657
  }
597
658
 
598
659
  fun download(options: ReadableMap) {
@@ -629,10 +690,11 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
629
690
  } else null
630
691
 
631
692
  val progressIntervalScope = options.getInt("progressInterval")
632
- val progressMinBytesScope = options.getDouble("progressMinBytes").toLong()
633
- if (progressIntervalScope > 0 || progressMinBytesScope > 0) {
693
+ // 0 is a valid value (percentage only), so it has to be applied too
694
+ val progressMinBytesScope = if (options.hasKey("progressMinBytes")) options.getDouble("progressMinBytes").toLong() else -1L
695
+ if (progressIntervalScope > 0 || progressMinBytesScope >= 0) {
634
696
  val newInterval = if (progressIntervalScope > 0) progressIntervalScope.toLong() else progressReporter.getProgressInterval()
635
- val newMinBytes = if (progressMinBytesScope > 0) progressMinBytesScope else progressReporter.getProgressMinBytes()
697
+ val newMinBytes = if (progressMinBytesScope >= 0) progressMinBytesScope else progressReporter.getProgressMinBytes()
636
698
  progressReporter.configure(newInterval, newMinBytes)
637
699
  // Sync notification update interval with progress interval for Android 14+
638
700
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
@@ -698,10 +760,6 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
698
760
  // DownloadManager requires external storage for downloads
699
761
  // Use app's private external files directory: /storage/emulated/0/Android/data/<package>/files/
700
762
  // This keeps files private to the app while being compatible with DownloadManager
701
- val uuid = (System.currentTimeMillis() and 0xfffffff).toInt()
702
- val extension = MimeTypeMap.getFileExtensionFromUrl(destination)
703
- val filename = "$uuid.$extension"
704
-
705
763
  // Get external files directory and validate it's a proper external storage path
706
764
  val externalFilesDir = reactContext.getExternalFilesDir(null)
707
765
  val isValidExternalPath = externalFilesDir != null &&
@@ -818,22 +876,13 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
818
876
  startWithResumableDownloader()
819
877
  }
820
878
  } else {
821
- // External files directory path is invalid or null
822
- // Try setDestinationInExternalFilesDir as fallback, then ResumableDownloader if that fails
879
+ // External files directory path is invalid or null (e.g. OnePlus devices returning
880
+ // /data/local/tmp/external/). DownloadManager could only save under its own name in
881
+ // the external files dir, not at the destination, so the completed file wouldn't be
882
+ // where the task expects it. ResumableDownloader writes to the destination directly.
823
883
  logW(NAME, "External files directory path may be invalid for DownloadManager: ${externalFilesDir?.absolutePath}")
824
-
825
- try {
826
- // Try standard setDestinationInExternalFilesDir - may work on some devices
827
- request.setDestinationInExternalFilesDir(reactContext, null, filename)
828
- startDownloadManagerDownload(downloader.download(request))
829
- logD(NAME, "Using setDestinationInExternalFilesDir for download: $id")
830
- } catch (e: Exception) {
831
- // DownloadManager failed - fall back to ResumableDownloader
832
- // This handles OnePlus and other devices that return paths like /data/local/tmp/external/
833
- logW(NAME, "DownloadManager failed with: ${e.message}")
834
- logD(NAME, "Using ResumableDownloader as fallback for download: $id")
835
- startWithResumableDownloader()
836
- }
884
+ logD(NAME, "Using ResumableDownloader for download: $id")
885
+ startWithResumableDownloader()
837
886
  }
838
887
  }
839
888
 
@@ -841,6 +890,8 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
841
890
  // If it's already using ResumableDownloader, it pauses the HTTP connection.
842
891
  fun pauseTask(configId: String) {
843
892
  synchronized(sharedLock) {
893
+ // Progress buffered before the pause would otherwise go out with another task's batch
894
+ progressReporter.clearPendingReport(configId)
844
895
  // First check if it's an active resumable download
845
896
  if (downloader.isResumableDownload(configId)) {
846
897
  // Get state before pausing - check both UIDT jobs and regular service
@@ -999,6 +1050,16 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
999
1050
  }
1000
1051
  }
1001
1052
 
1053
+ /**
1054
+ * Drop the bookkeeping for a download that finished, keeping its file.
1055
+ */
1056
+ private fun releaseCompletedTask(configId: String) {
1057
+ synchronized(sharedLock) {
1058
+ stopTaskProgress(configId)
1059
+ cleanupDownloadState(configId, configIdToDownloadId[configId], removePausedState = false)
1060
+ }
1061
+ }
1062
+
1002
1063
  fun completeHandler(configId: String) {
1003
1064
  // Firebase Performance compatibility: Add defensive programming to prevent crashes
1004
1065
  // when Firebase Performance SDK is installed and uses bytecode instrumentation
@@ -1096,6 +1157,13 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1096
1157
  processedIds.add(config.id)
1097
1158
  configIdToDownloadId[config.id] = downloadId
1098
1159
  progressReporter.setPercent(config.id, percent)
1160
+
1161
+ if (status == DownloadManager.STATUS_SUCCESSFUL) {
1162
+ // Finished while the app wasn't running, so no event was sent; it's
1163
+ // reported here as done once, then forgotten so it isn't listed again
1164
+ // on every launch (and a later stop can't remove its file)
1165
+ releaseCompletedTask(config.id)
1166
+ }
1099
1167
  }
1100
1168
  } else if (downloadId != null) {
1101
1169
  downloader.cancel(downloadId)
@@ -1165,6 +1233,25 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1165
1233
  processedIds.add(configId)
1166
1234
  }
1167
1235
 
1236
+ // Phase 3b: Downloads that finished while the app wasn't running (Android 14+ jobs
1237
+ // restarted in a process without the app). Reported once, as completed
1238
+ for ((configId, info) in downloader.takeFinishedDownloads()) {
1239
+ if (processedIds.contains(configId)) {
1240
+ continue
1241
+ }
1242
+
1243
+ val params = Arguments.createMap()
1244
+ params.putString("id", configId)
1245
+ params.putString("metadata", info.metadata)
1246
+ params.putInt("state", DownloadConstants.TASK_COMPLETED)
1247
+ params.putDouble("bytesDownloaded", info.bytesDownloaded.toDouble())
1248
+ params.putDouble("bytesTotal", info.bytesDownloaded.toDouble())
1249
+ params.putString("destination", info.destination)
1250
+
1251
+ foundTasks.pushMap(params)
1252
+ processedIds.add(configId)
1253
+ }
1254
+
1168
1255
  // Phase 4: Add active resumable downloads (in-progress via ResumableDownloader).
1169
1256
  // These run in the foreground service (Android < 14) and are invisible to
1170
1257
  // DownloadManager, so without this phase getExistingDownloadTasks misses them
@@ -1348,20 +1435,41 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1348
1435
  uploadProgressReporter.reportProgress(id, bytesUploaded, bytesTotal)
1349
1436
  }
1350
1437
 
1351
- override fun onComplete(id: String, responseCode: Int, responseBody: String, bytesUploaded: Long, bytesTotal: Long) {
1438
+ override fun onPartComplete(id: String, part: UploadPartResult) {
1439
+ synchronized(sharedLock) {
1440
+ uploadConfigs[id]?.let { config ->
1441
+ // A new list: the persisted one may be serialized concurrently
1442
+ config.completedParts = config.completedParts.orEmpty() + part
1443
+ storageManager.saveUploadConfigs(uploadConfigs)
1444
+ }
1445
+ }
1446
+ }
1447
+
1448
+ override fun onComplete(
1449
+ id: String,
1450
+ responseCode: Int,
1451
+ responseBody: String,
1452
+ responseHeaders: Map<String, String>,
1453
+ parts: List<UploadPartResult>?,
1454
+ bytesUploaded: Long,
1455
+ bytesTotal: Long
1456
+ ) {
1352
1457
  synchronized(sharedLock) {
1353
1458
  uploadConfigs[id]?.state = DownloadConstants.TASK_COMPLETED
1354
1459
  uploadConfigs.remove(id)
1460
+ // Progress still buffered must not arrive after uploadComplete
1461
+ uploadProgressReporter.clearDownloadState(id)
1355
1462
  // Remove from persistent storage on completion
1356
1463
  storageManager.saveUploadConfigs(uploadConfigs)
1357
1464
  }
1358
- uploadEventEmitter.emitComplete(id, responseCode, responseBody, bytesUploaded, bytesTotal)
1465
+ uploadEventEmitter.emitComplete(id, responseCode, responseBody, responseHeaders, parts, bytesUploaded, bytesTotal)
1359
1466
  }
1360
1467
 
1361
1468
  override fun onError(id: String, error: String, errorCode: Int) {
1362
1469
  synchronized(sharedLock) {
1363
1470
  uploadConfigs[id]?.state = DownloadConstants.TASK_CANCELING
1364
1471
  uploadConfigs.remove(id)
1472
+ uploadProgressReporter.clearDownloadState(id)
1365
1473
  // Remove from persistent storage on error
1366
1474
  storageManager.saveUploadConfigs(uploadConfigs)
1367
1475
  }
@@ -1420,12 +1528,18 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1420
1528
  result
1421
1529
  } else null
1422
1530
 
1531
+ val partUrls = if (options.hasKey("partUrls") && !options.isNull("partUrls")) {
1532
+ options.getArray("partUrls")?.let { array -> (0 until array.size()).mapNotNull { array.getString(it) } }
1533
+ } else null
1534
+ val partSize = if (options.hasKey("partSize") && !options.isNull("partSize")) options.getDouble("partSize").toLong() else 0L
1535
+
1423
1536
  // Progress settings
1424
1537
  val progressIntervalScope = options.getInt("progressInterval")
1425
- val progressMinBytesScope = options.getDouble("progressMinBytes").toLong()
1426
- if (progressIntervalScope > 0 || progressMinBytesScope > 0) {
1538
+ // 0 is a valid value (percentage only), so it has to be applied too
1539
+ val progressMinBytesScope = if (options.hasKey("progressMinBytes")) options.getDouble("progressMinBytes").toLong() else -1L
1540
+ if (progressIntervalScope > 0 || progressMinBytesScope >= 0) {
1427
1541
  val newInterval = if (progressIntervalScope > 0) progressIntervalScope.toLong() else uploadProgressReporter.getProgressInterval()
1428
- val newMinBytes = if (progressMinBytesScope > 0) progressMinBytesScope else uploadProgressReporter.getProgressMinBytes()
1542
+ val newMinBytes = if (progressMinBytesScope >= 0) progressMinBytesScope else uploadProgressReporter.getProgressMinBytes()
1429
1543
  uploadProgressReporter.configure(newInterval, newMinBytes)
1430
1544
  }
1431
1545
 
@@ -1443,7 +1557,9 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1443
1557
  headers = headers,
1444
1558
  fieldName = fieldName,
1445
1559
  mimeType = mimeType,
1446
- parameters = parameters
1560
+ parameters = parameters,
1561
+ partUrls = partUrls,
1562
+ partSize = partSize
1447
1563
  )
1448
1564
 
1449
1565
  synchronized(sharedLock) {
@@ -1459,6 +1575,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1459
1575
  fun pauseUploadTask(configId: String) {
1460
1576
  synchronized(sharedLock) {
1461
1577
  uploadConfigs[configId]?.state = DownloadConstants.TASK_SUSPENDED
1578
+ uploadProgressReporter.clearPendingReport(configId)
1462
1579
  // Persist state change
1463
1580
  storageManager.saveUploadConfigs(uploadConfigs)
1464
1581
  }
@@ -1467,12 +1584,21 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1467
1584
  }
1468
1585
 
1469
1586
  fun resumeUploadTask(configId: String) {
1470
- synchronized(sharedLock) {
1587
+ val config = synchronized(sharedLock) {
1471
1588
  uploadConfigs[configId]?.state = DownloadConstants.TASK_RUNNING
1472
1589
  // Persist state change
1473
1590
  storageManager.saveUploadConfigs(uploadConfigs)
1591
+ // A resumed upload starts over, so progress thresholds start from 0 too
1592
+ uploadProgressReporter.clearDownloadState(configId)
1593
+ uploadProgressReporter.initializeDownload(configId)
1594
+ uploadConfigs[configId]
1595
+ }
1596
+ if (!uploader.resume(configId, uploadListener) && config != null && uploader.getState(configId) == null) {
1597
+ // Restored after a restart: nothing is in memory to resume, so upload it again
1598
+ uploader.startUpload(config, uploadListener)
1599
+ logD(NAME, "Restarted restored upload: $configId")
1600
+ return
1474
1601
  }
1475
- uploader.resume(configId, uploadListener)
1476
1602
  logD(NAME, "Resumed upload: $configId")
1477
1603
  }
1478
1604
 
@@ -504,7 +504,8 @@ class ResumableDownloadService : Service() {
504
504
  }
505
505
 
506
506
  private fun acquireWakeLock() {
507
- if (wakeLock == null) {
507
+ // Not just a null check: the lock times out, and an expired one must be taken again
508
+ if (wakeLock?.isHeld != true) {
508
509
  val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
509
510
  wakeLock = powerManager.newWakeLock(
510
511
  PowerManager.PARTIAL_WAKE_LOCK,