@kesha-antonov/react-native-background-downloader 4.7.0 → 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 (33) hide show
  1. package/README.md +75 -32
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +5 -0
  3. package/android/src/main/java/com/eko/Downloader.kt +12 -5
  4. package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +36 -1
  5. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +94 -54
  6. package/android/src/main/java/com/eko/ResumableDownloader.kt +34 -13
  7. package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +134 -17
  8. package/android/src/main/java/com/eko/UploadEventEmitter.kt +26 -1
  9. package/android/src/main/java/com/eko/Uploader.kt +187 -17
  10. package/android/src/main/java/com/eko/handlers/OnProgress.kt +1 -1
  11. package/android/src/main/java/com/eko/utils/HeaderUtils.kt +9 -0
  12. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +29 -1
  13. package/android/src/test/java/com/eko/DownloadCompleteReceiverTest.kt +57 -0
  14. package/android/src/test/java/com/eko/ResumableDownloaderRedirectTest.kt +77 -0
  15. package/android/src/test/java/com/eko/UnmeteredNetworkGateTest.kt +248 -0
  16. package/android/src/test/java/com/eko/UploadPartRangesTest.kt +33 -0
  17. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +10 -1
  18. package/android/src/test/java/com/eko/UploaderPartsTest.kt +222 -0
  19. package/android/src/test/java/com/eko/UploaderResponseTest.kt +26 -0
  20. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +66 -0
  21. package/ios/RNBGDUploadTaskConfig.h +26 -0
  22. package/ios/RNBGDUploadTaskConfig.mm +69 -3
  23. package/ios/RNBackgroundDownloader.mm +563 -43
  24. package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
  25. package/lib/UploadTask.d.ts +5 -1
  26. package/lib/UploadTask.js +22 -4
  27. package/lib/index.js +57 -27
  28. package/lib/types.d.ts +33 -2
  29. package/package.json +1 -1
  30. package/src/NativeRNBackgroundDownloader.ts +23 -0
  31. package/src/UploadTask.ts +23 -1
  32. package/src/index.ts +60 -27
  33. package/src/types.ts +42 -2
@@ -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
  }
@@ -44,7 +44,21 @@ class Uploader(private val context: Context) {
44
44
  interface UploadListener {
45
45
  fun onBegin(id: String, expectedBytes: Long)
46
46
  fun onProgress(id: String, bytesUploaded: Long, bytesTotal: Long)
47
- fun onComplete(id: String, responseCode: Int, responseBody: String, bytesUploaded: Long, bytesTotal: Long)
47
+ /** A part of an upload with partUrls was accepted (persist it, so a resume skips it). */
48
+ fun onPartComplete(id: String, part: UploadPartResult)
49
+ /**
50
+ * [responseCode], [responseBody] and [responseHeaders] are the last part's for an
51
+ * upload with partUrls; [parts] lists every part in order then.
52
+ */
53
+ fun onComplete(
54
+ id: String,
55
+ responseCode: Int,
56
+ responseBody: String,
57
+ responseHeaders: Map<String, String>,
58
+ parts: List<UploadPartResult>?,
59
+ bytesUploaded: Long,
60
+ bytesTotal: Long
61
+ )
48
62
  fun onError(id: String, error: String, errorCode: Int)
49
63
  }
50
64
 
@@ -182,6 +196,11 @@ class Uploader(private val context: Context) {
182
196
  return
183
197
  }
184
198
 
199
+ if (config.partUrls != null) {
200
+ executePartUpload(state, listener)
201
+ return
202
+ }
203
+
185
204
  val file = File(config.source)
186
205
  val fileSize = file.length()
187
206
  state.bytesTotal = fileSize
@@ -204,7 +223,8 @@ class Uploader(private val context: Context) {
204
223
  // Apply custom headers
205
224
  config.headers?.forEach { (key, value) ->
206
225
  connection.setRequestProperty(key, value)
207
- RNBackgroundDownloaderModuleImpl.logD(TAG, "Set upload header: $key = $value")
226
+ // Name only: values carry tokens, and apps forward logs to their services
227
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Set upload header: $key")
208
228
  }
209
229
 
210
230
  if (useMultipart) {
@@ -254,23 +274,13 @@ class Uploader(private val context: Context) {
254
274
 
255
275
  // Get response
256
276
  val responseCode = connection.responseCode
257
- val responseBody = try {
258
- val reader = BufferedReader(InputStreamReader(
259
- if (responseCode in 200..299) connection.inputStream else connection.errorStream
260
- ))
261
- val response = StringBuilder()
262
- var line: String?
263
- while (reader.readLine().also { line = it } != null) {
264
- response.append(line)
265
- }
266
- reader.close()
267
- response.toString()
268
- } catch (e: Exception) {
269
- ""
270
- }
277
+ val responseBody = readResponseBody(connection, responseCode)
271
278
 
272
279
  if (responseCode in 200..299) {
273
- listener.onComplete(config.id, responseCode, responseBody, state.bytesUploaded.get(), state.bytesTotal)
280
+ listener.onComplete(
281
+ config.id, responseCode, responseBody, lowercasedResponseHeaders(connection), null,
282
+ state.bytesUploaded.get(), state.bytesTotal
283
+ )
274
284
  } else {
275
285
  listener.onError(config.id, "HTTP error: $responseCode - $responseBody", responseCode)
276
286
  }
@@ -302,6 +312,138 @@ class Uploader(private val context: Context) {
302
312
  }
303
313
  }
304
314
 
315
+ /**
316
+ * Upload the source in byte ranges, one request per part URL, in order. Parts the
317
+ * server already accepted (config.completedParts, kept across pause and restart) are
318
+ * skipped. Any part that isn't accepted fails the whole upload.
319
+ */
320
+ private fun executePartUpload(state: UploadState, listener: UploadListener) {
321
+ val config = state.config
322
+ val partUrls = config.partUrls ?: return
323
+ val file = File(config.source)
324
+ val fileSize = file.length()
325
+ val ranges = uploadPartRanges(fileSize, partUrls.size, config.partSize)
326
+ if (ranges == null) {
327
+ val sizeNote = if (config.partSize > 0) " of ${config.partSize} bytes" else ""
328
+ listener.onError(state.id, "The file ($fileSize bytes) can't be split into ${partUrls.size} parts$sizeNote", -1)
329
+ activeUploads.remove(state.id)
330
+ return
331
+ }
332
+
333
+ val results = config.completedParts.orEmpty().toMutableList()
334
+ state.bytesTotal = fileSize
335
+ state.bytesUploaded.set(results.sumOf { it.bytes })
336
+ if (!state.hasReportedBegin) {
337
+ state.hasReportedBegin = true
338
+ listener.onBegin(state.id, fileSize)
339
+ }
340
+
341
+ for ((index, range) in ranges.withIndex()) {
342
+ val partNumber = index + 1
343
+ if (results.any { it.partNumber == partNumber }) continue
344
+ if (state.isCancelled.get() || state.isPaused.get()) return
345
+
346
+ val part = uploadPart(state, listener, file, partUrls[index], partNumber, range) ?: return
347
+ if (part.responseCode !in 200..299) {
348
+ listener.onError(
349
+ state.id,
350
+ "Part $partNumber failed: HTTP ${part.responseCode} - ${part.responseBody}",
351
+ part.responseCode
352
+ )
353
+ activeUploads.remove(state.id)
354
+ return
355
+ }
356
+ results.add(part)
357
+ listener.onPartComplete(state.id, part)
358
+ }
359
+
360
+ val parts = results.sortedBy { it.partNumber }
361
+ val last = parts.last()
362
+ listener.onComplete(
363
+ state.id, last.responseCode, last.responseBody, last.responseHeaders, parts,
364
+ state.bytesUploaded.get(), state.bytesTotal
365
+ )
366
+ activeUploads.remove(state.id)
367
+ }
368
+
369
+ /** Send one part as the raw body. Null when the upload was paused or cancelled meanwhile. */
370
+ private fun uploadPart(
371
+ state: UploadState,
372
+ listener: UploadListener,
373
+ file: File,
374
+ url: String,
375
+ partNumber: Int,
376
+ range: LongRange
377
+ ): UploadPartResult? {
378
+ val config = state.config
379
+ val length = range.last - range.first + 1
380
+ val connection = URL(url).openConnection() as HttpURLConnection
381
+ state.connection = connection
382
+ try {
383
+ connection.requestMethod = config.method
384
+ connection.doOutput = true
385
+ connection.doInput = true
386
+ connection.useCaches = false
387
+ connection.connectTimeout = CONNECT_TIMEOUT_MS
388
+ connection.readTimeout = READ_TIMEOUT_MS
389
+ config.headers?.forEach { (key, value) -> connection.setRequestProperty(key, value) }
390
+ connection.setRequestProperty("Content-Type", config.mimeType ?: "application/octet-stream")
391
+ connection.setFixedLengthStreamingMode(length)
392
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Uploading part $partNumber of ${config.id}: bytes ${range.first}-${range.last}")
393
+
394
+ // Partial progress of this part is dropped if it has to be sent again
395
+ val bytesBefore = state.bytesUploaded.get()
396
+ java.io.RandomAccessFile(file, "r").use { input ->
397
+ input.seek(range.first)
398
+ connection.outputStream.use { output ->
399
+ val buffer = ByteArray(BUFFER_SIZE)
400
+ var remaining = length
401
+ while (remaining > 0) {
402
+ if (state.isCancelled.get() || state.isPaused.get()) {
403
+ state.bytesUploaded.set(bytesBefore)
404
+ return null
405
+ }
406
+ val read = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
407
+ if (read == -1) throw java.io.EOFException("Source file shrank while uploading part $partNumber")
408
+ output.write(buffer, 0, read)
409
+ remaining -= read
410
+ listener.onProgress(state.id, state.bytesUploaded.addAndGet(read.toLong()), state.bytesTotal)
411
+ }
412
+ }
413
+ }
414
+ if (state.isCancelled.get() || state.isPaused.get()) {
415
+ state.bytesUploaded.set(bytesBefore)
416
+ return null
417
+ }
418
+
419
+ val responseCode = connection.responseCode
420
+ return UploadPartResult(
421
+ partNumber = partNumber,
422
+ responseCode = responseCode,
423
+ responseBody = readResponseBody(connection, responseCode),
424
+ responseHeaders = lowercasedResponseHeaders(connection),
425
+ bytes = length
426
+ )
427
+ } finally {
428
+ try {
429
+ connection.disconnect()
430
+ } catch (e: Exception) {
431
+ // Ignore
432
+ }
433
+ }
434
+ }
435
+
436
+ private fun readResponseBody(connection: HttpURLConnection, responseCode: Int): String = try {
437
+ val stream = if (responseCode in 200..299) connection.inputStream else connection.errorStream
438
+ stream?.let {
439
+ BufferedReader(InputStreamReader(it)).use { reader ->
440
+ readCapped(reader, DownloadConstants.MAX_UPLOAD_RESPONSE_CHARS)
441
+ }
442
+ } ?: ""
443
+ } catch (e: Exception) {
444
+ ""
445
+ }
446
+
305
447
  private fun calculateMultipartSize(config: RNBGDUploadTaskConfig, file: File, boundary: String): Long {
306
448
  var size = 0L
307
449
  val crlf = "\r\n"
@@ -411,3 +553,31 @@ class Uploader(private val context: Context) {
411
553
  // Multipart text is sent as UTF-8 (DataOutputStream.writeBytes would keep only each
412
554
  // char's low byte, garbling non-ASCII names and values), so sizes count UTF-8 bytes
413
555
  private fun String.utf8Size(): Int = toByteArray(Charsets.UTF_8).size
556
+
557
+ /**
558
+ * Read at most [maxChars] characters: the body goes to JS as one string, and an
559
+ * unbounded one from a hostile or broken server would run the app out of memory.
560
+ */
561
+ internal fun readCapped(reader: java.io.Reader, maxChars: Int): String {
562
+ val response = StringBuilder()
563
+ val buffer = CharArray(8192)
564
+ while (response.length < maxChars) {
565
+ val read = reader.read(buffer, 0, minOf(buffer.size, maxChars - response.length))
566
+ if (read == -1) break
567
+ response.append(buffer, 0, read)
568
+ }
569
+ return response.toString()
570
+ }
571
+
572
+ /** Response headers with lowercased names; repeated headers are joined with ", ". */
573
+ internal fun lowercasedResponseHeaders(connection: HttpURLConnection): Map<String, String> {
574
+ val headers = mutableMapOf<String, String>()
575
+ for ((name, values) in connection.headerFields.orEmpty()) {
576
+ // The status line comes with a null name
577
+ if (name == null || values == null) continue
578
+ val key = name.lowercase()
579
+ val value = values.joinToString(", ")
580
+ headers[key] = headers[key]?.let { "$it, $value" } ?: value
581
+ }
582
+ return headers
583
+ }
@@ -90,7 +90,7 @@ class OnProgress(
90
90
  } catch (e: Exception) {
91
91
  stopLoopWithFail()
92
92
  // if reached maximum memory while downloading, the downloader broadcast can not receive event normally
93
- downloader.broadcast(downloadId)
93
+ downloader.reportDownloadEnded(downloadId)
94
94
  throw e
95
95
  }
96
96
 
@@ -10,6 +10,15 @@ import java.net.HttpURLConnection
10
10
  */
11
11
  object HeaderUtils {
12
12
 
13
+ // Headers that carry credentials and must not be sent to another host
14
+ private val CREDENTIAL_HEADERS = setOf("authorization", "cookie", "proxy-authorization")
15
+
16
+ fun isCredentialHeader(name: String): Boolean = name.lowercase() in CREDENTIAL_HEADERS
17
+
18
+ /** The headers without Authorization, Cookie and Proxy-Authorization (case-insensitive). */
19
+ fun withoutCredentials(headers: Map<String, String>): Map<String, String> =
20
+ headers.filterKeys { !isCredentialHeader(it) }
21
+
13
22
  /**
14
23
  * Check if the provided headers already contain a User-Agent header (case-insensitive).
15
24
  */
@@ -58,7 +58,15 @@ object RedirectResolver {
58
58
  // Resolve relative locations against the current URL, keeping its port,
59
59
  // path and scheme (for "//host/path")
60
60
  val previousUrl = currentUrl
61
- currentUrl = URL(URL(currentUrl), location).toString()
61
+ val nextUrl = URL(URL(currentUrl), location)
62
+ if (!isSafeHop(URL(currentUrl), nextUrl, headers)) {
63
+ // Leave this hop to the downloader: the platform's own redirect
64
+ // handling drops credentials across hosts and refuses downgrades
65
+ RNBackgroundDownloaderModuleImpl.logW(TAG, "Not following redirect from $previousUrl to $nextUrl")
66
+ connection.disconnect()
67
+ break
68
+ }
69
+ currentUrl = nextUrl.toString()
62
70
 
63
71
  RNBackgroundDownloaderModuleImpl.logD(TAG, "Redirect ${redirectCount + 1}/$maxRedirects: $previousUrl -> $currentUrl")
64
72
  redirectCount++
@@ -86,4 +94,24 @@ object RedirectResolver {
86
94
  return originalUrl
87
95
  }
88
96
  }
97
+
98
+ /**
99
+ * Whether the resolver may probe [next] with the request's headers. Only http(s),
100
+ * never https -> http, and no other origin while credentials are attached -
101
+ * every probe resends all headers, and the resolved URL is downloaded with them.
102
+ */
103
+ internal fun isSafeHop(current: URL, next: URL, headers: Map<String, String>): Boolean {
104
+ val scheme = next.protocol.lowercase()
105
+ if (scheme != "http" && scheme != "https") return false
106
+ if (current.protocol.equals("https", ignoreCase = true) && scheme == "http") return false
107
+ val sameOrigin = current.protocol.equals(next.protocol, ignoreCase = true) &&
108
+ current.host.equals(next.host, ignoreCase = true) &&
109
+ effectivePort(current) == effectivePort(next)
110
+ return sameOrigin || headers.keys.none { HeaderUtils.isCredentialHeader(it) }
111
+ }
112
+
113
+ private fun isSafeHop(current: URL, next: URL, headers: ReadableMap?): Boolean =
114
+ isSafeHop(current, next, HeaderUtils.toMap(headers))
115
+
116
+ private fun effectivePort(url: URL): Int = if (url.port != -1) url.port else url.defaultPort
89
117
  }
@@ -0,0 +1,57 @@
1
+ package com.eko
2
+
3
+ import android.app.Application
4
+ import android.app.DownloadManager
5
+ import androidx.test.core.app.ApplicationProvider
6
+ import com.facebook.react.bridge.BridgeReactContext
7
+ import org.junit.Assert.assertEquals
8
+ import org.junit.Assert.assertTrue
9
+ import org.junit.Test
10
+ import org.junit.runner.RunWith
11
+ import org.robolectric.RobolectricTestRunner
12
+ import org.robolectric.Shadows.shadowOf
13
+ import org.robolectric.annotation.Config
14
+
15
+ /**
16
+ * The DOWNLOAD_COMPLETE receiver has to be exported for DownloadManager to reach it,
17
+ * and the action isn't protected on every Android version. Without a sender
18
+ * permission any app could send one and end (and remove) a running download.
19
+ */
20
+ @RunWith(RobolectricTestRunner::class)
21
+ class DownloadCompleteReceiverTest {
22
+
23
+ private val app: Application get() = ApplicationProvider.getApplicationContext()
24
+
25
+ private fun registeredDownloadReceivers() = shadowOf(app).registeredReceivers.filter {
26
+ it.intentFilter.hasAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
27
+ }
28
+
29
+ private fun registerReceiver() {
30
+ val module = RNBackgroundDownloaderModuleImpl(BridgeReactContext(app))
31
+ RNBackgroundDownloaderModuleImpl::class.java.getDeclaredMethod("registerDownloadReceiver").apply {
32
+ isAccessible = true
33
+ invoke(module)
34
+ }
35
+ }
36
+
37
+ @Test
38
+ @Config(sdk = [33])
39
+ fun `only DownloadProvider may send it before Android 14`() {
40
+ registerReceiver()
41
+
42
+ val receivers = registeredDownloadReceivers()
43
+ assertEquals(1, receivers.size)
44
+ assertEquals("android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", receivers[0].broadcastPermission)
45
+ }
46
+
47
+ @Test
48
+ @Config(sdk = [34])
49
+ fun `only DownloadProvider may send it on Android 14+`() {
50
+ registerReceiver()
51
+
52
+ val receivers = registeredDownloadReceivers()
53
+ assertEquals(1, receivers.size)
54
+ assertEquals("android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", receivers[0].broadcastPermission)
55
+ assertTrue(receivers[0].flags and android.content.Context.RECEIVER_EXPORTED != 0)
56
+ }
57
+ }