@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
@@ -17,6 +17,11 @@ import java.util.concurrent.atomic.AtomicLong
17
17
  */
18
18
  class ResumableDownloader {
19
19
 
20
+ // How long a transfer may stall before it's retried, and the waits before each retry;
21
+ // shorter in tests
22
+ internal var readTimeoutMs = DownloadConstants.READ_TIMEOUT_MS
23
+ internal var networkRetryDelaysMs = DownloadConstants.NETWORK_RETRY_DELAYS_MS
24
+
20
25
  companion object {
21
26
  private const val TAG = "ResumableDownloader"
22
27
 
@@ -390,7 +395,31 @@ class ResumableDownloader {
390
395
  fun getBytesTotal(id: String): Long = activeDownloads[id]?.bytesTotal ?: -1
391
396
 
392
397
  private fun downloadWithResume(state: DownloadState, listener: DownloadListener, expectedSessionId: Long) {
393
- val result = executeDownload(state, listener, expectedSessionId)
398
+ var result = executeDownload(state, listener, expectedSessionId)
399
+
400
+ // A transfer the network cut off continues from the partial file after a short wait,
401
+ // as DownloadManager and iOS do, instead of failing the download
402
+ var retries = 0
403
+ while (result is DownloadResult.Error && result.isNetworkFailure) {
404
+ // A redirect replaces the state
405
+ val current = activeDownloads[state.id] ?: state
406
+ val bytesBefore = current.bytesDownloaded.get()
407
+ if (retries >= networkRetryDelaysMs.size) {
408
+ RNBackgroundDownloaderModuleImpl.logE(TAG, "Download error after $retries retries: ${result.message}")
409
+ listener.onError(result.id, result.message, result.errorCode)
410
+ return
411
+ }
412
+ RNBackgroundDownloaderModuleImpl.logW(TAG, "Network failure for ${state.id} (${result.message}), retry ${retries + 1} at $bytesBefore bytes")
413
+ if (!waitBeforeRetry(current, expectedSessionId, networkRetryDelaysMs[retries])) {
414
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Retry abandoned, download paused or cancelled: ${state.id}")
415
+ return
416
+ }
417
+ // The file holds exactly what was received; continue from there
418
+ current.bytesDownloaded.set(File(current.destination).let { if (it.exists()) it.length() else 0L })
419
+ result = executeDownload(current, listener, expectedSessionId)
420
+ val progressed = (activeDownloads[state.id] ?: current).bytesDownloaded.get() > bytesBefore
421
+ retries = if (progressed) 0 else retries + 1
422
+ }
394
423
 
395
424
  // Handle the result by notifying the listener
396
425
  when (result) {
@@ -415,11 +444,40 @@ class ResumableDownloader {
415
444
  }
416
445
  }
417
446
 
447
+ // False if the download was paused, cancelled or restarted meanwhile
448
+ private fun waitBeforeRetry(state: DownloadState, expectedSessionId: Long, delayMs: Long): Boolean {
449
+ val deadline = System.currentTimeMillis() + delayMs
450
+ while (true) {
451
+ if (state.sessionId.get() != expectedSessionId || state.isCancelled.get() || state.isPaused.get()) {
452
+ return false
453
+ }
454
+ val remaining = deadline - System.currentTimeMillis()
455
+ if (remaining <= 0) return true
456
+ try {
457
+ Thread.sleep(minOf(remaining, 200L))
458
+ } catch (e: InterruptedException) {
459
+ return false
460
+ }
461
+ }
462
+ }
463
+
464
+ private fun isNetworkFailure(e: Exception): Boolean =
465
+ e is java.net.SocketException ||
466
+ e is java.net.UnknownHostException ||
467
+ e is java.io.EOFException ||
468
+ // "unexpected end of stream" when the connection drops mid-body
469
+ e is java.net.ProtocolException
470
+
418
471
  /**
419
472
  * Execute the download and return a DownloadResult.
420
473
  * This method handles all download logic and returns a type-safe result.
421
474
  */
422
- private fun executeDownload(state: DownloadState, listener: DownloadListener, expectedSessionId: Long): DownloadResult {
475
+ private fun executeDownload(
476
+ state: DownloadState,
477
+ listener: DownloadListener,
478
+ expectedSessionId: Long,
479
+ redirectsLeft: Int = DownloadConstants.MAX_SCHEME_REDIRECTS
480
+ ): DownloadResult {
423
481
  var connection: HttpURLConnection? = null
424
482
  var inputStream: InputStream? = null
425
483
  var outputStream: FileOutputStream? = null
@@ -443,7 +501,7 @@ class ResumableDownloader {
443
501
  // Store connection reference so it can be disconnected on cancel
444
502
  state.connection = connection
445
503
  connection.connectTimeout = DownloadConstants.CONNECT_TIMEOUT_MS
446
- connection.readTimeout = DownloadConstants.READ_TIMEOUT_MS
504
+ connection.readTimeout = readTimeoutMs
447
505
  connection.requestMethod = "GET"
448
506
 
449
507
  // Check again after connection setup
@@ -519,17 +577,33 @@ class ResumableDownloader {
519
577
  HttpURLConnection.HTTP_MOVED_TEMP,
520
578
  HttpURLConnection.HTTP_SEE_OTHER,
521
579
  307, 308 -> {
522
- // Handle redirect
523
- val newUrl = connection.getHeaderField("Location")
524
- if (newUrl != null) {
525
- connection.disconnect()
526
- // Create new state with updated URL
527
- // Note: We preserve bytesDownloaded since the redirect should point to the same resource.
528
- // If the new server doesn't support Range headers, the HTTP_OK case above will reset it.
529
- val newState = state.copyWithUrl(newUrl)
530
- activeDownloads[state.id] = newState
531
- return executeDownload(newState, listener, expectedSessionId)
580
+ // HttpURLConnection follows same-scheme redirects itself, so this only
581
+ // sees ones that switch between http and https - which the platform
582
+ // refuses on purpose. Follow only http -> https upgrades, a bounded
583
+ // number of times, and drop credentials when the host changes.
584
+ val location = connection.getHeaderField("Location")
585
+ val newUrl = location?.let { runCatching { URL(URL(state.url), it) }.getOrNull() }
586
+ val currentUrl = URL(state.url)
587
+ if (newUrl == null || redirectsLeft <= 0 ||
588
+ !currentUrl.protocol.equals("http", ignoreCase = true) ||
589
+ !newUrl.protocol.equals("https", ignoreCase = true)
590
+ ) {
591
+ val error = DownloadResult.httpError(state.id, responseCode, "Refusing to follow redirect to $location")
592
+ listener.onError(state.id, error.message, error.errorCode)
593
+ return error
532
594
  }
595
+ connection.disconnect()
596
+ val headers = if (newUrl.host.equals(currentUrl.host, ignoreCase = true)) {
597
+ state.headers
598
+ } else {
599
+ HeaderUtils.withoutCredentials(state.headers)
600
+ }
601
+ // Create new state with updated URL
602
+ // Note: We preserve bytesDownloaded since the redirect should point to the same resource.
603
+ // If the new server doesn't support Range headers, the HTTP_OK case above will reset it.
604
+ val newState = state.copyWithUrl(newUrl.toString(), headers)
605
+ activeDownloads[state.id] = newState
606
+ return executeDownload(newState, listener, expectedSessionId, redirectsLeft - 1)
533
607
  }
534
608
  416 -> {
535
609
  // Range Not Satisfiable - file might be complete or server doesn't support ranges
@@ -640,6 +714,16 @@ class ResumableDownloader {
640
714
  val bytesDownloaded = state.bytesDownloaded.get()
641
715
  val bytesTotal = state.bytesTotal
642
716
 
717
+ // The connection closed before the whole body arrived (some servers and proxies end
718
+ // it without an error): not done, the rest has to be fetched
719
+ if (bytesTotal > 0 && bytesDownloaded < bytesTotal) {
720
+ return DownloadResult.Error(
721
+ state.id,
722
+ "Connection closed at $bytesDownloaded of $bytesTotal bytes",
723
+ isNetworkFailure = true
724
+ )
725
+ }
726
+
643
727
  activeDownloads.remove(state.id)
644
728
  listener.onComplete(state.id, state.destination, bytesDownloaded, bytesTotal)
645
729
  return DownloadResult.Success(state.id, state.destination, bytesDownloaded, bytesTotal)
@@ -660,7 +744,12 @@ class ResumableDownloader {
660
744
  state.sessionId.get() != expectedSessionId -> DownloadResult.SessionInvalidated(state.id)
661
745
  state.isCancelled.get() -> DownloadResult.Cancelled(state.id)
662
746
  state.isPaused.get() -> DownloadResult.Paused(state.id, state.bytesDownloaded.get(), state.bytesTotal)
663
- else -> DownloadResult.SessionInvalidated(state.id)
747
+ else -> {
748
+ // Not a pause or cancel, so a read or connect timeout (SocketTimeoutException is an
749
+ // InterruptedIOException). downloadWithResume retries it, then reports it
750
+ val errorCode = if (e is java.net.SocketTimeoutException) DownloadConstants.ERR_TIMED_OUT else -1
751
+ DownloadResult.fromException(state.id, e, errorCode).copy(isNetworkFailure = true)
752
+ }
664
753
  }
665
754
  } catch (e: Exception) {
666
755
  // Determine result based on state - expected exceptions vs real errors
@@ -677,6 +766,10 @@ class ResumableDownloader {
677
766
  RNBackgroundDownloaderModuleImpl.logD(TAG, "Download stopped (paused): ${state.id} - ${e.message}")
678
767
  DownloadResult.Paused(state.id, state.bytesDownloaded.get(), state.bytesTotal)
679
768
  }
769
+ isNetworkFailure(e) -> {
770
+ // downloadWithResume retries it, then reports it
771
+ DownloadResult.fromException(state.id, e).copy(isNetworkFailure = true)
772
+ }
680
773
  else -> {
681
774
  // Unexpected error - log with stack trace and report to listener
682
775
  RNBackgroundDownloaderModuleImpl.logE(TAG, "Download error: ${e.message}")
@@ -696,12 +789,12 @@ class ResumableDownloader {
696
789
  }
697
790
  }
698
791
 
699
- private fun DownloadState.copyWithUrl(url: String): DownloadState {
792
+ private fun DownloadState.copyWithUrl(url: String, headers: Map<String, String>): DownloadState {
700
793
  return DownloadState(
701
794
  id = this.id,
702
795
  url = url,
703
796
  destination = this.destination,
704
- headers = this.headers,
797
+ headers = headers,
705
798
  isPaused = this.isPaused,
706
799
  isCancelled = this.isCancelled,
707
800
  bytesDownloaded = this.bytesDownloaded,
@@ -15,7 +15,9 @@ import com.eko.uidt.UIDTJobRegistry
15
15
  import com.eko.uidt.UIDTNotificationIds
16
16
  import com.eko.uidt.UIDTNotificationManager
17
17
  import com.eko.utils.ProgressUtils
18
+ import com.eko.utils.StorageManager
18
19
  import org.json.JSONObject
20
+ import java.io.File
19
21
 
20
22
  /**
21
23
  * A JobService that uses User-Initiated Data Transfer (UIDT) for background downloads.
@@ -159,6 +161,15 @@ class UIDTDownloadJobService : JobService() {
159
161
  var downloadListener: ResumableDownloader.DownloadListener?
160
162
  get() = UIDTJobRegistry.downloadListener
161
163
  set(value) { UIDTJobRegistry.downloadListener = value }
164
+
165
+ /**
166
+ * The byte a job continues from. When resuming, the partial file is the source of
167
+ * truth: a saved offset can lag the bytes written (it's recorded when the job stops,
168
+ * or not at all if the process died), and appending from a lower offset duplicates
169
+ * data. No file means start over.
170
+ */
171
+ internal fun resumeStartByte(savedStartByte: Long, destination: String): Long =
172
+ if (savedStartByte > 0) File(destination).let { if (it.exists()) it.length() else 0L } else 0L
162
173
  }
163
174
 
164
175
  private var wakeLock: PowerManager.WakeLock? = null
@@ -211,31 +222,32 @@ class UIDTDownloadJobService : JobService() {
211
222
  // In-memory pendingHeaders is populated in the same process (scheduleDownload / onStopJob).
212
223
  // The disk-persisted resume state is the fallback for a fresh process after a restart.
213
224
  val inMemoryHeaders = UIDTJobRegistry.pendingHeaders.remove(configId)
225
+ // Kept on disk until the download completes, fails or is cancelled (those clear it):
226
+ // if the process dies mid-transfer, the restarted job still needs the headers
214
227
  val diskResumeState = UIDTJobRegistry.loadResumeState(this, configId)
215
- // Clear disk state now that we've consumed it.
216
- UIDTJobRegistry.clearResumeState(this, configId)
217
228
 
218
229
  val headers: Map<String, String>
219
- val startByte: Long
230
+ val savedStartByte: Long
220
231
  when {
221
232
  inMemoryHeaders != null -> {
222
233
  // Same-process restart: use in-memory headers.
223
234
  // Prefer the disk byte position if it is more advanced than the extras
224
235
  // (written by onStopJob with the actual download offset).
225
236
  headers = inMemoryHeaders
226
- startByte = if (diskResumeState != null && diskResumeState.second > startByteFromExtras)
237
+ savedStartByte = if (diskResumeState != null && diskResumeState.second > startByteFromExtras)
227
238
  diskResumeState.second else startByteFromExtras
228
239
  }
229
240
  diskResumeState != null -> {
230
241
  // Cross-process restart: use the persisted state.
231
242
  headers = diskResumeState.first
232
- startByte = diskResumeState.second
243
+ savedStartByte = diskResumeState.second
233
244
  }
234
245
  else -> {
235
246
  headers = emptyMap()
236
- startByte = startByteFromExtras
247
+ savedStartByte = startByteFromExtras
237
248
  }
238
249
  }
250
+ val startByte = resumeStartByte(savedStartByte, destination)
239
251
  RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob: configId=$configId, startByte=$startByte, headers=${headers.size}")
240
252
 
241
253
  // Create notification for UIDT job (required)
@@ -475,8 +487,14 @@ class UIDTDownloadJobService : JobService() {
475
487
  // took its ID from this offset, so it can go back to the pool
476
488
  UIDTNotificationIds.release(id)
477
489
 
478
- // Notify external listener
479
- UIDTJobRegistry.downloadListener?.onComplete(id, location, bytesDownloaded, bytesTotal)
490
+ // Notify external listener. With none (the job ran in a process without the
491
+ // app), record it so the next launch reports it as done, not as paused
492
+ val listener = UIDTJobRegistry.downloadListener
493
+ if (listener != null) {
494
+ listener.onComplete(id, location, bytesDownloaded, bytesTotal)
495
+ } else {
496
+ recordFinishedWithoutApp(id, bytesDownloaded)
497
+ }
480
498
  }
481
499
 
482
500
  override fun onError(id: String, error: String, errorCode: Int) {
@@ -523,6 +541,14 @@ class UIDTDownloadJobService : JobService() {
523
541
  }
524
542
  }
525
543
 
544
+ // The download's recovery snapshot (saved while the app was running) gets its final size,
545
+ // which recovery on the next launch takes as a finished download
546
+ private fun recordFinishedWithoutApp(configId: String, bytesDownloaded: Long) {
547
+ val storage = StorageManager(this, RNBackgroundDownloaderModuleImpl.NAME)
548
+ val snapshot = storage.loadActiveDownloads()[configId] ?: return
549
+ storage.saveActiveDownload(snapshot.copy(bytesDownloaded = bytesDownloaded, bytesTotal = bytesDownloaded))
550
+ }
551
+
526
552
  private fun acquireWakeLock() {
527
553
  if (wakeLock == null) {
528
554
  val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
@@ -3,6 +3,7 @@ package com.eko
3
3
  import android.content.Context
4
4
  import android.net.ConnectivityManager
5
5
  import android.net.Network
6
+ import android.net.NetworkCapabilities
6
7
  import com.eko.utils.NetworkRequestUtils
7
8
  import java.util.concurrent.ExecutorService
8
9
  import java.util.concurrent.Executors
@@ -60,8 +61,14 @@ class UnmeteredNetworkGate(
60
61
  private val running = mutableMapOf<String, Network>()
61
62
  // Unmetered networks currently known to be available
62
63
  private val unmeteredNetworks = mutableSetOf<Network>()
64
+ // The app's default network
65
+ private var defaultNetwork: Network? = null
66
+ private var defaultCapabilities: NetworkCapabilities? = null
63
67
  @Volatile
64
68
  private var networkCallback: ConnectivityManager.NetworkCallback? = null
69
+ // Registered together with networkCallback
70
+ private var defaultNetworkCallback: ConnectivityManager.NetworkCallback? = null
71
+ private var callbackGeneration = 0
65
72
  private val executor: ExecutorService = Executors.newSingleThreadExecutor()
66
73
 
67
74
  private val connectivityManager by lazy {
@@ -87,7 +94,7 @@ class UnmeteredNetworkGate(
87
94
  waiting.add(id)
88
95
  // The onAvailable replay only fires when the callback is first
89
96
  // registered - drain explicitly for networks we already know about
90
- unmeteredNetworks.firstOrNull()?.let { startWaitingLocked(it) }
97
+ pickNetworkLocked()?.let { startWaitingLocked(it) }
91
98
  return true
92
99
  }
93
100
  }
@@ -111,7 +118,7 @@ class UnmeteredNetworkGate(
111
118
  RNBackgroundDownloaderModuleImpl.logD(TAG, "Resume of $id waits for an unmetered network")
112
119
  waiting.add(id)
113
120
  // See parkNewDownload: drain explicitly for already-known networks
114
- unmeteredNetworks.firstOrNull()?.let { startWaitingLocked(it) }
121
+ pickNetworkLocked()?.let { startWaitingLocked(it) }
115
122
  return true
116
123
  }
117
124
  }
@@ -179,7 +186,7 @@ class UnmeteredNetworkGate(
179
186
  Thread.currentThread().interrupt()
180
187
  }
181
188
  lostUnmetered = !isNetworkUnmetered(boundNetwork) ||
182
- synchronized(lock) { !unmeteredNetworks.contains(boundNetwork) }
189
+ synchronized(lock) { !isBindableLocked(boundNetwork) }
183
190
  }
184
191
 
185
192
  synchronized(lock) {
@@ -209,11 +216,23 @@ class UnmeteredNetworkGate(
209
216
  waiting.add(id)
210
217
  ensureCallbackLocked()
211
218
  // If another unmetered network is already up, restart right away
212
- unmeteredNetworks.firstOrNull()?.let { startWaitingLocked(it) }
219
+ pickNetworkLocked()?.let { startWaitingLocked(it) }
213
220
  return true
214
221
  }
215
222
  }
216
223
 
224
+ /** The registered (unmetered, default network) callbacks; for tests. */
225
+ internal fun registeredCallbacks(): Pair<ConnectivityManager.NetworkCallback?, ConnectivityManager.NetworkCallback?> {
226
+ synchronized(lock) {
227
+ return Pair(networkCallback, defaultNetworkCallback)
228
+ }
229
+ }
230
+
231
+ /** Wait until callback bodies queued so far have run; for tests. */
232
+ internal fun awaitCallbacks() {
233
+ executor.submit {}.get()
234
+ }
235
+
217
236
  /** Tear the gate down (service destroy). */
218
237
  fun shutdown() {
219
238
  synchronized(lock) {
@@ -225,8 +244,9 @@ class UnmeteredNetworkGate(
225
244
  }
226
245
 
227
246
  /**
228
- * Register the shared callback for unmetered networks (idempotent). Caller must
229
- * hold the lock. Returns false when registration failed.
247
+ * Register the shared callback for unmetered networks and the default network
248
+ * callback (idempotent). Caller must hold the lock. Returns false when
249
+ * registration failed.
230
250
  *
231
251
  * registerNetworkCallback immediately replays onAvailable for networks that
232
252
  * already satisfy the request, which arms the initial drain.
@@ -234,13 +254,19 @@ class UnmeteredNetworkGate(
234
254
  private fun ensureCallbackLocked(): Boolean {
235
255
  if (networkCallback != null) return true
236
256
 
257
+ // Callback bodies run on the executor and can still be queued when the
258
+ // callbacks are unregistered - the generation lets them drop themselves
259
+ // instead of writing stale networks into a freshly cleared state
260
+ val generation = ++callbackGeneration
261
+
237
262
  val callback = object : ConnectivityManager.NetworkCallback() {
238
263
  override fun onAvailable(network: Network) {
239
264
  runOnExecutor {
240
- RNBackgroundDownloaderModuleImpl.logD(TAG, "Unmetered network available: $network")
241
265
  synchronized(lock) {
266
+ if (generation != callbackGeneration) return@runOnExecutor
267
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Unmetered network available: $network")
242
268
  unmeteredNetworks.add(network)
243
- startWaitingLocked(network)
269
+ pickNetworkLocked()?.let { startWaitingLocked(it) }
244
270
  }
245
271
  host.onGateStateChanged()
246
272
  }
@@ -250,27 +276,111 @@ class UnmeteredNetworkGate(
250
276
  // Also delivered when a network stops satisfying the request
251
277
  // (e.g. WiFi becomes metered), not only on disconnect
252
278
  runOnExecutor {
253
- RNBackgroundDownloaderModuleImpl.logD(TAG, "Unmetered network lost: $network")
254
279
  synchronized(lock) {
280
+ if (generation != callbackGeneration) return@runOnExecutor
281
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Unmetered network lost: $network")
255
282
  unmeteredNetworks.remove(network)
256
- pauseRunningOnLocked(network)
283
+ pauseRunningLocked("Unmetered network lost") { it == network }
284
+ }
285
+ host.onGateStateChanged()
286
+ }
287
+ }
288
+ }
289
+
290
+ // Tracks the app's default network. onCapabilitiesChanged also follows
291
+ // onAvailable, including when the default switches to another network.
292
+ val defaultCallback = object : ConnectivityManager.NetworkCallback() {
293
+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
294
+ runOnExecutor {
295
+ synchronized(lock) {
296
+ if (generation != callbackGeneration) return@runOnExecutor
297
+ val changed = network != defaultNetwork ||
298
+ defaultKind(capabilities) != defaultKind(defaultCapabilities)
299
+ defaultNetwork = network
300
+ defaultCapabilities = capabilities
301
+ // Capabilities change on every signal strength update - only act
302
+ // (and refresh the notification) when something the gate uses changed
303
+ if (!changed) return@runOnExecutor
304
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Default network changed: $network")
305
+ // A VPN that came up mid-transfer makes the network underneath it
306
+ // unusable for binding - move those transfers over to the VPN
307
+ pauseRunningLocked("Default network changed") { !isBindableLocked(it) }
308
+ pickNetworkLocked()?.let { startWaitingLocked(it) }
257
309
  }
258
310
  host.onGateStateChanged()
259
311
  }
260
312
  }
313
+
314
+ override fun onLost(network: Network) {
315
+ runOnExecutor {
316
+ synchronized(lock) {
317
+ if (generation != callbackGeneration) return@runOnExecutor
318
+ if (defaultNetwork == network) {
319
+ defaultNetwork = null
320
+ defaultCapabilities = null
321
+ }
322
+ }
323
+ }
324
+ }
261
325
  }
262
326
 
263
327
  return try {
328
+ connectivityManager.registerDefaultNetworkCallback(defaultCallback)
329
+ defaultNetworkCallback = defaultCallback
264
330
  connectivityManager.registerNetworkCallback(NetworkRequestUtils.internetRequest(requireUnmetered = true), callback)
265
331
  networkCallback = callback
266
332
  RNBackgroundDownloaderModuleImpl.logD(TAG, "Registered unmetered network callback")
267
333
  true
268
334
  } catch (e: Exception) {
269
335
  RNBackgroundDownloaderModuleImpl.logE(TAG, "Failed to register network callback: ${e.message}")
336
+ defaultNetworkCallback?.let { runCatching { connectivityManager.unregisterNetworkCallback(it) } }
337
+ defaultNetworkCallback = null
338
+ callbackGeneration++
270
339
  false
271
340
  }
272
341
  }
273
342
 
343
+ /** What the gate cares about in the default network's capabilities. */
344
+ private fun defaultKind(capabilities: NetworkCapabilities?): Pair<Boolean, Boolean>? {
345
+ capabilities ?: return null
346
+ return Pair(
347
+ NetworkRequestUtils.isUnmetered(capabilities),
348
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
349
+ )
350
+ }
351
+
352
+ private fun isDefaultVpnLocked(): Boolean {
353
+ return defaultCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
354
+ }
355
+
356
+ /**
357
+ * Whether a transfer may stay bound to the network. Caller must hold the lock.
358
+ * While the default network is a VPN, only the VPN itself qualifies: binding
359
+ * to the network underneath it fails with EPERM.
360
+ */
361
+ private fun isBindableLocked(network: Network): Boolean {
362
+ if (isDefaultVpnLocked()) {
363
+ return network == defaultNetwork && NetworkRequestUtils.isUnmetered(defaultCapabilities)
364
+ }
365
+ return unmeteredNetworks.contains(network)
366
+ }
367
+
368
+ /**
369
+ * The network to start waiting downloads on, or null to keep waiting. Caller
370
+ * must hold the lock. Prefers the default network, since that's where the
371
+ * app's traffic goes. A metered VPN means waiting: binding to the network
372
+ * underneath a VPN fails with EPERM (and Android 14+'s JobScheduler waits too).
373
+ */
374
+ private fun pickNetworkLocked(): Network? {
375
+ val capabilities = defaultCapabilities
376
+ return when {
377
+ capabilities == null -> unmeteredNetworks.firstOrNull()
378
+ NetworkRequestUtils.isUnmetered(capabilities) -> defaultNetwork
379
+ capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN) -> null
380
+ else -> unmeteredNetworks.firstOrNull()
381
+ }
382
+ }
383
+
274
384
  private fun runOnExecutor(block: () -> Unit) {
275
385
  try {
276
386
  executor.execute(block)
@@ -284,9 +394,15 @@ class UnmeteredNetworkGate(
284
394
  private fun maybeUnregisterCallbackLocked() {
285
395
  if (waiting.isNotEmpty() || running.isNotEmpty()) return
286
396
  val callback = networkCallback ?: return
397
+ val defaultCallback = defaultNetworkCallback
287
398
  networkCallback = null
399
+ defaultNetworkCallback = null
400
+ callbackGeneration++
288
401
  unmeteredNetworks.clear()
402
+ defaultNetwork = null
403
+ defaultCapabilities = null
289
404
  try {
405
+ defaultCallback?.let { connectivityManager.unregisterNetworkCallback(it) }
290
406
  connectivityManager.unregisterNetworkCallback(callback)
291
407
  RNBackgroundDownloaderModuleImpl.logD(TAG, "Unregistered unmetered network callback")
292
408
  } catch (e: Exception) {
@@ -336,16 +452,17 @@ class UnmeteredNetworkGate(
336
452
  }
337
453
 
338
454
  /**
339
- * Pause gated downloads bound to a network that is no longer unmetered/available
340
- * and put them back into the waiting set. If another unmetered network is still
341
- * available they restart on it immediately. Caller must hold the lock.
455
+ * Pause gated downloads whose bound network matches `shouldPause` (lost, no
456
+ * longer unmetered, or unusable under a VPN) and put them back into the
457
+ * waiting set. If another usable network is up they restart on it immediately.
458
+ * Caller must hold the lock.
342
459
  */
343
- private fun pauseRunningOnLocked(network: Network) {
460
+ private fun pauseRunningLocked(reason: String, shouldPause: (Network) -> Boolean) {
344
461
  var movedToWaiting = false
345
462
  for ((id, boundNetwork) in running.entries.toList()) {
346
- if (boundNetwork != network) continue
463
+ if (!shouldPause(boundNetwork)) continue
347
464
  running.remove(id)
348
- RNBackgroundDownloaderModuleImpl.logD(TAG, "Unmetered network lost, pausing gated download $id")
465
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "$reason, pausing gated download $id")
349
466
  resumableDownloader.pause(id)
350
467
  resumableDownloader.getState(id)?.network = null
351
468
  // Back to waiting: auto-restarts when an unmetered network is available again
@@ -356,7 +473,7 @@ class UnmeteredNetworkGate(
356
473
  if (movedToWaiting) {
357
474
  // Another unmetered network may still be up (e.g. ethernet next to WiFi) -
358
475
  // its onAvailable already fired, so re-drain the waiting set explicitly
359
- unmeteredNetworks.firstOrNull()?.let { startWaitingLocked(it) }
476
+ pickNetworkLocked()?.let { startWaitingLocked(it) }
360
477
  }
361
478
  }
362
479
 
@@ -46,11 +46,33 @@ class UploadEventEmitter(
46
46
  /**
47
47
  * Emit an upload complete event.
48
48
  */
49
- fun emitComplete(id: String, responseCode: Int, responseBody: String, bytesUploaded: Long, bytesTotal: Long) {
49
+ fun emitComplete(
50
+ id: String,
51
+ responseCode: Int,
52
+ responseBody: String,
53
+ responseHeaders: Map<String, String>,
54
+ parts: List<UploadPartResult>?,
55
+ bytesUploaded: Long,
56
+ bytesTotal: Long
57
+ ) {
50
58
  val params = Arguments.createMap()
51
59
  params.putString("id", id)
52
60
  params.putInt("responseCode", responseCode)
53
61
  params.putString("responseBody", responseBody)
62
+ params.putMap("responseHeaders", headersMap(responseHeaders))
63
+ if (parts != null) {
64
+ val array = Arguments.createArray()
65
+ for (part in parts) {
66
+ val map = Arguments.createMap()
67
+ map.putInt("partNumber", part.partNumber)
68
+ map.putInt("responseCode", part.responseCode)
69
+ map.putString("responseBody", part.responseBody)
70
+ map.putMap("responseHeaders", headersMap(part.responseHeaders))
71
+ map.putDouble("bytes", part.bytes.toDouble())
72
+ array.pushMap(map)
73
+ }
74
+ params.putArray("parts", array)
75
+ }
54
76
  params.putDouble("bytesUploaded", bytesUploaded.toDouble())
55
77
  params.putDouble("bytesTotal", bytesTotal.toDouble())
56
78
  safeEmit(EVENT_UPLOAD_COMPLETE, params)
@@ -67,4 +89,7 @@ class UploadEventEmitter(
67
89
  safeEmit(EVENT_UPLOAD_FAILED, params)
68
90
  }
69
91
 
92
+ private fun headersMap(headers: Map<String, String>) = Arguments.createMap().apply {
93
+ headers.forEach { (key, value) -> putString(key, value) }
94
+ }
70
95
  }