@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
package/README.md CHANGED
@@ -1,15 +1,14 @@
1
1
  <p align="center">
2
- <img src="docs/images/example-main-dark.png" width="250" alt="Example app: main screen" />
3
- &nbsp;
4
- <img src="docs/images/example-download-dark.png" width="250" alt="Example app: downloads, one in progress" />
5
- &nbsp;
6
- <img src="docs/images/example-upload-dark.png" width="250" alt="Example app: uploads" />
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="docs/images/how-it-works-dark.gif" />
4
+ <img src="docs/images/how-it-works-light.gif" width="800" alt="A map download starts in the app, keeps going after the phone locks and iOS terminates the app, and is found again with getExistingDownloadTasks() when the app reopens" />
5
+ </picture>
7
6
  </p>
8
7
 
9
8
  <p align="center">
10
9
  <a href="https://badge.fury.io/js/@kesha-antonov%2Freact-native-background-downloader"><img src="https://badge.fury.io/js/@kesha-antonov%2Freact-native-background-downloader.svg" alt="npm version"></a>
11
10
  <a href="https://www.npmjs.com/package/@kesha-antonov/react-native-background-downloader"><img src="https://img.shields.io/npm/dm/@kesha-antonov/react-native-background-downloader.svg" alt="npm downloads"></a>
12
- <a href="https://npm-stat.com/charts.html?package=%40kesha-antonov%2Freact-native-background-downloader&from=2015-01-01"><img src="https://img.shields.io/badge/total%20downloads-1.07M-blue.svg" alt="total npm downloads"></a>
11
+ <a href="https://npm-stat.com/charts.html?package=%40kesha-antonov%2Freact-native-background-downloader&from=2015-01-01"><img src="https://img.shields.io/badge/total%20downloads-1.37M-blue.svg" alt="total npm downloads"></a>
13
12
  <a href="https://www.npmjs.com/package/@kesha-antonov/react-native-background-downloader"><img src="https://img.shields.io/npm/dt/@kesha-antonov/react-native-background-downloader.svg?label=18-months%20downloads" alt="npm downloads (last 18 months)"></a>
14
13
  <a href="https://github.com/kesha-antonov/react-native-background-downloader/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="license"></a>
15
14
  <img src="https://img.shields.io/badge/platforms-iOS%20%7C%20Android-lightgrey.svg" alt="platforms">
@@ -158,8 +157,8 @@ How this library compares to other file transfer options in the React Native eco
158
157
  - [๐Ÿ“š API](#-api)
159
158
  - [Quick Reference](#quick-reference)
160
159
  - [๐Ÿ“ฑ Platform Notes](#-platform-notes)
161
- - [โ“ Troubleshooting](#-troubleshooting)
162
160
  - [๐Ÿงช Example App](#-example-app)
161
+ - [โ“ Troubleshooting](#-troubleshooting)
163
162
  - [๐Ÿ’ก Use Cases](#-use-cases)
164
163
  - [๐Ÿ”„ Migration Guide](#-migration-guide)
165
164
  - [๐Ÿค Contributing](#-contributing)
@@ -484,6 +483,40 @@ await task.stop()
484
483
 
485
484
  </details>
486
485
 
486
+ <details>
487
+ <summary><strong>Uploading a large file in parts (S3 multipart upload)</strong></summary>
488
+
489
+ Pass one presigned URL per part as `partUrls`: the library sends each byte range of the file to its URL under one task, with combined progress, and hands back every part's `ETag` for `CompleteMultipartUpload`. No part files are created on Android; on iOS each part is copied to a temporary file while it uploads.
490
+
491
+ ```javascript
492
+ import { createUploadTask, directories } from '@kesha-antonov/react-native-background-downloader'
493
+
494
+ // From your backend: CreateMultipartUpload, then a presigned UploadPart URL per part
495
+ const { uploadId, partUrls, partSize } = await api.startMultipartUpload({ fileSize })
496
+
497
+ const task = createUploadTask({
498
+ id: 'video-upload',
499
+ source: `${directories.documents}/video.mp4`,
500
+ partUrls, // method defaults to PUT
501
+ partSize, // optional: defaults to Math.ceil(fileSize / partUrls.length)
502
+ mimeType: 'video/mp4',
503
+ metadata: { uploadId },
504
+ }).progress(({ bytesUploaded, bytesTotal }) => {
505
+ console.log(`Uploaded: ${bytesUploaded / bytesTotal * 100}%`)
506
+ }).done(async ({ parts }) => {
507
+ await api.completeMultipartUpload({
508
+ uploadId,
509
+ parts: parts.map(({ partNumber, responseHeaders }) => ({ PartNumber: partNumber, ETag: responseHeaders.etag })),
510
+ })
511
+ })
512
+
513
+ task.start()
514
+ ```
515
+
516
+ A single upload's response headers are in `done` too, as `responseHeaders` (lowercased names). On iOS, an upload that finishes while the app isn't running comes back from `getExistingUploadTasks()` as a `DONE` task with `parts` and `responseHeaders` set. See [Uploading in parts](docs/API.md#uploading-in-parts).
517
+
518
+ </details>
519
+
487
520
  <details>
488
521
  <summary><strong>Updating headers on paused downloads</strong></summary>
489
522
 
@@ -694,6 +727,7 @@ setConfig({
694
727
  - The `logCallback` function is called for each native debug log (iOS only sends logs to callback currently)
695
728
  - Logs include detailed information about download lifecycle, session management, and errors
696
729
  - In production builds, logs are only printed when explicitly enabled via `isLogsEnabled`
730
+ - Logs include URLs but not header values or upload response bodies; see [Security Notes](docs/PLATFORM_NOTES.md#security-notes) before forwarding them anywhere
697
731
 
698
732
  </details>
699
733
 
@@ -750,6 +784,7 @@ task.start()
750
784
  - Uses HEAD requests to resolve redirects efficiently
751
785
  - Falls back to original URL if redirect resolution fails
752
786
  - Respects the same headers and timeouts as the main download
787
+ - While `Authorization`, `Cookie` or `Proxy-Authorization` is set, stops before a redirect to another origin, so the credentials aren't sent there; never follows a redirect to a non-http(s) URL or from https to http
753
788
 
754
789
  </details>
755
790
 
@@ -1001,6 +1036,39 @@ Key points:
1001
1036
  - **Android**: Uses `DownloadManager` + Foreground Services + MMKV
1002
1037
  - **Pause/Resume**: Works on both platforms (Android requires server Range header support)
1003
1038
 
1039
+ ## ๐Ÿงช Example App
1040
+
1041
+ The repository includes a full example app demonstrating all features:
1042
+
1043
+ <p align="center">
1044
+ <img src="docs/images/example-main-dark.png" width="250" alt="Example app: main screen" />
1045
+ &nbsp;
1046
+ <img src="docs/images/example-download-dark.png" width="250" alt="Example app: downloads, one in progress" />
1047
+ &nbsp;
1048
+ <img src="docs/images/example-upload-dark.png" width="250" alt="Example app: uploads" />
1049
+ </p>
1050
+
1051
+ ```bash
1052
+ cd example
1053
+ yarn install
1054
+
1055
+ # iOS
1056
+ cd ios && pod install && cd ..
1057
+ yarn ios
1058
+
1059
+ # Android
1060
+ yarn android
1061
+ ```
1062
+
1063
+ The example app shows:
1064
+ - Starting multiple downloads
1065
+ - Pause/resume functionality
1066
+ - Progress tracking with animations
1067
+ - Re-attaching to background tasks
1068
+ - File management
1069
+ - Uploads to a test server
1070
+ - Light and dark theme, following the system setting
1071
+
1004
1072
  ## โ“ Troubleshooting
1005
1073
 
1006
1074
  <details>
@@ -1094,31 +1162,6 @@ See the [Google Play Console Declaration](#google-play-console-declaration) sect
1094
1162
  Add the Proguard rules mentioned in the [Proguard Rules](#proguard-rules) section.
1095
1163
  </details>
1096
1164
 
1097
- ## ๐Ÿงช Example App
1098
-
1099
- The repository includes a full example app demonstrating all features:
1100
-
1101
- ```bash
1102
- cd example
1103
- yarn install
1104
-
1105
- # iOS
1106
- cd ios && pod install && cd ..
1107
- yarn ios
1108
-
1109
- # Android
1110
- yarn android
1111
- ```
1112
-
1113
- The example app shows:
1114
- - Starting multiple downloads
1115
- - Pause/resume functionality
1116
- - Progress tracking with animations
1117
- - Re-attaching to background tasks
1118
- - File management
1119
- - Uploads to a test server
1120
- - Light and dark theme, following the system setting
1121
-
1122
1165
  ## ๐Ÿ’ก Use Cases
1123
1166
 
1124
1167
  This library is perfect for apps that need reliable file transfers:
@@ -26,6 +26,11 @@ object DownloadConstants {
26
26
 
27
27
  /** Timeout for redirect resolution requests (milliseconds) */
28
28
  const val REDIRECT_TIMEOUT_MS = 10_000 // 10 seconds
29
+ // http -> https redirects the resumable downloader follows itself (the
30
+ // platform follows same-scheme ones); bounds a redirect loop between the two
31
+ const val MAX_SCHEME_REDIRECTS = 5
32
+ // Upload response bodies past this are cut off before they reach JS
33
+ const val MAX_UPLOAD_RESPONSE_CHARS = 1024 * 1024
29
34
 
30
35
  // ========== Download Buffer ==========
31
36
 
@@ -657,11 +657,18 @@ class Downloader(private val context: Context, private val storageManager: com.e
657
657
  }
658
658
  }
659
659
 
660
- // Manually trigger the receiver from anywhere.
661
- fun broadcast(downloadId: Long) {
662
- val intent = Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
663
- intent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, downloadId)
664
- context.sendBroadcast(intent)
660
+ /**
661
+ * Runs the module's download-complete handling for [downloadId], like a
662
+ * DOWNLOAD_COMPLETE broadcast would. Not a real broadcast: the receiver only
663
+ * accepts broadcasts from DownloadManager, so other apps can't fake one.
664
+ */
665
+ @Volatile
666
+ var downloadEndedHandler: ((Long) -> Unit)? = null
667
+
668
+ fun reportDownloadEnded(downloadId: Long) {
669
+ val handler = downloadEndedHandler ?: return
670
+ // On the main thread, where the receiver runs too
671
+ android.os.Handler(android.os.Looper.getMainLooper()).post { handler(downloadId) }
665
672
  }
666
673
 
667
674
  fun checkDownloadStatus(downloadId: Long): WritableMap {
@@ -14,9 +14,44 @@ data class RNBGDUploadTaskConfig(
14
14
  val fieldName: String? = null,
15
15
  val mimeType: String? = null,
16
16
  val parameters: Map<String, String>? = null,
17
+ // Upload source in parts, one URL per part (S3 multipart upload and similar)
18
+ val partUrls: List<String>? = null,
19
+ // Bytes per part; 0 means ceil(file size / number of parts)
20
+ val partSize: Long = 0,
17
21
  var reportedBegin: Boolean = false,
18
22
  var bytesUploaded: Long = 0,
19
23
  var bytesTotal: Long = 0,
20
24
  var state: Int = DownloadConstants.TASK_RUNNING,
21
- var errorCode: Int = 0
25
+ var errorCode: Int = 0,
26
+ // Parts the server accepted, persisted so a resumed upload continues after them.
27
+ // Replaced, never mutated: it's serialized while the upload thread runs
28
+ @Volatile var completedParts: List<UploadPartResult>? = null
22
29
  )
30
+
31
+ /** One accepted part of an upload with partUrls. */
32
+ data class UploadPartResult(
33
+ // 1-based, as S3's CompleteMultipartUpload numbers parts
34
+ val partNumber: Int,
35
+ val responseCode: Int,
36
+ val responseBody: String,
37
+ // Lowercased header names
38
+ val responseHeaders: Map<String, String>,
39
+ val bytes: Long
40
+ )
41
+
42
+ /**
43
+ * Byte ranges of the parts: every part [partSize] bytes (default ceil(size / count))
44
+ * and the last one what's left. Null when the parts can't cover the file exactly,
45
+ * which includes an empty last part.
46
+ */
47
+ internal fun uploadPartRanges(fileSize: Long, partCount: Int, partSize: Long): List<LongRange>? {
48
+ if (partCount <= 0 || fileSize <= 0) return null
49
+ val size = if (partSize > 0) partSize else (fileSize + partCount - 1) / partCount
50
+ val beforeLast = size * (partCount - 1)
51
+ if (beforeLast >= fileSize || fileSize - beforeLast > size) return null
52
+ return (0 until partCount).map { index ->
53
+ val start = size * index
54
+ val end = if (index == partCount - 1) fileSize else start + size
55
+ start until end
56
+ }
57
+ }
@@ -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
@@ -396,68 +400,75 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
396
400
 
397
401
  downloadReceiver = object : BroadcastReceiver() {
398
402
  override fun onReceive(context: Context, intent: Intent) {
399
- 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) }
400
407
 
401
- // Check if this download is being intentionally cancelled (paused or stopped)
402
- val cancelIntent = downloader.getCancelIntent(downloadId)
403
- if (cancelIntent != null) {
404
- downloader.clearCancelIntent(downloadId)
405
- logD(NAME, "Ignoring broadcast for ${cancelIntent.name.lowercase()} download: $downloadId")
406
- return
407
- }
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
+ }
408
415
 
409
- 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
+ }
410
424
 
411
- if (config != null) {
412
- if (!synchronized(sharedLock) { endedDownloadIds.add(downloadId) }) {
413
- logD(NAME, "Ignoring repeated broadcast for download: $downloadId")
414
- return
415
- }
416
- val downloadStatus = downloader.checkDownloadStatus(downloadId)
417
- val status = downloadStatus.getInt("status")
418
- val localUri = downloadStatus.getString("localUri")
425
+ val config = downloadIdToConfig[downloadId]
419
426
 
420
- 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")
421
435
 
422
- synchronized(sharedLock) {
423
- // Drop any buffered progress that slipped past stopTaskProgress's clearPendingReport
424
- // (the polling thread may have re-added it between clearPendingReport and this lock)
425
- progressReporter.clearPendingReport(config.id)
426
- when (status) {
427
- DownloadManager.STATUS_SUCCESSFUL -> {
428
- onSuccessfulDownload(config, downloadStatus)
429
- }
430
- DownloadManager.STATUS_FAILED -> {
431
- onFailedDownload(config, downloadStatus)
432
- }
433
- }
436
+ stopTaskProgress(config.id)
434
437
 
435
- if (localUri != null) {
436
- // Prevent memory leaks from MediaScanner.
437
- // Download successful, clean task after media scanning.
438
- val paths = arrayOf(localUri)
439
- MediaScannerConnection.scanFile(context, paths, null) { _, _ ->
440
- if (status == DownloadManager.STATUS_SUCCESSFUL) {
441
- // Not stopTask: DownloadManager.remove() deletes the downloaded file too
442
- releaseCompletedTask(config.id)
443
- } else {
444
- stopTask(config.id)
445
- }
446
- // Cleaned up: a later broadcast finds no config
447
- synchronized(sharedLock) { endedDownloadIds.remove(downloadId) }
448
- }
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)
449
459
  } else {
450
- // Download failed, clean task.
451
460
  stopTask(config.id)
452
- endedDownloadIds.remove(downloadId)
453
461
  }
462
+ // Cleaned up: a later broadcast finds no config
463
+ synchronized(sharedLock) { endedDownloadIds.remove(downloadId) }
454
464
  }
465
+ } else {
466
+ // Download failed, clean task.
467
+ stopTask(config.id)
468
+ endedDownloadIds.remove(downloadId)
455
469
  }
456
470
  }
457
471
  }
458
-
459
- compatRegisterReceiver(reactContext, downloadReceiver!!, filter, true)
460
- isReceiverRegistered = true
461
472
  }
462
473
 
463
474
  // TAKEN FROM
@@ -466,20 +477,24 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
466
477
  context: Context,
467
478
  receiver: BroadcastReceiver,
468
479
  filter: IntentFilter,
469
- exported: Boolean
480
+ exported: Boolean,
481
+ broadcastPermission: String? = null
470
482
  ) {
471
483
  if (Build.VERSION.SDK_INT >= 34 && context.applicationInfo.targetSdkVersion >= 34) {
472
484
  context.registerReceiver(
473
485
  receiver,
474
486
  filter,
487
+ broadcastPermission,
488
+ null,
475
489
  if (exported) Context.RECEIVER_EXPORTED else Context.RECEIVER_NOT_EXPORTED
476
490
  )
477
491
  } else {
478
- context.registerReceiver(receiver, filter)
492
+ context.registerReceiver(receiver, filter, broadcastPermission, null)
479
493
  }
480
494
  }
481
495
 
482
496
  private fun unregisterDownloadReceiver() {
497
+ downloader.downloadEndedHandler = null
483
498
  downloadReceiver?.let {
484
499
  try {
485
500
  reactContext.unregisterReceiver(it)
@@ -1420,7 +1435,25 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1420
1435
  uploadProgressReporter.reportProgress(id, bytesUploaded, bytesTotal)
1421
1436
  }
1422
1437
 
1423
- 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
+ ) {
1424
1457
  synchronized(sharedLock) {
1425
1458
  uploadConfigs[id]?.state = DownloadConstants.TASK_COMPLETED
1426
1459
  uploadConfigs.remove(id)
@@ -1429,7 +1462,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1429
1462
  // Remove from persistent storage on completion
1430
1463
  storageManager.saveUploadConfigs(uploadConfigs)
1431
1464
  }
1432
- uploadEventEmitter.emitComplete(id, responseCode, responseBody, bytesUploaded, bytesTotal)
1465
+ uploadEventEmitter.emitComplete(id, responseCode, responseBody, responseHeaders, parts, bytesUploaded, bytesTotal)
1433
1466
  }
1434
1467
 
1435
1468
  override fun onError(id: String, error: String, errorCode: Int) {
@@ -1495,6 +1528,11 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1495
1528
  result
1496
1529
  } else null
1497
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
+
1498
1536
  // Progress settings
1499
1537
  val progressIntervalScope = options.getInt("progressInterval")
1500
1538
  // 0 is a valid value (percentage only), so it has to be applied too
@@ -1519,7 +1557,9 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
1519
1557
  headers = headers,
1520
1558
  fieldName = fieldName,
1521
1559
  mimeType = mimeType,
1522
- parameters = parameters
1560
+ parameters = parameters,
1561
+ partUrls = partUrls,
1562
+ partSize = partSize
1523
1563
  )
1524
1564
 
1525
1565
  synchronized(sharedLock) {
@@ -472,7 +472,12 @@ class ResumableDownloader {
472
472
  * Execute the download and return a DownloadResult.
473
473
  * This method handles all download logic and returns a type-safe result.
474
474
  */
475
- 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 {
476
481
  var connection: HttpURLConnection? = null
477
482
  var inputStream: InputStream? = null
478
483
  var outputStream: FileOutputStream? = null
@@ -572,17 +577,33 @@ class ResumableDownloader {
572
577
  HttpURLConnection.HTTP_MOVED_TEMP,
573
578
  HttpURLConnection.HTTP_SEE_OTHER,
574
579
  307, 308 -> {
575
- // Handle redirect
576
- val newUrl = connection.getHeaderField("Location")
577
- if (newUrl != null) {
578
- connection.disconnect()
579
- // Create new state with updated URL
580
- // Note: We preserve bytesDownloaded since the redirect should point to the same resource.
581
- // If the new server doesn't support Range headers, the HTTP_OK case above will reset it.
582
- val newState = state.copyWithUrl(newUrl)
583
- activeDownloads[state.id] = newState
584
- 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
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)
585
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)
586
607
  }
587
608
  416 -> {
588
609
  // Range Not Satisfiable - file might be complete or server doesn't support ranges
@@ -768,12 +789,12 @@ class ResumableDownloader {
768
789
  }
769
790
  }
770
791
 
771
- private fun DownloadState.copyWithUrl(url: String): DownloadState {
792
+ private fun DownloadState.copyWithUrl(url: String, headers: Map<String, String>): DownloadState {
772
793
  return DownloadState(
773
794
  id = this.id,
774
795
  url = url,
775
796
  destination = this.destination,
776
- headers = this.headers,
797
+ headers = headers,
777
798
  isPaused = this.isPaused,
778
799
  isCancelled = this.isCancelled,
779
800
  bytesDownloaded = this.bytesDownloaded,