@kesha-antonov/react-native-background-downloader 4.6.4 → 4.7.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.
- package/README.md +27 -5
- package/android/src/main/java/com/eko/DownloadConstants.kt +13 -2
- package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
- package/android/src/main/java/com/eko/Downloader.kt +25 -4
- package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
- package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +162 -76
- package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
- package/android/src/main/java/com/eko/ResumableDownloader.kt +75 -3
- package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
- package/android/src/main/java/com/eko/Uploader.kt +15 -11
- package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
- package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
- package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
- package/android/src/main/java/com/eko/utils/RedirectResolver.kt +5 -13
- package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
- package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
- package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
- package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
- package/android/src/test/java/com/eko/UploaderMultipartTest.kt +84 -0
- package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
- package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
- package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +67 -0
- package/ios/RNBGDTaskConfig.h +2 -0
- package/ios/RNBGDTaskConfig.mm +6 -0
- package/ios/RNBackgroundDownloader.mm +640 -90
- package/lib/DownloadTask.d.ts +2 -0
- package/lib/DownloadTask.js +17 -1
- package/lib/UploadTask.d.ts +2 -0
- package/lib/UploadTask.js +17 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +50 -36
- package/package.json +14 -11
- package/plugin/build/index.d.ts +1 -0
- package/plugin/build/index.js +18 -10
- package/react-native-background-downloader.podspec +8 -0
- package/src/DownloadTask.ts +18 -1
- package/src/UploadTask.ts +18 -1
- package/src/index.ts +73 -41
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img
|
|
2
|
+
<img src="docs/images/example-main-dark.png" width="250" alt="Example app: main screen" />
|
|
3
|
+
|
|
4
|
+
<img src="docs/images/example-download-dark.png" width="250" alt="Example app: downloads, one in progress" />
|
|
5
|
+
|
|
6
|
+
<img src="docs/images/example-upload-dark.png" width="250" alt="Example app: uploads" />
|
|
3
7
|
</p>
|
|
4
8
|
|
|
5
9
|
<p align="center">
|
|
@@ -34,6 +38,16 @@
|
|
|
34
38
|
<!-- cryptoc-promo:start -->
|
|
35
39
|
<hr />
|
|
36
40
|
|
|
41
|
+
<h2 align="center">Sponsors</h2>
|
|
42
|
+
|
|
43
|
+
<p align="center">
|
|
44
|
+
<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>
|
|
45
|
+
<br />
|
|
46
|
+
<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
|
|
47
|
+
</p>
|
|
48
|
+
|
|
49
|
+
<hr />
|
|
50
|
+
|
|
37
51
|
<table align="center">
|
|
38
52
|
<tr>
|
|
39
53
|
<td align="center" valign="top" width="190">
|
|
@@ -43,8 +57,10 @@
|
|
|
43
57
|
<br />
|
|
44
58
|
<sub>Scan to install</sub>
|
|
45
59
|
<br /><br />
|
|
60
|
+
<!-- App Store button hidden for now
|
|
46
61
|
<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
62
|
<br />
|
|
63
|
+
-->
|
|
48
64
|
<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
65
|
</td>
|
|
50
66
|
<td valign="top">
|
|
@@ -346,6 +362,8 @@ let task = createDownloadTask({
|
|
|
346
362
|
completeHandler(jobId)
|
|
347
363
|
}).error(({ error, errorCode }) => {
|
|
348
364
|
console.log('Download canceled due to error: ', { error, errorCode });
|
|
365
|
+
|
|
366
|
+
completeHandler(jobId)
|
|
349
367
|
})
|
|
350
368
|
|
|
351
369
|
// starts download
|
|
@@ -445,6 +463,8 @@ let task = createUploadTask({
|
|
|
445
463
|
completeHandler(jobId)
|
|
446
464
|
}).error(({ error, errorCode }) => {
|
|
447
465
|
console.log('Upload canceled due to error: ', { error, errorCode })
|
|
466
|
+
|
|
467
|
+
completeHandler(jobId)
|
|
448
468
|
})
|
|
449
469
|
|
|
450
470
|
// starts upload
|
|
@@ -585,13 +605,13 @@ setConfig({
|
|
|
585
605
|
})
|
|
586
606
|
```
|
|
587
607
|
|
|
588
|
-
This is a cross-platform setting that works on both iOS and Android:
|
|
589
|
-
- **iOS**: Sets
|
|
608
|
+
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:
|
|
609
|
+
- **iOS**: Sets `allowsCellularAccess` on each task's request (the session itself always allows cellular)
|
|
590
610
|
- **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
611
|
|
|
592
612
|
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
613
|
|
|
594
|
-
**Per-
|
|
614
|
+
**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
615
|
|
|
596
616
|
```javascript
|
|
597
617
|
const task = createDownloadTask({
|
|
@@ -1051,7 +1071,7 @@ On iOS the actual transfer is handed to the system `nsurlsessiond` daemon and **
|
|
|
1051
1071
|
|
|
1052
1072
|
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
1073
|
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 `
|
|
1074
|
+
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
1075
|
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
1076
|
5. **Test on a real device.** The iOS Simulator's background-transfer behavior is unreliable; verify on hardware.
|
|
1057
1077
|
</details>
|
|
@@ -1096,6 +1116,8 @@ The example app shows:
|
|
|
1096
1116
|
- Progress tracking with animations
|
|
1097
1117
|
- Re-attaching to background tasks
|
|
1098
1118
|
- File management
|
|
1119
|
+
- Uploads to a test server
|
|
1120
|
+
- Light and dark theme, following the system setting
|
|
1099
1121
|
|
|
1100
1122
|
## 💡 Use Cases
|
|
1101
1123
|
|
|
@@ -13,7 +13,13 @@ 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 =
|
|
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
|
|
@@ -24,7 +30,9 @@ object DownloadConstants {
|
|
|
24
30
|
// ========== Download Buffer ==========
|
|
25
31
|
|
|
26
32
|
/** Size of buffer for reading download data (bytes) */
|
|
27
|
-
|
|
33
|
+
// Each read reports progress, so on a fast connection a small buffer means thousands
|
|
34
|
+
// of reports a second
|
|
35
|
+
const val BUFFER_SIZE = 64 * 1024 // 64KB
|
|
28
36
|
|
|
29
37
|
// ========== Progress Reporting ==========
|
|
30
38
|
|
|
@@ -86,6 +94,9 @@ object DownloadConstants {
|
|
|
86
94
|
/** Other/unknown error */
|
|
87
95
|
const val ERR_OTHERS = 100
|
|
88
96
|
|
|
97
|
+
/** The server stalled or the connection timed out; the same code as iOS (NSURLErrorTimedOut) */
|
|
98
|
+
const val ERR_TIMED_OUT = -1001
|
|
99
|
+
|
|
89
100
|
// ========== Service Configuration ==========
|
|
90
101
|
|
|
91
102
|
/** 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
|
|
289
|
-
|
|
290
|
-
pausedInfo.
|
|
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.
|
|
@@ -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
|
-
|
|
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 =
|
|
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
|
-
|
|
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 =
|
|
107
|
-
val isReportTimeDifference = now
|
|
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
|
|
125
|
-
|
|
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
|
-
}
|