@kesha-antonov/react-native-background-downloader 4.5.9 → 4.6.1
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 +69 -4
- 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/RNBackgroundDownloaderModuleImpl.kt +81 -11
- 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/res/xml/rnbgd_file_paths.xml +23 -0
- 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/lib/NativeRNBackgroundDownloader.d.ts +2 -0
- package/lib/config.d.ts +2 -0
- package/lib/config.js +3 -0
- package/lib/index.d.ts +1 -1
- package/lib/index.js +9 -2
- package/lib/notifications.js +4 -3
- package/lib/types.d.ts +19 -0
- package/package.json +3 -2
- package/react-native-background-downloader.podspec +14 -1
- package/src/NativeRNBackgroundDownloader.ts +8 -1
- package/src/config.ts +5 -0
- package/src/index.ts +19 -1
- package/src/notifications.ts +1 -0
- package/src/types.ts +19 -0
|
@@ -3,14 +3,21 @@ package com.eko.uidt
|
|
|
3
3
|
import android.app.Notification
|
|
4
4
|
import android.app.NotificationChannel
|
|
5
5
|
import android.app.NotificationManager
|
|
6
|
+
import android.app.PendingIntent
|
|
6
7
|
import android.app.job.JobService
|
|
7
8
|
import android.content.Context
|
|
9
|
+
import android.content.Intent
|
|
10
|
+
import android.content.pm.PackageManager
|
|
11
|
+
import android.net.Uri
|
|
8
12
|
import android.os.Build
|
|
9
13
|
import androidx.annotation.RequiresApi
|
|
10
14
|
import androidx.core.app.NotificationCompat
|
|
15
|
+
import androidx.core.content.FileProvider
|
|
11
16
|
import com.eko.RNBackgroundDownloaderModuleImpl
|
|
12
17
|
import com.eko.UIDTDownloadJobService
|
|
13
18
|
import com.eko.utils.ProgressUtils
|
|
19
|
+
import java.io.File
|
|
20
|
+
import java.net.URLConnection
|
|
14
21
|
|
|
15
22
|
/**
|
|
16
23
|
* Manages all notification-related operations for UIDT downloads.
|
|
@@ -23,13 +30,19 @@ object UIDTNotificationManager {
|
|
|
23
30
|
get() = UIDTJobRegistry.notificationConfig
|
|
24
31
|
|
|
25
32
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* even across app restarts.
|
|
33
|
+
* The notification ID for a download. Stable for as long as the download is
|
|
34
|
+
* live, and never shared with another live download - see [UIDTNotificationIds].
|
|
29
35
|
*/
|
|
30
|
-
fun getNotificationIdForConfig(configId: String): Int
|
|
31
|
-
|
|
32
|
-
|
|
36
|
+
fun getNotificationIdForConfig(configId: String): Int =
|
|
37
|
+
UIDTNotificationIds.progressIdFor(configId)
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Notification ID for the one-shot "download complete" notification.
|
|
41
|
+
* Lives in a disjoint range from [getNotificationIdForConfig] so it can
|
|
42
|
+
* never collide with another download's in-progress notification.
|
|
43
|
+
*/
|
|
44
|
+
fun getFinishedNotificationIdForConfig(configId: String): Int =
|
|
45
|
+
UIDTNotificationIds.finishedIdFor(configId)
|
|
33
46
|
|
|
34
47
|
/**
|
|
35
48
|
* Create notification channels for UIDT jobs.
|
|
@@ -74,7 +87,55 @@ object UIDTNotificationManager {
|
|
|
74
87
|
setSound(null, null)
|
|
75
88
|
}
|
|
76
89
|
notificationManager.createNotificationChannel(ultraSilentChannel)
|
|
90
|
+
|
|
91
|
+
// Channel for the one-shot "download complete" notification
|
|
92
|
+
// (IMPORTANCE_DEFAULT so it actually alerts, unlike the progress channel)
|
|
93
|
+
val finishedChannel = NotificationChannel(
|
|
94
|
+
UIDTConstants.NOTIFICATION_CHANNEL_FINISHED_ID,
|
|
95
|
+
"Download Complete",
|
|
96
|
+
NotificationManager.IMPORTANCE_DEFAULT
|
|
97
|
+
).apply {
|
|
98
|
+
description = "Notifies when a background download has finished"
|
|
99
|
+
}
|
|
100
|
+
notificationManager.createNotificationChannel(finishedChannel)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Build a PendingIntent that fires the in-notification "Cancel" action.
|
|
106
|
+
* The receiver lives in [CancelDownloadReceiver] and calls
|
|
107
|
+
* [UIDTJobManager.cancelJob] when triggered.
|
|
108
|
+
*/
|
|
109
|
+
/**
|
|
110
|
+
* Add the "Cancel" action to [builder] when the app opted into it via
|
|
111
|
+
* `showCancelAction`. The label goes through the notification texts so it
|
|
112
|
+
* stays localizable like every other string this library renders.
|
|
113
|
+
*/
|
|
114
|
+
private fun applyCancelAction(builder: NotificationCompat.Builder, context: Context, configId: String) {
|
|
115
|
+
if (!config.showCancelAction) return
|
|
116
|
+
|
|
117
|
+
builder.addAction(
|
|
118
|
+
android.R.drawable.ic_menu_close_clear_cancel,
|
|
119
|
+
config.getText("downloadCancel"),
|
|
120
|
+
buildCancelPendingIntent(context, configId),
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private fun buildCancelPendingIntent(context: Context, configId: String): PendingIntent {
|
|
125
|
+
val intent = Intent(context, CancelDownloadReceiver::class.java).apply {
|
|
126
|
+
action = CancelDownloadReceiver.ACTION_CANCEL_DOWNLOAD
|
|
127
|
+
setPackage(context.packageName)
|
|
128
|
+
putExtra(CancelDownloadReceiver.EXTRA_CONFIG_ID, configId)
|
|
77
129
|
}
|
|
130
|
+
// Use stable notification id as request code so subsequent updates
|
|
131
|
+
// reuse the same PendingIntent slot.
|
|
132
|
+
val requestCode = getNotificationIdForConfig(configId)
|
|
133
|
+
return PendingIntent.getBroadcast(
|
|
134
|
+
context,
|
|
135
|
+
requestCode,
|
|
136
|
+
intent,
|
|
137
|
+
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
|
138
|
+
)
|
|
78
139
|
}
|
|
79
140
|
|
|
80
141
|
/**
|
|
@@ -84,7 +145,8 @@ object UIDTNotificationManager {
|
|
|
84
145
|
context: Context,
|
|
85
146
|
configId: String,
|
|
86
147
|
groupId: String = "",
|
|
87
|
-
groupName: String = ""
|
|
148
|
+
groupName: String = "",
|
|
149
|
+
customTitle: String = ""
|
|
88
150
|
): Notification {
|
|
89
151
|
val isSummaryOnlyMode = config.mode == NotificationGroupingMode.SUMMARY_ONLY
|
|
90
152
|
|
|
@@ -123,10 +185,10 @@ object UIDTNotificationManager {
|
|
|
123
185
|
.build()
|
|
124
186
|
}
|
|
125
187
|
|
|
126
|
-
val title =
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
config.getText("downloadTitle")
|
|
188
|
+
val title = when {
|
|
189
|
+
customTitle.isNotEmpty() -> customTitle
|
|
190
|
+
config.groupingEnabled && groupName.isNotEmpty() -> groupName
|
|
191
|
+
else -> config.getText("downloadTitle")
|
|
130
192
|
}
|
|
131
193
|
val startingText = config.getText("downloadStarting")
|
|
132
194
|
|
|
@@ -140,6 +202,8 @@ object UIDTNotificationManager {
|
|
|
140
202
|
.setShowWhen(false)
|
|
141
203
|
.setProgress(0, 0, true)
|
|
142
204
|
|
|
205
|
+
applyCancelAction(builder, context, configId)
|
|
206
|
+
|
|
143
207
|
// Apply grouping when enabled and groupId is provided
|
|
144
208
|
if (config.groupingEnabled && groupId.isNotEmpty()) {
|
|
145
209
|
val groupKey = "${UIDTConstants.NOTIFICATION_GROUP_KEY}_$groupId"
|
|
@@ -154,6 +218,7 @@ object UIDTNotificationManager {
|
|
|
154
218
|
*/
|
|
155
219
|
fun updateProgressNotification(
|
|
156
220
|
context: Context,
|
|
221
|
+
configId: String,
|
|
157
222
|
jobState: JobState,
|
|
158
223
|
bytesDownloaded: Long,
|
|
159
224
|
bytesTotal: Long
|
|
@@ -173,10 +238,10 @@ object UIDTNotificationManager {
|
|
|
173
238
|
|
|
174
239
|
val progress = ProgressUtils.calculateProgress(bytesDownloaded, bytesTotal)
|
|
175
240
|
|
|
176
|
-
val title =
|
|
177
|
-
jobState.
|
|
178
|
-
|
|
179
|
-
config.getText("downloadTitle")
|
|
241
|
+
val title = when {
|
|
242
|
+
jobState.customTitle.isNotEmpty() -> jobState.customTitle
|
|
243
|
+
config.groupingEnabled && jobState.groupName.isNotEmpty() -> jobState.groupName
|
|
244
|
+
else -> config.getText("downloadTitle")
|
|
180
245
|
}
|
|
181
246
|
|
|
182
247
|
val progressText = config.getText("downloadProgress", "progress" to progress)
|
|
@@ -191,6 +256,8 @@ object UIDTNotificationManager {
|
|
|
191
256
|
.setShowWhen(false)
|
|
192
257
|
.setProgress(100, progress, bytesTotal <= 0)
|
|
193
258
|
|
|
259
|
+
applyCancelAction(builder, context, configId)
|
|
260
|
+
|
|
194
261
|
// Apply grouping when enabled
|
|
195
262
|
if (config.groupingEnabled && jobState.groupId.isNotEmpty()) {
|
|
196
263
|
val groupKey = "${UIDTConstants.NOTIFICATION_GROUP_KEY}_${jobState.groupId}"
|
|
@@ -249,10 +316,10 @@ object UIDTNotificationManager {
|
|
|
249
316
|
// Update tracking state so next onProgress knows current state
|
|
250
317
|
jobState.lastNotifiedProgress = progress
|
|
251
318
|
|
|
252
|
-
val title =
|
|
253
|
-
jobState.
|
|
254
|
-
|
|
255
|
-
config.getText("downloadTitle")
|
|
319
|
+
val title = when {
|
|
320
|
+
jobState.customTitle.isNotEmpty() -> jobState.customTitle
|
|
321
|
+
config.groupingEnabled && jobState.groupName.isNotEmpty() -> jobState.groupName
|
|
322
|
+
else -> config.getText("downloadTitle")
|
|
256
323
|
}
|
|
257
324
|
|
|
258
325
|
val builder = NotificationCompat.Builder(context, UIDTConstants.NOTIFICATION_CHANNEL_ID)
|
|
@@ -451,6 +518,7 @@ object UIDTNotificationManager {
|
|
|
451
518
|
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
452
519
|
val notificationId = getNotificationIdForConfig(configId)
|
|
453
520
|
notificationManager.cancel(notificationId)
|
|
521
|
+
UIDTNotificationIds.release(configId)
|
|
454
522
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Cancelled notification $notificationId for $configId")
|
|
455
523
|
}
|
|
456
524
|
|
|
@@ -514,4 +582,163 @@ object UIDTNotificationManager {
|
|
|
514
582
|
.setSmallIcon(android.R.drawable.stat_sys_download)
|
|
515
583
|
.build()
|
|
516
584
|
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Show a one-shot "download complete" notification that persists after the
|
|
588
|
+
* UIDT job is removed by the system. The title is [customTitle] when the
|
|
589
|
+
* download carries one, otherwise the configured "downloadFinished" text;
|
|
590
|
+
* the body is the supplied [fileName]. Posted via NotificationManager (not
|
|
591
|
+
* tied to the JobService) so it survives the service shutdown.
|
|
592
|
+
*
|
|
593
|
+
* Requires the app to opt in with `showCompletionNotification`, since this
|
|
594
|
+
* one alerts on its own IMPORTANCE_DEFAULT channel.
|
|
595
|
+
*
|
|
596
|
+
* Nothing is posted in summaryOnly mode - that mode exists so a batch of
|
|
597
|
+
* downloads produces a single notification, and one completion notification
|
|
598
|
+
* per finished file would defeat it.
|
|
599
|
+
*
|
|
600
|
+
* Tapping the notification fires ACTION_VIEW with a FileProvider content
|
|
601
|
+
* URI for [destination] so the system file viewer / Files app can open it.
|
|
602
|
+
*/
|
|
603
|
+
fun showFinishedNotification(
|
|
604
|
+
context: Context,
|
|
605
|
+
configId: String,
|
|
606
|
+
destination: String,
|
|
607
|
+
fileName: String,
|
|
608
|
+
groupId: String = "",
|
|
609
|
+
customTitle: String = "",
|
|
610
|
+
) {
|
|
611
|
+
if (!config.showNotificationsEnabled || !config.showCompletionNotification) return
|
|
612
|
+
|
|
613
|
+
val isSummaryOnlyMode = config.mode == NotificationGroupingMode.SUMMARY_ONLY
|
|
614
|
+
if (isSummaryOnlyMode && config.groupingEnabled && groupId.isNotEmpty()) {
|
|
615
|
+
RNBackgroundDownloaderModuleImpl.logD(
|
|
616
|
+
UIDTConstants.TAG,
|
|
617
|
+
"Skipping finished notification for $configId (summaryOnly mode)",
|
|
618
|
+
)
|
|
619
|
+
return
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
createNotificationChannels(context)
|
|
623
|
+
|
|
624
|
+
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
|
625
|
+
// Use an id from a disjoint range so it is neither removed by the REMOVE
|
|
626
|
+
// policy applied to the ongoing notification nor collides with another
|
|
627
|
+
// download's in-progress notification.
|
|
628
|
+
val notificationId = getFinishedNotificationIdForConfig(configId)
|
|
629
|
+
|
|
630
|
+
// Same precedence as the progress notification: a per-download title
|
|
631
|
+
// wins over the configured default text.
|
|
632
|
+
val title = customTitle.ifEmpty { config.getText("downloadFinished") }
|
|
633
|
+
|
|
634
|
+
// Build a PendingIntent that lets the user open the saved file with the
|
|
635
|
+
// system viewer (Files app / Drive / Extract...). We resolve the file
|
|
636
|
+
// through the library-owned FileProvider first (declared in this
|
|
637
|
+
// library's manifest, so it works with no host-app configuration) and
|
|
638
|
+
// only fall back to auto-detecting a host-app provider if that fails.
|
|
639
|
+
// If neither produces a URI the tap action is simply omitted and the
|
|
640
|
+
// notification is still posted.
|
|
641
|
+
val pendingIntent: PendingIntent? = try {
|
|
642
|
+
val file = File(destination)
|
|
643
|
+
val uri = resolveContentUri(context, file)
|
|
644
|
+
val mime = URLConnection.guessContentTypeFromName(fileName) ?: "*/*"
|
|
645
|
+
val viewIntent = Intent(Intent.ACTION_VIEW).apply {
|
|
646
|
+
setDataAndType(uri, mime)
|
|
647
|
+
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
|
648
|
+
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
649
|
+
}
|
|
650
|
+
val chooser = Intent.createChooser(viewIntent, title).apply {
|
|
651
|
+
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
|
652
|
+
}
|
|
653
|
+
PendingIntent.getActivity(
|
|
654
|
+
context,
|
|
655
|
+
notificationId,
|
|
656
|
+
chooser,
|
|
657
|
+
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
|
658
|
+
)
|
|
659
|
+
} catch (e: Exception) {
|
|
660
|
+
RNBackgroundDownloaderModuleImpl.logW(UIDTConstants.TAG, "Failed to build pendingIntent for finished noti: ${e.message}")
|
|
661
|
+
null
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
val builder = NotificationCompat.Builder(context, UIDTConstants.NOTIFICATION_CHANNEL_FINISHED_ID)
|
|
665
|
+
.setContentTitle(title)
|
|
666
|
+
.setContentText(fileName)
|
|
667
|
+
.setSmallIcon(android.R.drawable.stat_sys_download_done)
|
|
668
|
+
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
|
669
|
+
.setAutoCancel(true)
|
|
670
|
+
if (pendingIntent != null) builder.setContentIntent(pendingIntent)
|
|
671
|
+
|
|
672
|
+
// Deliberately NOT part of the download's notification group: when the
|
|
673
|
+
// last job of a group finishes, cancelSummaryNotification tears down
|
|
674
|
+
// every notification carrying that group key, which would wipe these
|
|
675
|
+
// completion notifications the moment they are posted. The shade still
|
|
676
|
+
// bundles them on its own once there are enough of them.
|
|
677
|
+
notificationManager.notify(notificationId, builder.build())
|
|
678
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Posted finished notification $notificationId for $configId")
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* Resolve a content:// URI for [file], preferring this library's own
|
|
683
|
+
* FileProvider (authority "${packageName}.rnbackgrounddownloader.fileprovider",
|
|
684
|
+
* declared in the library manifest with [RNBGDFileProvider] +
|
|
685
|
+
* rnbgd_file_paths.xml) so tap-to-open works with no host-app setup.
|
|
686
|
+
*
|
|
687
|
+
* If the file falls outside the library provider's configured roots — e.g.
|
|
688
|
+
* a consumer downloads to a directory not covered by rnbgd_file_paths.xml —
|
|
689
|
+
* fall back to auto-detecting a host-app FileProvider authority. Throws if
|
|
690
|
+
* neither can serve the file; the caller catches and omits the tap action.
|
|
691
|
+
*/
|
|
692
|
+
private fun resolveContentUri(context: Context, file: File): Uri {
|
|
693
|
+
val libraryAuthority = "${context.packageName}.rnbackgrounddownloader.fileprovider"
|
|
694
|
+
return try {
|
|
695
|
+
FileProvider.getUriForFile(context, libraryAuthority, file)
|
|
696
|
+
} catch (e: IllegalArgumentException) {
|
|
697
|
+
// File not under any root declared in rnbgd_file_paths.xml; try a
|
|
698
|
+
// host-app provider as a secondary path.
|
|
699
|
+
RNBackgroundDownloaderModuleImpl.logW(
|
|
700
|
+
UIDTConstants.TAG,
|
|
701
|
+
"Library FileProvider can't serve $file (${e.message}); trying host-app provider",
|
|
702
|
+
)
|
|
703
|
+
val fallbackAuthority = resolveFileProviderAuthority(context)
|
|
704
|
+
FileProvider.getUriForFile(context, fallbackAuthority, file)
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Resolve the host app's FileProvider authority at runtime by scanning the
|
|
710
|
+
* providers registered in its manifest, rather than assuming a fixed
|
|
711
|
+
* "${packageName}.provider". Used only as a secondary fallback when the
|
|
712
|
+
* library-owned provider cannot serve a file (see [resolveContentUri]).
|
|
713
|
+
*
|
|
714
|
+
* Preference order: an authority equal to "${packageName}.provider", then
|
|
715
|
+
* any authority owned by this package, then the conventional default as a
|
|
716
|
+
* last resort (which may still throw in getUriForFile if unregistered —
|
|
717
|
+
* that is caught by the caller).
|
|
718
|
+
*/
|
|
719
|
+
private fun resolveFileProviderAuthority(context: Context): String {
|
|
720
|
+
val packageName = context.packageName
|
|
721
|
+
val default = "$packageName.provider"
|
|
722
|
+
// Skip our own provider — resolveContentUri already tried it.
|
|
723
|
+
val libraryAuthority = "$packageName.rnbackgrounddownloader.fileprovider"
|
|
724
|
+
return try {
|
|
725
|
+
val flags = PackageManager.GET_PROVIDERS
|
|
726
|
+
val providers = context.packageManager
|
|
727
|
+
.getPackageInfo(packageName, flags)
|
|
728
|
+
.providers
|
|
729
|
+
?.filter { it.name == "androidx.core.content.FileProvider" || it.name.endsWith("FileProvider") }
|
|
730
|
+
?.mapNotNull { it.authority }
|
|
731
|
+
?.flatMap { it.split(';') }
|
|
732
|
+
?.filter { it != libraryAuthority }
|
|
733
|
+
?: emptyList()
|
|
734
|
+
|
|
735
|
+
providers.firstOrNull { it == default }
|
|
736
|
+
?: providers.firstOrNull { it.startsWith(packageName) }
|
|
737
|
+
?: providers.firstOrNull()
|
|
738
|
+
?: default
|
|
739
|
+
} catch (e: Exception) {
|
|
740
|
+
RNBackgroundDownloaderModuleImpl.logW(UIDTConstants.TAG, "Failed to resolve FileProvider authority: ${e.message}")
|
|
741
|
+
default
|
|
742
|
+
}
|
|
743
|
+
}
|
|
517
744
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
<?xml version="1.0" encoding="utf-8"?>
|
|
2
|
+
<!--
|
|
3
|
+
Paths the library-owned RNBGDFileProvider can expose via getUriForFile.
|
|
4
|
+
|
|
5
|
+
Downloads default to the app's internal files dir (documents == filesDir),
|
|
6
|
+
but consumers may pass any `destination` under the app's private storage, so
|
|
7
|
+
every app-scoped root is covered. Names are arbitrary URI path segments and
|
|
8
|
+
do not need to match the host app's own file_paths.xml.
|
|
9
|
+
|
|
10
|
+
Only app-scoped roots are declared — the directories this library writes to.
|
|
11
|
+
Shared/public storage is deliberately not exposed; a download saved outside
|
|
12
|
+
these roots falls back to a host-app FileProvider (see resolveContentUri).
|
|
13
|
+
-->
|
|
14
|
+
<paths>
|
|
15
|
+
<!-- context.getFilesDir() — default download location (documents) -->
|
|
16
|
+
<files-path name="rnbgd_files" path="." />
|
|
17
|
+
<!-- context.getCacheDir() -->
|
|
18
|
+
<cache-path name="rnbgd_cache" path="." />
|
|
19
|
+
<!-- context.getExternalFilesDir(null) -->
|
|
20
|
+
<external-files-path name="rnbgd_external_files" path="." />
|
|
21
|
+
<!-- context.getExternalCacheDir() -->
|
|
22
|
+
<external-cache-path name="rnbgd_external_cache" path="." />
|
|
23
|
+
</paths>
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import okhttp3.mockwebserver.Dispatcher
|
|
4
|
+
import okhttp3.mockwebserver.MockResponse
|
|
5
|
+
import okhttp3.mockwebserver.MockWebServer
|
|
6
|
+
import okhttp3.mockwebserver.RecordedRequest
|
|
7
|
+
import org.junit.After
|
|
8
|
+
import org.junit.Assert.assertEquals
|
|
9
|
+
import org.junit.Assert.assertTrue
|
|
10
|
+
import org.junit.Before
|
|
11
|
+
import org.junit.Rule
|
|
12
|
+
import org.junit.Test
|
|
13
|
+
import org.junit.rules.TemporaryFolder
|
|
14
|
+
import org.junit.runner.RunWith
|
|
15
|
+
import org.robolectric.RobolectricTestRunner
|
|
16
|
+
import org.robolectric.annotation.Config
|
|
17
|
+
import java.util.concurrent.ConcurrentHashMap
|
|
18
|
+
import java.util.concurrent.CopyOnWriteArrayList
|
|
19
|
+
import java.util.concurrent.CountDownLatch
|
|
20
|
+
import java.util.concurrent.TimeUnit
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The library's own downloader is the one path with no scheduler in front of it:
|
|
24
|
+
* before `maxParallelDownloads` applied here, every download took a thread and a
|
|
25
|
+
* socket of its own the moment it started. These pin the cap that replaced that.
|
|
26
|
+
*/
|
|
27
|
+
@RunWith(RobolectricTestRunner::class)
|
|
28
|
+
@Config(sdk = [34])
|
|
29
|
+
class ResumableDownloaderConcurrencyTest {
|
|
30
|
+
|
|
31
|
+
@get:Rule
|
|
32
|
+
val tempFolder = TemporaryFolder()
|
|
33
|
+
|
|
34
|
+
private lateinit var server: MockWebServer
|
|
35
|
+
private lateinit var downloader: ResumableDownloader
|
|
36
|
+
|
|
37
|
+
/** Held closed while a request is being served, so transfers stay in flight. */
|
|
38
|
+
private val holdResponses = CountDownLatch(1)
|
|
39
|
+
private val requested = CopyOnWriteArrayList<String>()
|
|
40
|
+
|
|
41
|
+
private val completed = CopyOnWriteArrayList<String>()
|
|
42
|
+
private val failed = ConcurrentHashMap<String, String>()
|
|
43
|
+
|
|
44
|
+
private val listener = object : ResumableDownloader.DownloadListener {
|
|
45
|
+
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
|
|
46
|
+
override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
47
|
+
override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) {
|
|
48
|
+
completed.add(id)
|
|
49
|
+
}
|
|
50
|
+
override fun onError(id: String, error: String, errorCode: Int) {
|
|
51
|
+
failed[id] = error
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
@Before
|
|
56
|
+
fun startServer() {
|
|
57
|
+
server = MockWebServer()
|
|
58
|
+
server.dispatcher = object : Dispatcher() {
|
|
59
|
+
override fun dispatch(request: RecordedRequest): MockResponse {
|
|
60
|
+
requested.add(request.path ?: "")
|
|
61
|
+
// Keep the transfer open until the test lets it finish, so a
|
|
62
|
+
// running download really does occupy its slot
|
|
63
|
+
holdResponses.await(20, TimeUnit.SECONDS)
|
|
64
|
+
return MockResponse().setBody("payload")
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
server.start()
|
|
68
|
+
downloader = ResumableDownloader()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@After
|
|
72
|
+
fun stopServer() {
|
|
73
|
+
holdResponses.countDown()
|
|
74
|
+
server.shutdown()
|
|
75
|
+
// Other tests must not inherit this test's cap
|
|
76
|
+
ResumableDownloader.setMaxConcurrentTransfers(DownloadConstants.DEFAULT_MAX_PARALLEL_DOWNLOADS)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private fun start(id: String) {
|
|
80
|
+
downloader.startDownload(
|
|
81
|
+
id = id,
|
|
82
|
+
url = server.url("/$id").toString(),
|
|
83
|
+
destination = tempFolder.newFile(id).absolutePath,
|
|
84
|
+
headers = emptyMap(),
|
|
85
|
+
listener = listener,
|
|
86
|
+
isAllowedOverMetered = true
|
|
87
|
+
)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private fun awaitUntil(what: String, timeoutMs: Long = 5000, condition: () -> Boolean) {
|
|
91
|
+
val deadline = System.currentTimeMillis() + timeoutMs
|
|
92
|
+
while (System.currentTimeMillis() < deadline) {
|
|
93
|
+
if (condition()) return
|
|
94
|
+
Thread.sleep(25)
|
|
95
|
+
}
|
|
96
|
+
throw AssertionError("Timed out waiting for: $what")
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private fun assertStaysAt(count: Int, what: String) {
|
|
100
|
+
// Give anything that should not have started the chance to prove it did
|
|
101
|
+
Thread.sleep(500)
|
|
102
|
+
assertEquals(what, count, requested.size)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
@Test
|
|
106
|
+
fun `only maxConcurrentTransfers downloads transfer at once`() {
|
|
107
|
+
ResumableDownloader.setMaxConcurrentTransfers(2)
|
|
108
|
+
|
|
109
|
+
repeat(5) { start("download-$it") }
|
|
110
|
+
|
|
111
|
+
awaitUntil("two transfers to reach the server") { requested.size == 2 }
|
|
112
|
+
assertStaysAt(2, "third download must wait for a slot")
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
@Test
|
|
116
|
+
fun `a waiting download starts when a running one finishes`() {
|
|
117
|
+
ResumableDownloader.setMaxConcurrentTransfers(2)
|
|
118
|
+
|
|
119
|
+
repeat(3) { start("download-$it") }
|
|
120
|
+
awaitUntil("two transfers to reach the server") { requested.size == 2 }
|
|
121
|
+
|
|
122
|
+
// Let the running transfers complete - each one frees its slot
|
|
123
|
+
holdResponses.countDown()
|
|
124
|
+
|
|
125
|
+
awaitUntil("the queued download to start") { requested.size == 3 }
|
|
126
|
+
awaitUntil("every download to complete") { completed.size == 3 }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
@Test
|
|
130
|
+
fun `a download paused while waiting never starts`() {
|
|
131
|
+
ResumableDownloader.setMaxConcurrentTransfers(1)
|
|
132
|
+
|
|
133
|
+
start("running")
|
|
134
|
+
awaitUntil("the first transfer to reach the server") { requested.size == 1 }
|
|
135
|
+
|
|
136
|
+
start("waiting")
|
|
137
|
+
assertStaysAt(1, "the second download must wait for a slot")
|
|
138
|
+
|
|
139
|
+
// The user pauses it before it ever got a slot
|
|
140
|
+
assertTrue(downloader.pause("waiting"))
|
|
141
|
+
|
|
142
|
+
holdResponses.countDown()
|
|
143
|
+
awaitUntil("the running download to complete") { completed.contains("running") }
|
|
144
|
+
|
|
145
|
+
// Its slot freed, but a paused download must not be started by the queue
|
|
146
|
+
assertStaysAt(1, "a download paused while waiting must not start")
|
|
147
|
+
assertTrue(downloader.isPaused("waiting"))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
@Test
|
|
151
|
+
fun `a download cancelled while waiting never starts`() {
|
|
152
|
+
ResumableDownloader.setMaxConcurrentTransfers(1)
|
|
153
|
+
|
|
154
|
+
start("running")
|
|
155
|
+
awaitUntil("the first transfer to reach the server") { requested.size == 1 }
|
|
156
|
+
|
|
157
|
+
start("waiting")
|
|
158
|
+
assertStaysAt(1, "the second download must wait for a slot")
|
|
159
|
+
|
|
160
|
+
assertTrue(downloader.cancel("waiting"))
|
|
161
|
+
|
|
162
|
+
holdResponses.countDown()
|
|
163
|
+
awaitUntil("the running download to complete") { completed.contains("running") }
|
|
164
|
+
|
|
165
|
+
assertStaysAt(1, "a cancelled download must not start")
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
@Test
|
|
169
|
+
fun `resuming a paused download goes back through the queue`() {
|
|
170
|
+
ResumableDownloader.setMaxConcurrentTransfers(1)
|
|
171
|
+
|
|
172
|
+
start("running")
|
|
173
|
+
awaitUntil("the first transfer to reach the server") { requested.size == 1 }
|
|
174
|
+
|
|
175
|
+
start("waiting")
|
|
176
|
+
assertTrue(downloader.pause("waiting"))
|
|
177
|
+
assertTrue(downloader.resume("waiting", listener))
|
|
178
|
+
|
|
179
|
+
// The slot is still taken by the running download, so a resume waits too
|
|
180
|
+
assertStaysAt(1, "a resumed download must not jump the queue")
|
|
181
|
+
|
|
182
|
+
holdResponses.countDown()
|
|
183
|
+
awaitUntil("the resumed download to start") { requested.size == 2 }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
@Test
|
|
187
|
+
fun `the cap does not lose downloads under load`() {
|
|
188
|
+
ResumableDownloader.setMaxConcurrentTransfers(3)
|
|
189
|
+
|
|
190
|
+
repeat(12) { start("download-$it") }
|
|
191
|
+
awaitUntil("the first batch to reach the server") { requested.size == 3 }
|
|
192
|
+
|
|
193
|
+
holdResponses.countDown()
|
|
194
|
+
|
|
195
|
+
awaitUntil("every download to complete", timeoutMs = 20000) { completed.size == 12 }
|
|
196
|
+
assertEquals("no download ran twice", 12, requested.toSet().size)
|
|
197
|
+
assertTrue("no download failed: $failed", failed.isEmpty())
|
|
198
|
+
}
|
|
199
|
+
}
|