@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
package/README.md CHANGED
@@ -1,11 +1,14 @@
1
1
  <p align="center">
2
- <img width="300" src="https://github.com/user-attachments/assets/25e89808-9eb7-42b2-8031-b48d8c24796c" />
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>
3
6
  </p>
4
7
 
5
8
  <p align="center">
6
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>
7
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>
8
- <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>
9
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>
10
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>
11
14
  <img src="https://img.shields.io/badge/platforms-iOS%20%7C%20Android-lightgrey.svg" alt="platforms">
@@ -34,6 +37,16 @@
34
37
  <!-- cryptoc-promo:start -->
35
38
  <hr />
36
39
 
40
+ <h2 align="center">Sponsors</h2>
41
+
42
+ <p align="center">
43
+ <a href="https://getstream.io/chat/sdk/react-native/?utm_source=github&utm_medium=sponsor&utm_campaign=keshaantonov&utm_term=react-native-background-downloader"><img width="100" height="100" src="https://raw.githubusercontent.com/kesha-antonov/react-native-chat/main/media/getstream-sponsor-logo.png" alt="Stream" /></a>
44
+ <br />
45
+ <a href="https://getstream.io/chat/sdk/react-native/?utm_source=github&utm_medium=sponsor&utm_campaign=keshaantonov&utm_term=react-native-background-downloader"><strong>Stream</strong></a> - React Native Chat SDK
46
+ </p>
47
+
48
+ <hr />
49
+
37
50
  <table align="center">
38
51
  <tr>
39
52
  <td align="center" valign="top" width="190">
@@ -43,8 +56,10 @@
43
56
  <br />
44
57
  <sub>Scan to install</sub>
45
58
  <br /><br />
59
+ <!-- App Store button hidden for now
46
60
  <a href="https://apps.apple.com/app/cryptoc/id1333169178"><img height="40" src="https://cryptoc-app.web.app/img/appstore.svg?v=2" alt="Download on the App Store" /></a>
47
61
  <br />
62
+ -->
48
63
  <a href="https://play.google.com/store/apps/details?id=co.ssoul.CryptoC"><img height="59" src="https://cryptoc-app.web.app/img/googleplay.png?v=2" alt="Get it on Google Play" /></a>
49
64
  </td>
50
65
  <td valign="top">
@@ -142,8 +157,8 @@ How this library compares to other file transfer options in the React Native eco
142
157
  - [📚 API](#-api)
143
158
  - [Quick Reference](#quick-reference)
144
159
  - [📱 Platform Notes](#-platform-notes)
145
- - [❓ Troubleshooting](#-troubleshooting)
146
160
  - [🧪 Example App](#-example-app)
161
+ - [❓ Troubleshooting](#-troubleshooting)
147
162
  - [💡 Use Cases](#-use-cases)
148
163
  - [🔄 Migration Guide](#-migration-guide)
149
164
  - [🤝 Contributing](#-contributing)
@@ -346,6 +361,8 @@ let task = createDownloadTask({
346
361
  completeHandler(jobId)
347
362
  }).error(({ error, errorCode }) => {
348
363
  console.log('Download canceled due to error: ', { error, errorCode });
364
+
365
+ completeHandler(jobId)
349
366
  })
350
367
 
351
368
  // starts download
@@ -445,6 +462,8 @@ let task = createUploadTask({
445
462
  completeHandler(jobId)
446
463
  }).error(({ error, errorCode }) => {
447
464
  console.log('Upload canceled due to error: ', { error, errorCode })
465
+
466
+ completeHandler(jobId)
448
467
  })
449
468
 
450
469
  // starts upload
@@ -464,6 +483,40 @@ await task.stop()
464
483
 
465
484
  </details>
466
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
+
467
520
  <details>
468
521
  <summary><strong>Updating headers on paused downloads</strong></summary>
469
522
 
@@ -585,13 +638,13 @@ setConfig({
585
638
  })
586
639
  ```
587
640
 
588
- This is a cross-platform setting that works on both iOS and Android:
589
- - **iOS**: Sets the `allowsCellularAccess` property on the NSURLSession configuration
641
+ This is a cross-platform setting that works on both iOS and Android, for downloads and uploads. It's the default for each task's `isAllowedOverMetered`, so it applies to tasks created after the call:
642
+ - **iOS**: Sets `allowsCellularAccess` on each task's request (the session itself always allows cellular)
590
643
  - **Android**: Applied on all three download mechanisms - `DownloadManager` requests (`setAllowedOverMetered`), the UIDT/JobScheduler jobs used on Android 14+ (the job requires an unmetered network), and the foreground-service fallback used on Android < 14 (gated on a `ConnectivityManager` unmetered-network callback)
591
644
 
592
645
  When cellular is disallowed and the device only has a metered connection, the download doesn't fail - it waits until an unmetered network (e.g. WiFi) becomes available, then starts automatically. If the unmetered network is lost mid-download (e.g. WiFi drops and the device falls back to cellular), the download pauses instead of failing and automatically resumes from where it left off once an unmetered network returns. The restriction is kept across pause/resume and app restarts.
593
646
 
594
- **Per-download override (Android only):** On Android, you can override the global cellular setting for individual downloads using the `isAllowedOverMetered` option in `createDownloadTask()`:
647
+ **Per-task override:** You can override the global cellular setting for individual tasks using the `isAllowedOverMetered` option in `createDownloadTask()` or `createUploadTask()`, in either direction:
595
648
 
596
649
  ```javascript
597
650
  const task = createDownloadTask({
@@ -674,6 +727,7 @@ setConfig({
674
727
  - The `logCallback` function is called for each native debug log (iOS only sends logs to callback currently)
675
728
  - Logs include detailed information about download lifecycle, session management, and errors
676
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
677
731
 
678
732
  </details>
679
733
 
@@ -730,6 +784,7 @@ task.start()
730
784
  - Uses HEAD requests to resolve redirects efficiently
731
785
  - Falls back to original URL if redirect resolution fails
732
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
733
788
 
734
789
  </details>
735
790
 
@@ -981,6 +1036,39 @@ Key points:
981
1036
  - **Android**: Uses `DownloadManager` + Foreground Services + MMKV
982
1037
  - **Pause/Resume**: Works on both platforms (Android requires server Range header support)
983
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
+
984
1072
  ## ❓ Troubleshooting
985
1073
 
986
1074
  <details>
@@ -1051,7 +1139,7 @@ On iOS the actual transfer is handed to the system `nsurlsessiond` daemon and **
1051
1139
 
1052
1140
  1. **Did you force-quit the app?** If the user swipes the app away in the app switcher, iOS halts *that app's* background transfers until it's relaunched. This is an OS policy and cannot be worked around by any library.
1053
1141
  2. **You won't get live `progress` events while locked.** Your JavaScript isn't running while the app is suspended, so `begin` / `progress` / `complete` callbacks fire when the app resumes or is relaunched - not in real time. Re-attach with `getExistingDownloadTasks()` on launch.
1054
- 3. **AppDelegate wiring.** Make sure `handleEventsForBackgroundURLSession` is implemented (see [Installation](#-installation)) and that you call `completeHandler(jobId)` from JS in your `complete`/`error` handlers, or iOS will throttle future background time.
1142
+ 3. **AppDelegate wiring.** Make sure `handleEventsForBackgroundURLSession` is implemented (see [Installation](#-installation)) and that you call `completeHandler(jobId)` from JS in your `done` and `error` handlers, for every task. After a background launch the library tells iOS it's finished once every task that finished in it has been passed to `completeHandler` (or after 25 seconds), so it doesn't get suspended while you're still processing them.
1055
1143
  4. **Data Protection (the one this library handles).** On a passcoded, locked device, files protected with `NSFileProtectionComplete` can't be written, so a download that *finishes* while locked could previously fail to save. The library now writes the file with `NSFileProtectionCompleteUntilFirstUserAuthentication` by default (writable while locked after the first unlock since boot), and if the move still can't happen because the device is locked it stages the bytes and completes the save automatically when the device is next unlocked - emitting `complete` then. You can change the level with `setConfig({ iosDataProtection })` or per task (see Advanced Configuration).
1056
1144
  5. **Test on a real device.** The iOS Simulator's background-transfer behavior is unreliable; verify on hardware.
1057
1145
  </details>
@@ -1074,29 +1162,6 @@ See the [Google Play Console Declaration](#google-play-console-declaration) sect
1074
1162
  Add the Proguard rules mentioned in the [Proguard Rules](#proguard-rules) section.
1075
1163
  </details>
1076
1164
 
1077
- ## 🧪 Example App
1078
-
1079
- The repository includes a full example app demonstrating all features:
1080
-
1081
- ```bash
1082
- cd example
1083
- yarn install
1084
-
1085
- # iOS
1086
- cd ios && pod install && cd ..
1087
- yarn ios
1088
-
1089
- # Android
1090
- yarn android
1091
- ```
1092
-
1093
- The example app shows:
1094
- - Starting multiple downloads
1095
- - Pause/resume functionality
1096
- - Progress tracking with animations
1097
- - Re-attaching to background tasks
1098
- - File management
1099
-
1100
1165
  ## 💡 Use Cases
1101
1166
 
1102
1167
  This library is perfect for apps that need reliable file transfers:
@@ -13,18 +13,31 @@ object DownloadConstants {
13
13
  const val CONNECT_TIMEOUT_MS = 30_000 // 30 seconds
14
14
 
15
15
  /** Timeout for reading HTTP response (milliseconds) */
16
- const val READ_TIMEOUT_MS = 30_000 // 30 seconds
16
+ const val READ_TIMEOUT_MS = 20_000 // 20 seconds without data: the transfer has stalled
17
+
18
+ /**
19
+ * Waits before each retry of a transfer the network cut off (timeout, reset, lost
20
+ * connection). The count starts over whenever a retry gets data through.
21
+ */
22
+ val NETWORK_RETRY_DELAYS_MS = longArrayOf(1_000, 2_000, 4_000, 8_000, 15_000)
17
23
 
18
24
  /** Timeout for HEAD requests when fetching headers (milliseconds) */
19
25
  const val HEAD_REQUEST_READ_TIMEOUT_MS = 60_000 // 60 seconds
20
26
 
21
27
  /** Timeout for redirect resolution requests (milliseconds) */
22
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
23
34
 
24
35
  // ========== Download Buffer ==========
25
36
 
26
37
  /** Size of buffer for reading download data (bytes) */
27
- const val BUFFER_SIZE = 8192 // 8KB
38
+ // Each read reports progress, so on a fast connection a small buffer means thousands
39
+ // of reports a second
40
+ const val BUFFER_SIZE = 64 * 1024 // 64KB
28
41
 
29
42
  // ========== Progress Reporting ==========
30
43
 
@@ -86,6 +99,9 @@ object DownloadConstants {
86
99
  /** Other/unknown error */
87
100
  const val ERR_OTHERS = 100
88
101
 
102
+ /** The server stalled or the connection timed out; the same code as iOS (NSURLErrorTimedOut) */
103
+ const val ERR_TIMED_OUT = -1001
104
+
89
105
  // ========== Service Configuration ==========
90
106
 
91
107
  /** Notification channel ID for foreground service */
@@ -52,7 +52,9 @@ sealed class DownloadResult {
52
52
  val id: String,
53
53
  val message: String,
54
54
  val errorCode: Int = -1,
55
- val cause: Throwable? = null
55
+ val cause: Throwable? = null,
56
+ // The network cut the transfer off. Not reported yet: the downloader retries it first
57
+ val isNetworkFailure: Boolean = false
56
58
  ) : DownloadResult()
57
59
 
58
60
  /**
@@ -45,6 +45,10 @@ class Downloader(private val context: Context, private val storageManager: com.e
45
45
  // This is loaded from persistent storage and synchronized with it
46
46
  private val pausedDownloads = ConcurrentHashMap<String, PausedDownloadInfo>()
47
47
 
48
+ // Downloads that finished while the app wasn't running, found on recovery. Reported once
49
+ // as completed by getExistingDownloadTasks (takeFinishedDownloads)
50
+ private val finishedDownloads = ConcurrentHashMap<String, PausedDownloadInfo>()
51
+
48
52
  // Track download IDs that are being intentionally cancelled (to ignore broadcast events)
49
53
  // The value indicates the cancellation intent: PAUSING or STOPPING
50
54
  enum class CancelIntent { PAUSING, STOPPING }
@@ -283,11 +287,14 @@ class Downloader(private val context: Context, private val storageManager: com.e
283
287
  // resumed in-service and transferred further before a force-stop froze the
284
288
  // record). The file grows by sequential appends, so its on-disk length is
285
289
  // the authoritative resume offset - resuming below it would append
286
- // mid-stream data at the end of the file and corrupt it.
290
+ // mid-stream data at the end of the file and corrupt it. A missing file
291
+ // (pausing a DownloadManager download removes it, and its partial file
292
+ // with it) means starting from 0, or only the tail would be saved.
287
293
  val destFile = File(pausedInfo.destination)
288
- val resumeInfo = if (destFile.exists() && destFile.length() != pausedInfo.bytesDownloaded) {
289
- RNBackgroundDownloaderModuleImpl.logD(TAG, "Adjusting resume offset for $configId from ${pausedInfo.bytesDownloaded} to on-disk ${destFile.length()} bytes")
290
- pausedInfo.copy(bytesDownloaded = destFile.length())
294
+ val onDiskBytes = if (destFile.exists()) destFile.length() else 0L
295
+ val resumeInfo = if (onDiskBytes != pausedInfo.bytesDownloaded) {
296
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Adjusting resume offset for $configId from ${pausedInfo.bytesDownloaded} to on-disk $onDiskBytes bytes")
297
+ pausedInfo.copy(bytesDownloaded = onDiskBytes)
291
298
  } else {
292
299
  pausedInfo
293
300
  }
@@ -513,6 +520,12 @@ class Downloader(private val context: Context, private val storageManager: com.e
513
520
  return pausedDownloads.toMap()
514
521
  }
515
522
 
523
+ fun takeFinishedDownloads(): Map<String, PausedDownloadInfo> {
524
+ val finished = finishedDownloads.toMap()
525
+ finished.keys.forEach { finishedDownloads.remove(it) }
526
+ return finished
527
+ }
528
+
516
529
  /**
517
530
  * Get all in-progress resumable downloads tracked by the foreground service.
518
531
  * On Android 14+ active downloads run as UIDT jobs instead and are not included here.
@@ -574,6 +587,14 @@ class Downloader(private val context: Context, private val storageManager: com.e
574
587
  val destFile = File(info.destination)
575
588
  val fileLength = if (destFile.exists()) destFile.length() else 0L
576
589
 
590
+ // Finished with no app to report to: a job that completes in a process without the
591
+ // app records its final size. Report it as done once, not as paused (resuming a
592
+ // complete file fails with 416)
593
+ if (info.bytesTotal > 0 && fileLength >= info.bytesTotal) {
594
+ finishedDownloads[configId] = info.copy(bytesDownloaded = fileLength)
595
+ continue
596
+ }
597
+
577
598
  // Use the on-disk length as the authoritative resume offset. A length of 0
578
599
  // is still recoverable (restart from the beginning) - e.g. a download that
579
600
  // was parked waiting for an unmetered network when the app was killed.
@@ -636,11 +657,18 @@ class Downloader(private val context: Context, private val storageManager: com.e
636
657
  }
637
658
  }
638
659
 
639
- // Manually trigger the receiver from anywhere.
640
- fun broadcast(downloadId: Long) {
641
- val intent = Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
642
- intent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, downloadId)
643
- 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) }
644
672
  }
645
673
 
646
674
  fun checkDownloadStatus(downloadId: Long): WritableMap {
@@ -2,8 +2,6 @@ package com.eko
2
2
 
3
3
  import com.facebook.react.bridge.Arguments
4
4
  import com.facebook.react.bridge.WritableArray
5
- import com.facebook.react.bridge.WritableMap
6
- import java.util.Date
7
5
  import java.util.concurrent.ConcurrentHashMap
8
6
 
9
7
  /**
@@ -30,12 +28,15 @@ class ProgressReporter(
30
28
  // Per-download tracking state
31
29
  private val configIdToPercent = ConcurrentHashMap<String, Double>()
32
30
  private val configIdToLastBytes = ConcurrentHashMap<String, Long>()
33
- private val progressReports = ConcurrentHashMap<String, WritableMap>()
31
+ // Plain values: this runs for every chunk read, and a React map is a native object.
32
+ // The maps are made when a batch goes out.
33
+ private class Report(val bytes: Long, val bytesTotal: Long)
34
+ private val progressReports = ConcurrentHashMap<String, Report>()
34
35
 
35
36
  // Batching configuration
36
37
  private var progressInterval: Long = 0
37
38
  private var progressMinBytes: Long = 0
38
- private var lastProgressReportedAt = Date()
39
+ private var lastProgressReportedAt = System.currentTimeMillis()
39
40
 
40
41
  /**
41
42
  * Configure the progress reporting thresholds.
@@ -86,11 +87,7 @@ class ProgressReporter(
86
87
  // Report progress if either threshold is met, or if total bytes unknown (for realtime streams)
87
88
  // bytesTotal <= 0 means unknown size (-1) or zero
88
89
  if (percentThresholdMet || bytesThresholdMet || bytesTotal <= 0) {
89
- val params = Arguments.createMap()
90
- params.putString("id", configId)
91
- params.putDouble(bytesFieldName, bytesDownloaded.toDouble())
92
- params.putDouble("bytesTotal", bytesTotal.toDouble())
93
- progressReports[configId] = params
90
+ progressReports[configId] = Report(bytesDownloaded, bytesTotal)
94
91
  configIdToPercent[configId] = percent
95
92
  configIdToLastBytes[configId] = bytesDownloaded
96
93
  }
@@ -103,8 +100,8 @@ class ProgressReporter(
103
100
  * Check if the time interval has passed and emit any pending reports.
104
101
  */
105
102
  private fun emitBatchedReportsIfNeeded() {
106
- val now = Date()
107
- val isReportTimeDifference = now.time - lastProgressReportedAt.time > progressInterval
103
+ val now = System.currentTimeMillis()
104
+ val isReportTimeDifference = now - lastProgressReportedAt > progressInterval
108
105
  val isReportNotEmpty = progressReports.isNotEmpty()
109
106
 
110
107
  if (isReportTimeDifference && isReportNotEmpty) {
@@ -118,11 +115,14 @@ class ProgressReporter(
118
115
  */
119
116
  private fun emitBatchedReports() {
120
117
  // Create a copy to avoid concurrent modification
121
- val reportsList = progressReports.values.toList()
122
118
  val reportsArray = Arguments.createArray()
123
119
 
124
- for (report in reportsList) {
125
- reportsArray.pushMap(report.copy())
120
+ for ((configId, report) in progressReports.toMap()) {
121
+ val params = Arguments.createMap()
122
+ params.putString("id", configId)
123
+ params.putDouble(bytesFieldName, report.bytes.toDouble())
124
+ params.putDouble("bytesTotal", report.bytesTotal.toDouble())
125
+ reportsArray.pushMap(params)
126
126
  }
127
127
 
128
128
  onEmitProgress(reportsArray)
@@ -166,24 +166,3 @@ class ProgressReporter(
166
166
  configIdToLastBytes[configId] = 0L
167
167
  }
168
168
  }
169
-
170
- /**
171
- * Extension function to copy a WritableMap.
172
- * React Native's WritableMap can only be consumed once, so we need to copy it.
173
- */
174
- fun WritableMap.copy(): WritableMap {
175
- val copy = Arguments.createMap()
176
- val iterator = this.keySetIterator()
177
- while (iterator.hasNextKey()) {
178
- val key = iterator.nextKey()
179
- when (this.getType(key)) {
180
- com.facebook.react.bridge.ReadableType.Null -> copy.putNull(key)
181
- com.facebook.react.bridge.ReadableType.Boolean -> copy.putBoolean(key, this.getBoolean(key))
182
- com.facebook.react.bridge.ReadableType.Number -> copy.putDouble(key, this.getDouble(key))
183
- com.facebook.react.bridge.ReadableType.String -> copy.putString(key, this.getString(key))
184
- com.facebook.react.bridge.ReadableType.Map -> copy.putMap(key, this.getMap(key))
185
- com.facebook.react.bridge.ReadableType.Array -> copy.putArray(key, this.getArray(key))
186
- }
187
- }
188
- return copy
189
- }
@@ -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
+ }