@kesha-antonov/react-native-background-downloader 4.5.8 → 4.6.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 +30 -3
- package/android/build.gradle +17 -0
- package/android/src/main/AndroidManifest.xml +24 -0
- package/android/src/main/java/com/eko/DownloadConstants.kt +14 -2
- package/android/src/main/java/com/eko/Downloader.kt +77 -12
- package/android/src/main/java/com/eko/PromiseExtensions.kt +36 -0
- package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +82 -134
- package/android/src/main/java/com/eko/ResumableDownloadService.kt +0 -4
- package/android/src/main/java/com/eko/ResumableDownloader.kt +121 -12
- package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +65 -9
- package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +64 -0
- package/android/src/main/java/com/eko/uidt/RNBGDFileProvider.kt +17 -0
- package/android/src/main/java/com/eko/uidt/UIDTJobIds.kt +112 -0
- package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +178 -17
- package/android/src/main/java/com/eko/uidt/UIDTJobState.kt +23 -1
- package/android/src/main/java/com/eko/uidt/UIDTNotificationIds.kt +73 -0
- package/android/src/main/java/com/eko/uidt/UIDTNotificationManager.kt +246 -19
- package/android/src/main/java/com/eko/utils/ReadableConverters.kt +55 -0
- package/android/src/main/java/com/eko/utils/RedirectResolver.kt +97 -0
- package/android/src/main/java/com/eko/utils/StorageManager.kt +13 -0
- package/android/src/main/res/xml/rnbgd_file_paths.xml +23 -0
- package/android/src/newarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
- package/android/src/oldarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
- package/android/src/test/java/com/eko/ResumableDownloaderConcurrencyTest.kt +199 -0
- package/android/src/test/java/com/eko/uidt/UIDTJobIdsTest.kt +159 -0
- package/android/src/test/java/com/eko/uidt/UIDTJobManagerTest.kt +192 -0
- package/android/src/test/java/com/eko/uidt/UIDTNotificationIdsTest.kt +99 -0
- package/ios/RNBackgroundDownloader.mm +187 -91
- package/lib/DownloadTask.js +8 -7
- package/lib/NativeRNBackgroundDownloader.d.ts +2 -0
- package/lib/UploadTask.js +11 -10
- package/lib/config.d.ts +3 -10
- package/lib/config.js +4 -44
- package/lib/index.d.ts +1 -1
- package/lib/index.js +43 -34
- package/lib/logger.d.ts +2 -0
- package/lib/logger.js +16 -0
- package/lib/notifications.d.ts +8 -0
- package/lib/notifications.js +35 -0
- package/lib/types.d.ts +19 -0
- package/package.json +8 -3
- package/src/DownloadTask.ts +2 -1
- package/src/NativeRNBackgroundDownloader.ts +8 -1
- package/src/UploadTask.ts +2 -1
- package/src/config.ts +9 -45
- package/src/index.ts +22 -2
- package/src/logger.ts +16 -0
- package/src/notifications.ts +32 -0
- package/src/types.ts +19 -0
package/README.md
CHANGED
|
@@ -475,9 +475,9 @@ Headers given in `createDownloadTask()` are **merged** with the ones given in `s
|
|
|
475
475
|
|
|
476
476
|
You can configure global settings for download behavior using `setConfig()`:
|
|
477
477
|
|
|
478
|
-
#### Max Parallel Downloads
|
|
478
|
+
#### Max Parallel Downloads
|
|
479
479
|
|
|
480
|
-
Control how many
|
|
480
|
+
Control how many downloads transfer at once. This is useful for managing bandwidth and server load.
|
|
481
481
|
|
|
482
482
|
```javascript
|
|
483
483
|
import { setConfig } from '@kesha-antonov/react-native-background-downloader'
|
|
@@ -488,7 +488,7 @@ setConfig({
|
|
|
488
488
|
})
|
|
489
489
|
```
|
|
490
490
|
|
|
491
|
-
**Note:**
|
|
491
|
+
**Note:** the two platforms apply it at different layers. On iOS it is the download session's maximum simultaneous connections per host. On Android it caps the library's own downloader - the mechanism used on Android 16+, and whenever `DownloadManager` or a UIDT job can't take the download - while downloads that run through `DownloadManager` or the JobScheduler are queued by those schedulers instead.
|
|
492
492
|
|
|
493
493
|
#### Cellular/WiFi Restrictions
|
|
494
494
|
|
|
@@ -692,6 +692,33 @@ setConfig({
|
|
|
692
692
|
})
|
|
693
693
|
```
|
|
694
694
|
|
|
695
|
+
**Cancel button and completion notification (Android 14+):**
|
|
696
|
+
|
|
697
|
+
Two extras are available on top of `showNotificationsEnabled`. Both are off by default, so enabling notifications alone never adds an alerting notification or a button your app is not ready for:
|
|
698
|
+
|
|
699
|
+
```javascript
|
|
700
|
+
setConfig({
|
|
701
|
+
showNotificationsEnabled: true,
|
|
702
|
+
// Adds a Cancel button to the download notification. Tapping it stops the
|
|
703
|
+
// download like task.stop() and fires the task's .error() handler with
|
|
704
|
+
// errorCode = -1, so handle that in your app before enabling it.
|
|
705
|
+
showCancelAction: true,
|
|
706
|
+
// Posts a "download complete" notification when a download finishes.
|
|
707
|
+
// Tapping it opens the saved file with the system chooser.
|
|
708
|
+
// Skipped in 'summaryOnly' grouping mode.
|
|
709
|
+
showCompletionNotification: true,
|
|
710
|
+
notificationsGrouping: {
|
|
711
|
+
enabled: true,
|
|
712
|
+
texts: {
|
|
713
|
+
downloadCancel: 'Cancel', // Label of the Cancel button
|
|
714
|
+
downloadFinished: 'Download complete', // Title of the completion notification
|
|
715
|
+
},
|
|
716
|
+
},
|
|
717
|
+
})
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
Per-download notification titles are supported too - pass `metadata.notificationTitle` to override `groupName` and the default `downloadTitle` for a single download. See [Platform Notes](docs/PLATFORM_NOTES.md#download-notifications-android-14) for the full behavior.
|
|
721
|
+
|
|
695
722
|
**Notification grouping modes:**
|
|
696
723
|
|
|
697
724
|
When downloading many files (e.g., thousands of photos), you can use the `mode` option to control how notifications are displayed:
|
package/android/build.gradle
CHANGED
|
@@ -66,6 +66,16 @@ android {
|
|
|
66
66
|
useLegacyPackaging = false
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
|
+
|
|
70
|
+
testOptions {
|
|
71
|
+
unitTests {
|
|
72
|
+
includeAndroidResources = true
|
|
73
|
+
// Framework calls the tests don't exercise (e.g. Log from a class
|
|
74
|
+
// loaded outside a Robolectric environment) return a default instead
|
|
75
|
+
// of throwing "not mocked"
|
|
76
|
+
returnDefaultValues = true
|
|
77
|
+
}
|
|
78
|
+
}
|
|
69
79
|
}
|
|
70
80
|
|
|
71
81
|
repositories {
|
|
@@ -84,4 +94,11 @@ dependencies {
|
|
|
84
94
|
compileOnly 'com.tencent:mmkv-shared:1.3.16'
|
|
85
95
|
|
|
86
96
|
implementation 'com.google.code.gson:gson:2.12.1'
|
|
97
|
+
|
|
98
|
+
// Unit tests. Robolectric gives the tests a real JobScheduler, SharedPreferences
|
|
99
|
+
// and Log without a device; MockWebServer backs the download-transfer tests.
|
|
100
|
+
testImplementation 'junit:junit:4.13.2'
|
|
101
|
+
testImplementation 'org.robolectric:robolectric:4.14.1'
|
|
102
|
+
testImplementation 'androidx.test:core:1.6.1'
|
|
103
|
+
testImplementation 'com.squareup.okhttp3:mockwebserver:4.12.0'
|
|
87
104
|
}
|
|
@@ -25,6 +25,30 @@
|
|
|
25
25
|
android:name=".UIDTDownloadJobService"
|
|
26
26
|
android:permission="android.permission.BIND_JOB_SERVICE"
|
|
27
27
|
android:exported="false" />
|
|
28
|
+
|
|
29
|
+
<!-- Receiver for the in-notification "Cancel" action -->
|
|
30
|
+
<receiver
|
|
31
|
+
android:name=".uidt.CancelDownloadReceiver"
|
|
32
|
+
android:exported="false">
|
|
33
|
+
<intent-filter>
|
|
34
|
+
<action android:name="com.eko.uidt.ACTION_CANCEL_DOWNLOAD" />
|
|
35
|
+
</intent-filter>
|
|
36
|
+
</receiver>
|
|
37
|
+
|
|
38
|
+
<!-- Library-owned FileProvider so tapping the "download complete"
|
|
39
|
+
notification can open the saved file via the system viewer with no
|
|
40
|
+
host-app configuration. A dedicated subclass + unique authority avoid
|
|
41
|
+
manifest-merger / authority collisions with the host app's own
|
|
42
|
+
FileProvider. -->
|
|
43
|
+
<provider
|
|
44
|
+
android:name=".uidt.RNBGDFileProvider"
|
|
45
|
+
android:authorities="${applicationId}.rnbackgrounddownloader.fileprovider"
|
|
46
|
+
android:exported="false"
|
|
47
|
+
android:grantUriPermissions="true">
|
|
48
|
+
<meta-data
|
|
49
|
+
android:name="android.support.FILE_PROVIDER_PATHS"
|
|
50
|
+
android:resource="@xml/rnbgd_file_paths" />
|
|
51
|
+
</provider>
|
|
28
52
|
</application>
|
|
29
53
|
|
|
30
54
|
</manifest>
|
|
@@ -97,6 +97,18 @@ object DownloadConstants {
|
|
|
97
97
|
/** Wake lock timeout (milliseconds) - 1 hour */
|
|
98
98
|
const val WAKELOCK_TIMEOUT_MS = 60 * 60 * 1000L
|
|
99
99
|
|
|
100
|
-
/**
|
|
101
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Transfers the library's own downloader runs at once by default, matching
|
|
102
|
+
* the JS `maxParallelDownloads` default. Downloads over the limit wait for a
|
|
103
|
+
* slot instead of each taking a thread and a socket of their own.
|
|
104
|
+
*/
|
|
105
|
+
const val DEFAULT_MAX_PARALLEL_DOWNLOADS = 4
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* How long a download may wait for the download service to connect before it
|
|
109
|
+
* is failed. Binding normally completes in milliseconds; the wait only runs
|
|
110
|
+
* long when the system refused to start the service at all, and a download
|
|
111
|
+
* left parked there would never report anything to JS.
|
|
112
|
+
*/
|
|
113
|
+
const val SERVICE_START_TIMEOUT_MS = 15_000L
|
|
102
114
|
}
|
|
@@ -7,12 +7,15 @@ import android.content.Intent
|
|
|
7
7
|
import android.content.ServiceConnection
|
|
8
8
|
import android.database.Cursor
|
|
9
9
|
import android.os.Build
|
|
10
|
+
import android.os.Handler
|
|
10
11
|
import android.os.IBinder
|
|
12
|
+
import android.os.Looper
|
|
11
13
|
import android.util.Log
|
|
12
14
|
import com.facebook.react.bridge.Arguments
|
|
13
15
|
import com.facebook.react.bridge.WritableMap
|
|
14
16
|
import java.io.File
|
|
15
17
|
import java.util.concurrent.ConcurrentHashMap
|
|
18
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
16
19
|
|
|
17
20
|
/**
|
|
18
21
|
* Wrapper around Android's DownloadManager for managing file downloads.
|
|
@@ -305,8 +308,17 @@ class Downloader(private val context: Context, private val storageManager: com.e
|
|
|
305
308
|
* - Work properly on Android 16+ where foreground services are restricted
|
|
306
309
|
*
|
|
307
310
|
* On Android < 14, uses the foreground service with dataSync type.
|
|
311
|
+
*
|
|
312
|
+
* @param allowServiceFallback when false, a download that can't get a UIDT job
|
|
313
|
+
* is reported back to the caller (`false`) instead of being handed to
|
|
314
|
+
* the foreground service, so the caller can pick another mechanism.
|
|
315
|
+
* @return whether a mechanism took the download.
|
|
308
316
|
*/
|
|
309
|
-
private fun startDownloadService(
|
|
317
|
+
private fun startDownloadService(
|
|
318
|
+
info: PausedDownloadInfo,
|
|
319
|
+
listener: ResumableDownloader.DownloadListener,
|
|
320
|
+
allowServiceFallback: Boolean = true
|
|
321
|
+
): Boolean {
|
|
310
322
|
// On Android 14+, use UIDT jobs for better background execution
|
|
311
323
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
|
312
324
|
// Set the listener for UIDT job callbacks
|
|
@@ -327,11 +339,18 @@ class Downloader(private val context: Context, private val storageManager: com.e
|
|
|
327
339
|
|
|
328
340
|
if (scheduled) {
|
|
329
341
|
RNBackgroundDownloaderModuleImpl.logD(TAG, "Using UIDT job for download: ${info.configId}")
|
|
330
|
-
return
|
|
342
|
+
return true
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (!allowServiceFallback) {
|
|
346
|
+
RNBackgroundDownloaderModuleImpl.logW(TAG, "UIDT scheduling failed for ${info.configId}, leaving the mechanism to the caller")
|
|
347
|
+
return false
|
|
331
348
|
}
|
|
332
349
|
|
|
333
350
|
// Fall through to foreground service if UIDT scheduling fails
|
|
334
351
|
RNBackgroundDownloaderModuleImpl.logW(TAG, "UIDT scheduling failed, falling back to foreground service")
|
|
352
|
+
} else if (!allowServiceFallback) {
|
|
353
|
+
return false
|
|
335
354
|
}
|
|
336
355
|
|
|
337
356
|
// On Android < 14 or if UIDT fails, use foreground service.
|
|
@@ -352,7 +371,11 @@ class Downloader(private val context: Context, private val storageManager: com.e
|
|
|
352
371
|
}
|
|
353
372
|
|
|
354
373
|
// Now use the direct service call path
|
|
374
|
+
val settled = AtomicBoolean(false)
|
|
355
375
|
executeWhenServiceReady {
|
|
376
|
+
// Lost the race to the watchdog below - the download was already failed
|
|
377
|
+
if (!settled.compareAndSet(false, true)) return@executeWhenServiceReady
|
|
378
|
+
|
|
356
379
|
downloadService?.setDownloadListener(listener)
|
|
357
380
|
downloadService?.startDownload(
|
|
358
381
|
info.configId,
|
|
@@ -364,16 +387,43 @@ class Downloader(private val context: Context, private val storageManager: com.e
|
|
|
364
387
|
info.isAllowedOverMetered
|
|
365
388
|
)
|
|
366
389
|
}
|
|
390
|
+
|
|
391
|
+
if (settled.get()) return true
|
|
392
|
+
|
|
393
|
+
// The service wasn't connected, so the download is parked until it is. That
|
|
394
|
+
// normally takes milliseconds, but when the system refuses to start the
|
|
395
|
+
// service - a background start on Android 12+, say - nothing ever runs the
|
|
396
|
+
// parked operation, and the task would stay pending in JS with no event
|
|
397
|
+
// either way. Fail it instead of letting it hang.
|
|
398
|
+
Handler(Looper.getMainLooper()).postDelayed({
|
|
399
|
+
if (settled.compareAndSet(false, true)) {
|
|
400
|
+
RNBackgroundDownloaderModuleImpl.logE(TAG, "Download service never started for ${info.configId}")
|
|
401
|
+
listener.onError(info.configId, "Could not start the download service", -1)
|
|
402
|
+
}
|
|
403
|
+
}, DownloadConstants.SERVICE_START_TIMEOUT_MS)
|
|
404
|
+
|
|
405
|
+
return true
|
|
367
406
|
}
|
|
368
407
|
|
|
369
408
|
/**
|
|
370
|
-
* Start a new download using ResumableDownloader (HTTP-based download)
|
|
371
|
-
*
|
|
372
|
-
*
|
|
409
|
+
* Start a new download using ResumableDownloader (HTTP-based download): a UIDT
|
|
410
|
+
* job on Android 14+, the foreground service below that.
|
|
411
|
+
*
|
|
412
|
+
* @param allowServiceFallback when false, a download that can't get a UIDT job
|
|
413
|
+
* is reported back as `false` instead of falling back to the foreground
|
|
414
|
+
* service - used where DownloadManager is still a viable next choice.
|
|
415
|
+
* @return whether a mechanism took the download.
|
|
373
416
|
*/
|
|
374
|
-
fun startResumableDownload(
|
|
375
|
-
|
|
376
|
-
|
|
417
|
+
fun startResumableDownload(
|
|
418
|
+
info: PausedDownloadInfo,
|
|
419
|
+
listener: ResumableDownloader.DownloadListener,
|
|
420
|
+
allowServiceFallback: Boolean = true
|
|
421
|
+
): Boolean {
|
|
422
|
+
val started = startDownloadService(info, listener, allowServiceFallback)
|
|
423
|
+
if (started) {
|
|
424
|
+
RNBackgroundDownloaderModuleImpl.logD(TAG, "Started ResumableDownloader for ${info.configId}")
|
|
425
|
+
}
|
|
426
|
+
return started
|
|
377
427
|
}
|
|
378
428
|
|
|
379
429
|
/**
|
|
@@ -502,14 +552,22 @@ class Downloader(private val context: Context, private val storageManager: com.e
|
|
|
502
552
|
}
|
|
503
553
|
|
|
504
554
|
var recoveredCount = 0
|
|
555
|
+
val stillLive = mutableSetOf<String>()
|
|
505
556
|
for ((configId, info) in recoverable) {
|
|
506
|
-
// Skip if it is already tracked as paused, or still
|
|
557
|
+
// Skip if it is already tracked as paused, or still live as a UIDT job.
|
|
507
558
|
if (pausedDownloads.containsKey(configId)) {
|
|
559
|
+
stillLive.add(configId)
|
|
508
560
|
continue
|
|
509
561
|
}
|
|
562
|
+
// isActiveJob only knows jobs that already started in this process, and
|
|
563
|
+
// this runs at startup - ask the JobScheduler, which still holds the job
|
|
564
|
+
// whether it is running or waiting on a constraint. Recovering one of
|
|
565
|
+
// those as paused would double-track a download that is about to start.
|
|
510
566
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
|
|
511
|
-
UIDTDownloadJobService.isActiveJob(configId)
|
|
567
|
+
(UIDTDownloadJobService.isActiveJob(configId) ||
|
|
568
|
+
UIDTDownloadJobService.isScheduledJob(context, configId))
|
|
512
569
|
) {
|
|
570
|
+
stillLive.add(configId)
|
|
513
571
|
continue
|
|
514
572
|
}
|
|
515
573
|
|
|
@@ -528,8 +586,15 @@ class Downloader(private val context: Context, private val storageManager: com.e
|
|
|
528
586
|
RNBackgroundDownloaderModuleImpl.logD(TAG, "Recovered $recoveredCount interrupted resumable download(s) after force-stop")
|
|
529
587
|
}
|
|
530
588
|
|
|
531
|
-
//
|
|
532
|
-
|
|
589
|
+
// Drop the snapshots recovery consumed, but keep the ones belonging to
|
|
590
|
+
// downloads that are still live: a scheduled job that hasn't transferred a
|
|
591
|
+
// byte yet has no progress callback to re-save its snapshot, so clearing the
|
|
592
|
+
// whole store would lose it if the app is force-stopped again.
|
|
593
|
+
for (configId in recoverable.keys) {
|
|
594
|
+
if (configId !in stillLive) {
|
|
595
|
+
sm.removeActiveDownload(configId)
|
|
596
|
+
}
|
|
597
|
+
}
|
|
533
598
|
}
|
|
534
599
|
|
|
535
600
|
/**
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import com.facebook.react.bridge.Promise
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Bridge helpers shared by the old- and new-architecture module wrappers so the
|
|
7
|
+
* try/resolve/reject boilerplate lives in exactly one place instead of being
|
|
8
|
+
* copy-pasted per method across both source sets.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Runs [block] and resolves the promise with `null` on success; rejects with
|
|
13
|
+
* [errorCode] (plus the exception message and cause) if it throws. Use for
|
|
14
|
+
* fire-and-forget bridge methods that only need to acknowledge completion.
|
|
15
|
+
*/
|
|
16
|
+
inline fun Promise.resolveCatching(errorCode: String, block: () -> Unit) {
|
|
17
|
+
try {
|
|
18
|
+
block()
|
|
19
|
+
resolve(null)
|
|
20
|
+
} catch (e: Exception) {
|
|
21
|
+
reject(errorCode, e.message, e)
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Runs [block], which is responsible for resolving the promise itself (typically by
|
|
27
|
+
* handing it to the impl). Rejects with [errorCode] only if [block] throws before it
|
|
28
|
+
* gets a chance to resolve. Use for methods that return data through the promise.
|
|
29
|
+
*/
|
|
30
|
+
inline fun Promise.rejectOnThrow(errorCode: String, block: () -> Unit) {
|
|
31
|
+
try {
|
|
32
|
+
block()
|
|
33
|
+
} catch (e: Exception) {
|
|
34
|
+
reject(errorCode, e.message, e)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -14,6 +14,8 @@ import com.eko.handlers.OnBegin
|
|
|
14
14
|
import com.eko.handlers.OnProgress
|
|
15
15
|
import com.eko.handlers.OnProgressState
|
|
16
16
|
import com.eko.utils.HeaderUtils
|
|
17
|
+
import com.eko.utils.ReadableConverters
|
|
18
|
+
import com.eko.utils.RedirectResolver
|
|
17
19
|
import com.eko.utils.StorageManager
|
|
18
20
|
import com.facebook.react.bridge.Arguments
|
|
19
21
|
import com.facebook.react.bridge.Promise
|
|
@@ -25,8 +27,6 @@ import com.facebook.react.bridge.WritableMap
|
|
|
25
27
|
import com.facebook.react.modules.core.DeviceEventManagerModule
|
|
26
28
|
import org.json.JSONObject
|
|
27
29
|
import java.io.File
|
|
28
|
-
import java.net.HttpURLConnection
|
|
29
|
-
import java.net.URL
|
|
30
30
|
import java.util.concurrent.ExecutorService
|
|
31
31
|
import java.util.concurrent.Executors
|
|
32
32
|
import java.util.concurrent.Future
|
|
@@ -63,45 +63,25 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
63
63
|
if (isLogsEnabled) Log.e(tag, message)
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (map == null) return null
|
|
72
|
-
val json = JSONObject()
|
|
73
|
-
val iterator = map.keySetIterator()
|
|
74
|
-
while (iterator.hasNextKey()) {
|
|
75
|
-
val key = iterator.nextKey()
|
|
76
|
-
when (map.getType(key)) {
|
|
77
|
-
ReadableType.Null -> json.put(key, JSONObject.NULL)
|
|
78
|
-
ReadableType.Boolean -> json.put(key, map.getBoolean(key))
|
|
79
|
-
ReadableType.Number -> json.put(key, map.getDouble(key))
|
|
80
|
-
ReadableType.String -> json.put(key, map.getString(key))
|
|
81
|
-
ReadableType.Map -> json.put(key, readableMapToJsonObject(map.getMap(key)))
|
|
82
|
-
ReadableType.Array -> json.put(key, readableArrayToJsonArray(map.getArray(key)))
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
return json
|
|
86
|
-
}
|
|
66
|
+
// The live module instance, set once initialize() has run and cleared on
|
|
67
|
+
// invalidate(). Lets native-only entry points (the notification Cancel
|
|
68
|
+
// action) reuse the exact same teardown as a call coming from JS.
|
|
69
|
+
@Volatile
|
|
70
|
+
private var activeInstance: RNBackgroundDownloaderModuleImpl? = null
|
|
87
71
|
|
|
88
72
|
/**
|
|
89
|
-
*
|
|
73
|
+
* Stop a download from native code, going through the same path as a
|
|
74
|
+
* task.stop() call from JS (progress tracking, resumable/DownloadManager
|
|
75
|
+
* cancellation, persisted state cleanup).
|
|
76
|
+
*
|
|
77
|
+
* @return `true` when the module was alive and handled the stop, `false`
|
|
78
|
+
* when there is no instance yet (e.g. a broadcast cold-started the process)
|
|
79
|
+
* and the caller has to fall back to a narrower cancellation.
|
|
90
80
|
*/
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
when (array.getType(i)) {
|
|
96
|
-
ReadableType.Null -> json.put(JSONObject.NULL)
|
|
97
|
-
ReadableType.Boolean -> json.put(array.getBoolean(i))
|
|
98
|
-
ReadableType.Number -> json.put(array.getDouble(i))
|
|
99
|
-
ReadableType.String -> json.put(array.getString(i))
|
|
100
|
-
ReadableType.Map -> json.put(readableMapToJsonObject(array.getMap(i)))
|
|
101
|
-
ReadableType.Array -> json.put(readableArrayToJsonArray(array.getArray(i)))
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
return json
|
|
81
|
+
fun stopTaskFromNative(configId: String): Boolean {
|
|
82
|
+
val instance = activeInstance ?: return false
|
|
83
|
+
instance.stopTask(configId)
|
|
84
|
+
return true
|
|
105
85
|
}
|
|
106
86
|
}
|
|
107
87
|
|
|
@@ -295,9 +275,11 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
295
275
|
}
|
|
296
276
|
|
|
297
277
|
fun setMaxParallelDownloads(max: Int) {
|
|
298
|
-
//
|
|
299
|
-
//
|
|
300
|
-
|
|
278
|
+
// Caps the transfers the library's own downloader runs at once - the path
|
|
279
|
+
// with no scheduler in front of it. DownloadManager and the JobScheduler
|
|
280
|
+
// queue their own work, so downloads running through them are unaffected.
|
|
281
|
+
ResumableDownloader.setMaxConcurrentTransfers(max)
|
|
282
|
+
logD(NAME, "setMaxParallelDownloads: $max")
|
|
301
283
|
}
|
|
302
284
|
|
|
303
285
|
fun setAllowsCellularAccess(allows: Boolean) {
|
|
@@ -310,6 +292,8 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
310
292
|
fun setNotificationGroupingConfig(config: ReadableMap) {
|
|
311
293
|
val enabled = if (config.hasKey("enabled")) config.getBoolean("enabled") else false
|
|
312
294
|
val showNotificationsEnabled = if (config.hasKey("showNotificationsEnabled")) config.getBoolean("showNotificationsEnabled") else false
|
|
295
|
+
val showCompletionNotification = if (config.hasKey("showCompletionNotification")) config.getBoolean("showCompletionNotification") else false
|
|
296
|
+
val showCancelAction = if (config.hasKey("showCancelAction")) config.getBoolean("showCancelAction") else false
|
|
313
297
|
val mode = if (config.hasKey("mode")) config.getString("mode") ?: "individual" else "individual"
|
|
314
298
|
val texts = if (config.hasKey("texts")) config.getMap("texts") else null
|
|
315
299
|
|
|
@@ -324,15 +308,23 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
324
308
|
|
|
325
309
|
// Store the config for use by UIDTDownloadJobService
|
|
326
310
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
|
327
|
-
UIDTDownloadJobService.setNotificationGroupingConfig(
|
|
311
|
+
UIDTDownloadJobService.setNotificationGroupingConfig(
|
|
312
|
+
enabled,
|
|
313
|
+
showNotificationsEnabled,
|
|
314
|
+
showCompletionNotification,
|
|
315
|
+
showCancelAction,
|
|
316
|
+
mode,
|
|
317
|
+
textsMap
|
|
318
|
+
)
|
|
328
319
|
}
|
|
329
320
|
|
|
330
|
-
logD(NAME, "setNotificationGroupingConfig: enabled=$enabled, showNotificationsEnabled=$showNotificationsEnabled, mode=$mode, texts=$textsMap")
|
|
321
|
+
logD(NAME, "setNotificationGroupingConfig: enabled=$enabled, showNotificationsEnabled=$showNotificationsEnabled, showCompletionNotification=$showCompletionNotification, showCancelAction=$showCancelAction, mode=$mode, texts=$textsMap")
|
|
331
322
|
}
|
|
332
323
|
|
|
333
324
|
fun initialize() {
|
|
334
325
|
ee = reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
|
|
335
326
|
isInitialized = true
|
|
327
|
+
activeInstance = this
|
|
336
328
|
registerDownloadReceiver()
|
|
337
329
|
|
|
338
330
|
// Set the listener for resumable downloads (used by the background service)
|
|
@@ -378,6 +370,10 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
378
370
|
|
|
379
371
|
unregisterDownloadReceiver()
|
|
380
372
|
downloader.unbindService()
|
|
373
|
+
|
|
374
|
+
if (activeInstance === this) {
|
|
375
|
+
activeInstance = null
|
|
376
|
+
}
|
|
381
377
|
}
|
|
382
378
|
|
|
383
379
|
private fun registerDownloadReceiver() {
|
|
@@ -599,88 +595,6 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
599
595
|
)
|
|
600
596
|
}
|
|
601
597
|
|
|
602
|
-
/**
|
|
603
|
-
* Resolve redirects for a URL up to maxRedirects limit
|
|
604
|
-
* @param originalUrl The original URL to follow
|
|
605
|
-
* @param maxRedirects Maximum number of redirects to follow (0 means no redirect resolution)
|
|
606
|
-
* @param headers Headers to include in redirect resolution requests
|
|
607
|
-
* @return The final resolved URL, or original URL if maxRedirects is 0 or resolution fails
|
|
608
|
-
*/
|
|
609
|
-
private fun resolveRedirects(originalUrl: String, maxRedirects: Int, headers: ReadableMap?): String {
|
|
610
|
-
if (maxRedirects <= 0) {
|
|
611
|
-
return originalUrl
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
try {
|
|
615
|
-
var currentUrl = originalUrl
|
|
616
|
-
var redirectCount = 0
|
|
617
|
-
|
|
618
|
-
while (redirectCount < maxRedirects) {
|
|
619
|
-
val url = URL(currentUrl)
|
|
620
|
-
val connection = url.openConnection() as HttpURLConnection
|
|
621
|
-
|
|
622
|
-
// Add headers to the redirect resolution request
|
|
623
|
-
HeaderUtils.applyToConnection(connection, headers)
|
|
624
|
-
|
|
625
|
-
// Add default headers for consistency with DownloadManager
|
|
626
|
-
HeaderUtils.applyDefaultHeaders(connection, headers)
|
|
627
|
-
|
|
628
|
-
connection.instanceFollowRedirects = false
|
|
629
|
-
connection.requestMethod = "HEAD" // Use HEAD to avoid downloading content
|
|
630
|
-
connection.connectTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
|
|
631
|
-
connection.readTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
|
|
632
|
-
|
|
633
|
-
val responseCode = connection.responseCode
|
|
634
|
-
|
|
635
|
-
if (responseCode in 300..399) {
|
|
636
|
-
// This is a redirect
|
|
637
|
-
val location = connection.getHeaderField("Location")
|
|
638
|
-
if (location == null) {
|
|
639
|
-
logW(NAME, "Redirect response without Location header at: $currentUrl")
|
|
640
|
-
break
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
// Handle relative URLs
|
|
644
|
-
currentUrl = when {
|
|
645
|
-
location.startsWith("/") -> {
|
|
646
|
-
val baseUrl = URL(currentUrl)
|
|
647
|
-
"${baseUrl.protocol}://${baseUrl.host}$location"
|
|
648
|
-
}
|
|
649
|
-
!location.startsWith("http") -> {
|
|
650
|
-
val baseUrl = URL(currentUrl)
|
|
651
|
-
"${baseUrl.protocol}://${baseUrl.host}/$location"
|
|
652
|
-
}
|
|
653
|
-
else -> location
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
logD(NAME, "Redirect ${redirectCount + 1}/$maxRedirects: $currentUrl -> $location")
|
|
657
|
-
redirectCount++
|
|
658
|
-
} else {
|
|
659
|
-
// Not a redirect, we've found the final URL
|
|
660
|
-
break
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
connection.disconnect()
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
if (redirectCount >= maxRedirects) {
|
|
667
|
-
logW(
|
|
668
|
-
NAME,
|
|
669
|
-
"Reached maximum redirects ($maxRedirects) for URL: $originalUrl. Final URL: $currentUrl"
|
|
670
|
-
)
|
|
671
|
-
} else {
|
|
672
|
-
logD(NAME, "Resolved URL after $redirectCount redirects: $currentUrl")
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
return currentUrl
|
|
676
|
-
|
|
677
|
-
} catch (e: Exception) {
|
|
678
|
-
logE(NAME, "Failed to resolve redirects for URL: $originalUrl. Error: ${e.message}")
|
|
679
|
-
// Return original URL if redirect resolution fails
|
|
680
|
-
return originalUrl
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
|
|
684
598
|
fun download(options: ReadableMap) {
|
|
685
599
|
// Ensure event emitter is initialized before starting download
|
|
686
600
|
// This fixes issues on first app install where download() might be called
|
|
@@ -704,7 +618,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
704
618
|
// If passed as object, convert to JSON string properly
|
|
705
619
|
try {
|
|
706
620
|
val map = options.getMap("metadata")
|
|
707
|
-
|
|
621
|
+
ReadableConverters.toJsonObject(map)?.toString() ?: "{}"
|
|
708
622
|
} catch (e: Exception) {
|
|
709
623
|
logW(NAME, "Failed to convert metadata map to string: ${e.message}")
|
|
710
624
|
"{}"
|
|
@@ -752,7 +666,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
752
666
|
// Resolve redirects if maxRedirects is specified
|
|
753
667
|
if (maxRedirects > 0) {
|
|
754
668
|
logD(NAME, "Resolving redirects for URL: $url (maxRedirects: $maxRedirects)")
|
|
755
|
-
url =
|
|
669
|
+
url = RedirectResolver.resolve(url, maxRedirects, headers)
|
|
756
670
|
logD(NAME, "Final resolved URL: $url")
|
|
757
671
|
}
|
|
758
672
|
|
|
@@ -818,8 +732,12 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
818
732
|
}
|
|
819
733
|
}
|
|
820
734
|
|
|
821
|
-
// Helper function to
|
|
822
|
-
|
|
735
|
+
// Helper function to run the download through the library's own downloader:
|
|
736
|
+
// a UIDT job on Android 14+, the foreground service below that.
|
|
737
|
+
// Returns whether a mechanism took it; with allowServiceFallback = false a
|
|
738
|
+
// download that can't get a UIDT job comes back unstarted so the caller can
|
|
739
|
+
// try DownloadManager instead.
|
|
740
|
+
fun startWithResumableDownloader(allowServiceFallback: Boolean = true): Boolean {
|
|
823
741
|
val spec = Downloader.PausedDownloadInfo(
|
|
824
742
|
configId = id,
|
|
825
743
|
url = url,
|
|
@@ -846,7 +764,17 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
846
764
|
downloader.saveActiveDownloadSnapshot(spec)
|
|
847
765
|
configIdToLastSnapshotMs[id] = System.currentTimeMillis()
|
|
848
766
|
}
|
|
849
|
-
|
|
767
|
+
|
|
768
|
+
val started = downloader.startResumableDownload(spec, resumableDownloadListener, allowServiceFallback)
|
|
769
|
+
if (!started) {
|
|
770
|
+
// Nothing took the download - drop the bookkeeping so the mechanism the
|
|
771
|
+
// caller tries next starts from a clean slate
|
|
772
|
+
synchronized(sharedLock) {
|
|
773
|
+
downloader.removeActiveDownloadSnapshot(id)
|
|
774
|
+
configIdToLastSnapshotMs.remove(id)
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
return started
|
|
850
778
|
}
|
|
851
779
|
|
|
852
780
|
// On Android 16+ (API 36), DownloadManager has strict path restrictions and throws
|
|
@@ -857,6 +785,21 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
857
785
|
return
|
|
858
786
|
}
|
|
859
787
|
|
|
788
|
+
// On Android 14/15, prefer a UIDT job: it isn't subject to App Standby
|
|
789
|
+
// quotas, and it is the only path where the library manages the download's
|
|
790
|
+
// notification, so grouping, the completion notification, the Cancel action
|
|
791
|
+
// and per-download titles work for a fresh download instead of only after a
|
|
792
|
+
// pause/resume. DownloadManager stays as the fallback for when the job can't
|
|
793
|
+
// be scheduled - most importantly download() called from the background,
|
|
794
|
+
// where user-initiated jobs are refused.
|
|
795
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
|
796
|
+
if (startWithResumableDownloader(allowServiceFallback = false)) {
|
|
797
|
+
logD(NAME, "Android 14+: using a UIDT job for download: $id")
|
|
798
|
+
return
|
|
799
|
+
}
|
|
800
|
+
logD(NAME, "Android 14+: no UIDT job for $id, using DownloadManager")
|
|
801
|
+
}
|
|
802
|
+
|
|
860
803
|
if (isValidExternalPath) {
|
|
861
804
|
// Use DownloadManager with valid external storage path
|
|
862
805
|
// Download directly to final destination to avoid file duplication
|
|
@@ -1164,11 +1107,16 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
1164
1107
|
logE(NAME, "getExistingDownloadTasks: ${Log.getStackTraceString(e)}")
|
|
1165
1108
|
}
|
|
1166
1109
|
|
|
1167
|
-
// Phase 2: Query
|
|
1168
|
-
// On Android 14+, downloads may use UIDT instead of DownloadManager
|
|
1110
|
+
// Phase 2: Query UIDT jobs (Android 14+)
|
|
1111
|
+
// On Android 14+, downloads may use UIDT instead of DownloadManager.
|
|
1112
|
+
// Scheduled-but-not-yet-started jobs are included: they have no registry
|
|
1113
|
+
// entry (that is filled in onStartJob), so without them a download waiting
|
|
1114
|
+
// on its network constraint - or every job at all after a process restart -
|
|
1115
|
+
// would be missing from the list while its transfer is still coming.
|
|
1169
1116
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
|
1170
1117
|
try {
|
|
1171
|
-
val uidtJobs = UIDTDownloadJobService.getAllActiveJobs()
|
|
1118
|
+
val uidtJobs = UIDTDownloadJobService.getAllActiveJobs() +
|
|
1119
|
+
UIDTDownloadJobService.getScheduledJobs(reactContext)
|
|
1172
1120
|
|
|
1173
1121
|
for (job in uidtJobs) {
|
|
1174
1122
|
// Skip if already processed from DownloadManager
|
|
@@ -1435,7 +1383,7 @@ class RNBackgroundDownloaderModuleImpl(private val reactContext: ReactApplicatio
|
|
|
1435
1383
|
ReadableType.Map -> {
|
|
1436
1384
|
try {
|
|
1437
1385
|
val map = options.getMap("metadata")
|
|
1438
|
-
|
|
1386
|
+
ReadableConverters.toJsonObject(map)?.toString() ?: "{}"
|
|
1439
1387
|
} catch (e: Exception) {
|
|
1440
1388
|
logW(NAME, "Failed to convert metadata map to string: ${e.message}")
|
|
1441
1389
|
"{}"
|