@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.
Files changed (49) hide show
  1. package/README.md +30 -3
  2. package/android/build.gradle +17 -0
  3. package/android/src/main/AndroidManifest.xml +24 -0
  4. package/android/src/main/java/com/eko/DownloadConstants.kt +14 -2
  5. package/android/src/main/java/com/eko/Downloader.kt +77 -12
  6. package/android/src/main/java/com/eko/PromiseExtensions.kt +36 -0
  7. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +82 -134
  8. package/android/src/main/java/com/eko/ResumableDownloadService.kt +0 -4
  9. package/android/src/main/java/com/eko/ResumableDownloader.kt +121 -12
  10. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +65 -9
  11. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +64 -0
  12. package/android/src/main/java/com/eko/uidt/RNBGDFileProvider.kt +17 -0
  13. package/android/src/main/java/com/eko/uidt/UIDTJobIds.kt +112 -0
  14. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +178 -17
  15. package/android/src/main/java/com/eko/uidt/UIDTJobState.kt +23 -1
  16. package/android/src/main/java/com/eko/uidt/UIDTNotificationIds.kt +73 -0
  17. package/android/src/main/java/com/eko/uidt/UIDTNotificationManager.kt +246 -19
  18. package/android/src/main/java/com/eko/utils/ReadableConverters.kt +55 -0
  19. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +97 -0
  20. package/android/src/main/java/com/eko/utils/StorageManager.kt +13 -0
  21. package/android/src/main/res/xml/rnbgd_file_paths.xml +23 -0
  22. package/android/src/newarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
  23. package/android/src/oldarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
  24. package/android/src/test/java/com/eko/ResumableDownloaderConcurrencyTest.kt +199 -0
  25. package/android/src/test/java/com/eko/uidt/UIDTJobIdsTest.kt +159 -0
  26. package/android/src/test/java/com/eko/uidt/UIDTJobManagerTest.kt +192 -0
  27. package/android/src/test/java/com/eko/uidt/UIDTNotificationIdsTest.kt +99 -0
  28. package/ios/RNBackgroundDownloader.mm +187 -91
  29. package/lib/DownloadTask.js +8 -7
  30. package/lib/NativeRNBackgroundDownloader.d.ts +2 -0
  31. package/lib/UploadTask.js +11 -10
  32. package/lib/config.d.ts +3 -10
  33. package/lib/config.js +4 -44
  34. package/lib/index.d.ts +1 -1
  35. package/lib/index.js +43 -34
  36. package/lib/logger.d.ts +2 -0
  37. package/lib/logger.js +16 -0
  38. package/lib/notifications.d.ts +8 -0
  39. package/lib/notifications.js +35 -0
  40. package/lib/types.d.ts +19 -0
  41. package/package.json +8 -3
  42. package/src/DownloadTask.ts +2 -1
  43. package/src/NativeRNBackgroundDownloader.ts +8 -1
  44. package/src/UploadTask.ts +2 -1
  45. package/src/config.ts +9 -45
  46. package/src/index.ts +22 -2
  47. package/src/logger.ts +16 -0
  48. package/src/notifications.ts +32 -0
  49. 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
- * Generate a stable notification ID for a configId.
27
- * This ensures the same download always uses the same notification ID,
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
- return UIDTConstants.NOTIFICATION_ID_BASE + (configId.hashCode() and 0x7FFFFFFF) % 100000
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 = if (config.groupingEnabled && groupName.isNotEmpty()) {
127
- groupName
128
- } else {
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 = if (config.groupingEnabled && jobState.groupName.isNotEmpty()) {
177
- jobState.groupName
178
- } else {
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 = if (config.groupingEnabled && jobState.groupName.isNotEmpty()) {
253
- jobState.groupName
254
- } else {
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,55 @@
1
+ package com.eko.utils
2
+
3
+ import com.facebook.react.bridge.ReadableArray
4
+ import com.facebook.react.bridge.ReadableMap
5
+ import com.facebook.react.bridge.ReadableType
6
+ import org.json.JSONArray
7
+ import org.json.JSONObject
8
+
9
+ /**
10
+ * Stateless conversion of React Native's ReadableMap/ReadableArray bridge types into
11
+ * org.json structures. Pure helpers with no module state - extracted from the module
12
+ * so the conversion logic is reusable and unit-testable on its own.
13
+ */
14
+ object ReadableConverters {
15
+
16
+ /**
17
+ * Convert a ReadableMap to JSONObject, handling nested maps and arrays.
18
+ */
19
+ fun toJsonObject(map: ReadableMap?): JSONObject? {
20
+ if (map == null) return null
21
+ val json = JSONObject()
22
+ val iterator = map.keySetIterator()
23
+ while (iterator.hasNextKey()) {
24
+ val key = iterator.nextKey()
25
+ when (map.getType(key)) {
26
+ ReadableType.Null -> json.put(key, JSONObject.NULL)
27
+ ReadableType.Boolean -> json.put(key, map.getBoolean(key))
28
+ ReadableType.Number -> json.put(key, map.getDouble(key))
29
+ ReadableType.String -> json.put(key, map.getString(key))
30
+ ReadableType.Map -> json.put(key, toJsonObject(map.getMap(key)))
31
+ ReadableType.Array -> json.put(key, toJsonArray(map.getArray(key)))
32
+ }
33
+ }
34
+ return json
35
+ }
36
+
37
+ /**
38
+ * Convert a ReadableArray to JSONArray.
39
+ */
40
+ fun toJsonArray(array: ReadableArray?): JSONArray? {
41
+ if (array == null) return null
42
+ val json = JSONArray()
43
+ for (i in 0 until array.size()) {
44
+ when (array.getType(i)) {
45
+ ReadableType.Null -> json.put(JSONObject.NULL)
46
+ ReadableType.Boolean -> json.put(array.getBoolean(i))
47
+ ReadableType.Number -> json.put(array.getDouble(i))
48
+ ReadableType.String -> json.put(array.getString(i))
49
+ ReadableType.Map -> json.put(toJsonObject(array.getMap(i)))
50
+ ReadableType.Array -> json.put(toJsonArray(array.getArray(i)))
51
+ }
52
+ }
53
+ return json
54
+ }
55
+ }
@@ -0,0 +1,97 @@
1
+ package com.eko.utils
2
+
3
+ import com.eko.DownloadConstants
4
+ import com.eko.RNBackgroundDownloaderModuleImpl
5
+ import com.facebook.react.bridge.ReadableMap
6
+ import java.net.HttpURLConnection
7
+ import java.net.URL
8
+
9
+ /**
10
+ * Follows HTTP 3xx redirects with HEAD requests to find the final download URL before
11
+ * handing it to DownloadManager (which does not expose the resolved URL). Stateless and
12
+ * self-contained - extracted from the module so the redirect logic is isolated and
13
+ * testable. Never throws: on any failure it returns the original URL unchanged.
14
+ */
15
+ object RedirectResolver {
16
+
17
+ private const val TAG = "RNBackgroundDownloader"
18
+
19
+ /**
20
+ * Resolve up to [maxRedirects] redirects starting from [originalUrl], applying
21
+ * [headers] to each probe. Returns the final URL, or [originalUrl] if resolution
22
+ * is disabled ([maxRedirects] <= 0) or fails.
23
+ */
24
+ fun resolve(originalUrl: String, maxRedirects: Int, headers: ReadableMap?): String {
25
+ if (maxRedirects <= 0) {
26
+ return originalUrl
27
+ }
28
+
29
+ try {
30
+ var currentUrl = originalUrl
31
+ var redirectCount = 0
32
+
33
+ while (redirectCount < maxRedirects) {
34
+ val url = URL(currentUrl)
35
+ val connection = url.openConnection() as HttpURLConnection
36
+
37
+ // Add headers to the redirect resolution request
38
+ HeaderUtils.applyToConnection(connection, headers)
39
+
40
+ // Add default headers for consistency with DownloadManager
41
+ HeaderUtils.applyDefaultHeaders(connection, headers)
42
+
43
+ connection.instanceFollowRedirects = false
44
+ connection.requestMethod = "HEAD" // Use HEAD to avoid downloading content
45
+ connection.connectTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
46
+ connection.readTimeout = DownloadConstants.REDIRECT_TIMEOUT_MS
47
+
48
+ val responseCode = connection.responseCode
49
+
50
+ if (responseCode in 300..399) {
51
+ // This is a redirect
52
+ val location = connection.getHeaderField("Location")
53
+ if (location == null) {
54
+ RNBackgroundDownloaderModuleImpl.logW(TAG, "Redirect response without Location header at: $currentUrl")
55
+ break
56
+ }
57
+
58
+ // Handle relative URLs
59
+ currentUrl = when {
60
+ location.startsWith("/") -> {
61
+ val baseUrl = URL(currentUrl)
62
+ "${baseUrl.protocol}://${baseUrl.host}$location"
63
+ }
64
+ !location.startsWith("http") -> {
65
+ val baseUrl = URL(currentUrl)
66
+ "${baseUrl.protocol}://${baseUrl.host}/$location"
67
+ }
68
+ else -> location
69
+ }
70
+
71
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Redirect ${redirectCount + 1}/$maxRedirects: $currentUrl -> $location")
72
+ redirectCount++
73
+ } else {
74
+ // Not a redirect, we've found the final URL
75
+ break
76
+ }
77
+
78
+ connection.disconnect()
79
+ }
80
+
81
+ if (redirectCount >= maxRedirects) {
82
+ RNBackgroundDownloaderModuleImpl.logW(
83
+ TAG,
84
+ "Reached maximum redirects ($maxRedirects) for URL: $originalUrl. Final URL: $currentUrl"
85
+ )
86
+ } else {
87
+ RNBackgroundDownloaderModuleImpl.logD(TAG, "Resolved URL after $redirectCount redirects: $currentUrl")
88
+ }
89
+
90
+ return currentUrl
91
+ } catch (e: Exception) {
92
+ RNBackgroundDownloaderModuleImpl.logE(TAG, "Failed to resolve redirects for URL: $originalUrl. Error: ${e.message}")
93
+ // Return original URL if redirect resolution fails
94
+ return originalUrl
95
+ }
96
+ }
97
+ }
@@ -188,6 +188,19 @@ class StorageManager(context: Context, private val name: String) {
188
188
  /**
189
189
  * Serializable data class for storing paused download information.
190
190
  * This is needed because Gson requires explicit serialization for complex types.
191
+ *
192
+ * PERSISTENCE MIGRATION INVARIANT — read before adding a field here.
193
+ * This DTO is written to MMKV/SharedPreferences by one app version and read back
194
+ * by the next, so it must stay forward/backward compatible with in-flight downloads
195
+ * across an app update. Every NEW field MUST:
196
+ * 1. be nullable (or have a default) so a record written by an older version -
197
+ * where the JSON key is simply absent - deserializes instead of failing; and
198
+ * 2. resolve its legacy meaning explicitly in [toInfo] with `?: <safe default>`,
199
+ * never relying on Gson's zero-value default (e.g. `false`/`0`), which is
200
+ * usually the wrong choice for an absent key.
201
+ * See `isAllowedOverMetered` below for the reference pattern, and keep the
202
+ * runtime<->DTO mapping in the single [toData]/[toInfo] pair so a field is added
203
+ * in exactly one place.
191
204
  */
192
205
  data class PausedDownloadInfoData(
193
206
  val configId: String,
@@ -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>
@@ -30,53 +30,24 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
30
30
  impl.download(options)
31
31
  }
32
32
 
33
- override fun pauseTask(id: String, promise: com.facebook.react.bridge.Promise) {
34
- try {
35
- impl.pauseTask(id)
36
- promise.resolve(null)
37
- } catch (e: Exception) {
38
- promise.reject("ERR_PAUSE_TASK", e.message, e)
39
- }
40
- }
33
+ override fun pauseTask(id: String, promise: com.facebook.react.bridge.Promise) =
34
+ promise.resolveCatching("ERR_PAUSE_TASK") { impl.pauseTask(id) }
41
35
 
42
- override fun resumeTask(id: String, promise: com.facebook.react.bridge.Promise) {
43
- try {
44
- impl.resumeTask(id)
45
- promise.resolve(null)
46
- } catch (e: Exception) {
47
- promise.reject("ERR_RESUME_TASK", e.message, e)
48
- }
49
- }
36
+ override fun resumeTask(id: String, promise: com.facebook.react.bridge.Promise) =
37
+ promise.resolveCatching("ERR_RESUME_TASK") { impl.resumeTask(id) }
50
38
 
51
- override fun stopTask(id: String, promise: com.facebook.react.bridge.Promise) {
52
- try {
53
- impl.stopTask(id)
54
- promise.resolve(null)
55
- } catch (e: Exception) {
56
- promise.reject("ERR_STOP_TASK", e.message, e)
57
- }
58
- }
39
+ override fun stopTask(id: String, promise: com.facebook.react.bridge.Promise) =
40
+ promise.resolveCatching("ERR_STOP_TASK") { impl.stopTask(id) }
59
41
 
60
42
  override fun updateTaskHeaders(id: String, headers: com.facebook.react.bridge.ReadableMap, promise: com.facebook.react.bridge.Promise) {
61
43
  impl.updateTaskHeaders(id, headers, promise)
62
44
  }
63
45
 
64
- override fun completeHandler(jobId: String, promise: com.facebook.react.bridge.Promise) {
65
- try {
66
- impl.completeHandler(jobId)
67
- promise.resolve(null)
68
- } catch (e: Exception) {
69
- promise.reject("ERR_COMPLETE_HANDLER", e.message, e)
70
- }
71
- }
46
+ override fun completeHandler(jobId: String, promise: com.facebook.react.bridge.Promise) =
47
+ promise.resolveCatching("ERR_COMPLETE_HANDLER") { impl.completeHandler(jobId) }
72
48
 
73
- override fun getExistingDownloadTasks(promise: com.facebook.react.bridge.Promise) {
74
- try {
75
- impl.getExistingDownloadTasks(promise)
76
- } catch (e: Exception) {
77
- promise.reject("ERR_GET_EXISTING_TASKS", e.message, e)
78
- }
79
- }
49
+ override fun getExistingDownloadTasks(promise: com.facebook.react.bridge.Promise) =
50
+ promise.rejectOnThrow("ERR_GET_EXISTING_TASKS") { impl.getExistingDownloadTasks(promise) }
80
51
 
81
52
  override fun setLogsEnabled(enabled: Boolean) {
82
53
  impl.setLogsEnabled(enabled)
@@ -112,38 +83,15 @@ class RNBackgroundDownloaderModule(reactContext: ReactApplicationContext) :
112
83
  impl.upload(options)
113
84
  }
114
85
 
115
- override fun pauseUploadTask(id: String, promise: com.facebook.react.bridge.Promise) {
116
- try {
117
- impl.pauseUploadTask(id)
118
- promise.resolve(null)
119
- } catch (e: Exception) {
120
- promise.reject("ERR_PAUSE_UPLOAD_TASK", e.message, e)
121
- }
122
- }
86
+ override fun pauseUploadTask(id: String, promise: com.facebook.react.bridge.Promise) =
87
+ promise.resolveCatching("ERR_PAUSE_UPLOAD_TASK") { impl.pauseUploadTask(id) }
123
88
 
124
- override fun resumeUploadTask(id: String, promise: com.facebook.react.bridge.Promise) {
125
- try {
126
- impl.resumeUploadTask(id)
127
- promise.resolve(null)
128
- } catch (e: Exception) {
129
- promise.reject("ERR_RESUME_UPLOAD_TASK", e.message, e)
130
- }
131
- }
89
+ override fun resumeUploadTask(id: String, promise: com.facebook.react.bridge.Promise) =
90
+ promise.resolveCatching("ERR_RESUME_UPLOAD_TASK") { impl.resumeUploadTask(id) }
132
91
 
133
- override fun stopUploadTask(id: String, promise: com.facebook.react.bridge.Promise) {
134
- try {
135
- impl.stopUploadTask(id)
136
- promise.resolve(null)
137
- } catch (e: Exception) {
138
- promise.reject("ERR_STOP_UPLOAD_TASK", e.message, e)
139
- }
140
- }
92
+ override fun stopUploadTask(id: String, promise: com.facebook.react.bridge.Promise) =
93
+ promise.resolveCatching("ERR_STOP_UPLOAD_TASK") { impl.stopUploadTask(id) }
141
94
 
142
- override fun getExistingUploadTasks(promise: com.facebook.react.bridge.Promise) {
143
- try {
144
- impl.getExistingUploadTasks(promise)
145
- } catch (e: Exception) {
146
- promise.reject("ERR_GET_EXISTING_UPLOAD_TASKS", e.message, e)
147
- }
148
- }
95
+ override fun getExistingUploadTasks(promise: com.facebook.react.bridge.Promise) =
96
+ promise.rejectOnThrow("ERR_GET_EXISTING_UPLOAD_TASKS") { impl.getExistingUploadTasks(promise) }
149
97
  }