@kesha-antonov/react-native-background-downloader 4.5.9 → 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/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/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
|
@@ -12,6 +12,7 @@ import com.eko.uidt.UIDTConstants
|
|
|
12
12
|
import com.eko.uidt.UIDTJobInfo
|
|
13
13
|
import com.eko.uidt.UIDTJobManager
|
|
14
14
|
import com.eko.uidt.UIDTJobRegistry
|
|
15
|
+
import com.eko.uidt.UIDTNotificationIds
|
|
15
16
|
import com.eko.uidt.UIDTNotificationManager
|
|
16
17
|
import com.eko.utils.ProgressUtils
|
|
17
18
|
import org.json.JSONObject
|
|
@@ -103,8 +104,21 @@ class UIDTDownloadJobService : JobService() {
|
|
|
103
104
|
/**
|
|
104
105
|
* Configure notification grouping and texts.
|
|
105
106
|
*/
|
|
106
|
-
fun setNotificationGroupingConfig(
|
|
107
|
-
|
|
107
|
+
fun setNotificationGroupingConfig(
|
|
108
|
+
enabled: Boolean,
|
|
109
|
+
showNotificationsEnabled: Boolean,
|
|
110
|
+
showCompletionNotification: Boolean,
|
|
111
|
+
showCancelAction: Boolean,
|
|
112
|
+
mode: String,
|
|
113
|
+
texts: Map<String, String>
|
|
114
|
+
) = UIDTJobManager.setNotificationConfig(
|
|
115
|
+
enabled,
|
|
116
|
+
showNotificationsEnabled,
|
|
117
|
+
showCompletionNotification,
|
|
118
|
+
showCancelAction,
|
|
119
|
+
mode,
|
|
120
|
+
texts
|
|
121
|
+
)
|
|
108
122
|
|
|
109
123
|
/**
|
|
110
124
|
* Set notification update interval.
|
|
@@ -127,6 +141,18 @@ class UIDTDownloadJobService : JobService() {
|
|
|
127
141
|
*/
|
|
128
142
|
fun getAllActiveJobs(): List<UIDTJobInfo> = UIDTJobRegistry.getAllActiveJobs()
|
|
129
143
|
|
|
144
|
+
/**
|
|
145
|
+
* Returns the downloads whose job is scheduled but hasn't started yet.
|
|
146
|
+
* These have no registry entry, so they are invisible to [getAllActiveJobs].
|
|
147
|
+
*/
|
|
148
|
+
fun getScheduledJobs(context: Context): List<UIDTJobInfo> = UIDTJobManager.getScheduledJobs(context)
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Whether a download has a job with the JobScheduler, running or not yet started.
|
|
152
|
+
*/
|
|
153
|
+
fun isScheduledJob(context: Context, configId: String): Boolean =
|
|
154
|
+
UIDTJobManager.isScheduledJob(context, configId)
|
|
155
|
+
|
|
130
156
|
/**
|
|
131
157
|
* Set download listener.
|
|
132
158
|
*/
|
|
@@ -169,12 +195,14 @@ class UIDTDownloadJobService : JobService() {
|
|
|
169
195
|
val metadataJson = extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
|
|
170
196
|
var groupId = ""
|
|
171
197
|
var groupName = ""
|
|
198
|
+
var customTitle = ""
|
|
172
199
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob: configId=$configId, metadataJson=$metadataJson")
|
|
173
200
|
try {
|
|
174
201
|
val json = JSONObject(metadataJson)
|
|
175
202
|
groupId = json.optString("groupId", "")
|
|
176
203
|
groupName = json.optString("groupName", "")
|
|
177
|
-
|
|
204
|
+
customTitle = json.optString("notificationTitle", "")
|
|
205
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Parsed metadata: groupId='$groupId', groupName='$groupName', customTitle='$customTitle'")
|
|
178
206
|
} catch (e: Exception) {
|
|
179
207
|
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "Failed to parse metadata: ${e.message}")
|
|
180
208
|
}
|
|
@@ -212,7 +240,7 @@ class UIDTDownloadJobService : JobService() {
|
|
|
212
240
|
|
|
213
241
|
// Create notification for UIDT job (required)
|
|
214
242
|
val notificationId = UIDTNotificationManager.getNotificationIdForConfig(configId)
|
|
215
|
-
val notification = UIDTNotificationManager.createDownloadNotification(this, configId, groupId, groupName)
|
|
243
|
+
val notification = UIDTNotificationManager.createDownloadNotification(this, configId, groupId, groupName, customTitle)
|
|
216
244
|
|
|
217
245
|
// Set the notification for this job (required for UIDT)
|
|
218
246
|
setNotification(params, notificationId, notification, JOB_END_NOTIFICATION_POLICY_DETACH)
|
|
@@ -229,13 +257,13 @@ class UIDTDownloadJobService : JobService() {
|
|
|
229
257
|
}
|
|
230
258
|
|
|
231
259
|
// Store job state BEFORE updating summary (so count includes this job)
|
|
232
|
-
UIDTJobRegistry.activeJobs[configId] = JobState(params, resumableDownloader, notificationId, groupId, groupName)
|
|
260
|
+
UIDTJobRegistry.activeJobs[configId] = JobState(params, resumableDownloader, notificationId, groupId, groupName, customTitle)
|
|
233
261
|
|
|
234
262
|
// Update summary notification if grouping enabled (now includes new job in count)
|
|
235
263
|
UIDTNotificationManager.updateSummaryNotificationForGroup(this, groupId, groupName)
|
|
236
264
|
|
|
237
265
|
// Create listener that will notify completion
|
|
238
|
-
val jobListener = createJobListener(configId, params, groupId, groupName)
|
|
266
|
+
val jobListener = createJobListener(configId, params, groupId, groupName, customTitle)
|
|
239
267
|
|
|
240
268
|
// Start the download asynchronously. The network constraint is enforced by
|
|
241
269
|
// the JobScheduler; the flag is passed so the DownloadState stays truthful
|
|
@@ -303,7 +331,8 @@ class UIDTDownloadJobService : JobService() {
|
|
|
303
331
|
configId: String,
|
|
304
332
|
params: JobParameters,
|
|
305
333
|
groupId: String,
|
|
306
|
-
groupName: String
|
|
334
|
+
groupName: String,
|
|
335
|
+
customTitle: String = ""
|
|
307
336
|
): ResumableDownloader.DownloadListener {
|
|
308
337
|
return object : ResumableDownloader.DownloadListener {
|
|
309
338
|
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) {
|
|
@@ -314,7 +343,7 @@ class UIDTDownloadJobService : JobService() {
|
|
|
314
343
|
if (jobState != null) {
|
|
315
344
|
// Store total bytes for summary progress calculation
|
|
316
345
|
jobState.bytesTotal = expectedBytes
|
|
317
|
-
UIDTNotificationManager.updateProgressNotification(this@UIDTDownloadJobService, jobState, 0, expectedBytes)
|
|
346
|
+
UIDTNotificationManager.updateProgressNotification(this@UIDTDownloadJobService, id, jobState, 0, expectedBytes)
|
|
318
347
|
}
|
|
319
348
|
|
|
320
349
|
// Notify external listener
|
|
@@ -365,7 +394,7 @@ class UIDTDownloadJobService : JobService() {
|
|
|
365
394
|
} else {
|
|
366
395
|
// Update individual notification
|
|
367
396
|
UIDTNotificationManager.updateProgressNotification(
|
|
368
|
-
this@UIDTDownloadJobService, jobState, bytesDownloaded, bytesTotal
|
|
397
|
+
this@UIDTDownloadJobService, id, jobState, bytesDownloaded, bytesTotal
|
|
369
398
|
)
|
|
370
399
|
}
|
|
371
400
|
}
|
|
@@ -384,6 +413,29 @@ class UIDTDownloadJobService : JobService() {
|
|
|
384
413
|
|
|
385
414
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onComplete: notificationId=$notificationId, jobState groupId=${jobState?.groupId}")
|
|
386
415
|
|
|
416
|
+
// Resolve a display name for the completion notification.
|
|
417
|
+
// Prefer metadata.fileName (set from JS), fall back to the
|
|
418
|
+
// saved file's basename.
|
|
419
|
+
val displayName = try {
|
|
420
|
+
val metadataStr = params.extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
|
|
421
|
+
val metadata = JSONObject(metadataStr)
|
|
422
|
+
metadata.optString("fileName", "").ifEmpty { location.substringAfterLast('/') }
|
|
423
|
+
} catch (e: Exception) {
|
|
424
|
+
location.substringAfterLast('/')
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Post a standalone "download complete" notification BEFORE
|
|
428
|
+
// we tear down the UIDT-controlled one so it persists. Tap
|
|
429
|
+
// opens the saved file via FileProvider (system file viewer).
|
|
430
|
+
UIDTNotificationManager.showFinishedNotification(
|
|
431
|
+
this@UIDTDownloadJobService,
|
|
432
|
+
id,
|
|
433
|
+
location,
|
|
434
|
+
displayName,
|
|
435
|
+
jobState?.groupId ?: groupId,
|
|
436
|
+
jobState?.customTitle ?: customTitle,
|
|
437
|
+
)
|
|
438
|
+
|
|
387
439
|
// Clean up - remove from activeJobs first
|
|
388
440
|
UIDTJobRegistry.activeJobs.remove(id)
|
|
389
441
|
releaseWakeLock()
|
|
@@ -419,6 +471,9 @@ class UIDTDownloadJobService : JobService() {
|
|
|
419
471
|
|
|
420
472
|
// Clear persisted resume state - no longer needed after successful completion
|
|
421
473
|
UIDTJobRegistry.clearResumeState(this@UIDTDownloadJobService, id)
|
|
474
|
+
// The progress notification is gone; the completion one above already
|
|
475
|
+
// took its ID from this offset, so it can go back to the pool
|
|
476
|
+
UIDTNotificationIds.release(id)
|
|
422
477
|
|
|
423
478
|
// Notify external listener
|
|
424
479
|
UIDTJobRegistry.downloadListener?.onComplete(id, location, bytesDownloaded, bytesTotal)
|
|
@@ -460,6 +515,7 @@ class UIDTDownloadJobService : JobService() {
|
|
|
460
515
|
|
|
461
516
|
// Clear persisted resume state - no longer needed after failure
|
|
462
517
|
UIDTJobRegistry.clearResumeState(this@UIDTDownloadJobService, id)
|
|
518
|
+
UIDTNotificationIds.release(id)
|
|
463
519
|
|
|
464
520
|
// Notify external listener
|
|
465
521
|
UIDTJobRegistry.downloadListener?.onError(id, error, errorCode)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
package com.eko.uidt
|
|
2
|
+
|
|
3
|
+
import android.content.BroadcastReceiver
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.Intent
|
|
6
|
+
import android.os.Build
|
|
7
|
+
import androidx.annotation.RequiresApi
|
|
8
|
+
import com.eko.RNBackgroundDownloaderModuleImpl
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Receives the cancel action fired from the download progress notification.
|
|
12
|
+
* The action carries the download's [EXTRA_CONFIG_ID] as a string extra; on
|
|
13
|
+
* receive we stop the download and dispatch a downloadFailed event so JS can
|
|
14
|
+
* clean up.
|
|
15
|
+
*
|
|
16
|
+
* Cancelling from the shade must leave exactly the same state behind as
|
|
17
|
+
* `task.stop()` from JS, so the work is delegated to the module's stopTask
|
|
18
|
+
* (progress tracking, resumable + DownloadManager cancellation, persisted
|
|
19
|
+
* maps and paused records). Only when the module is not up - a cold start
|
|
20
|
+
* triggered by this very broadcast - do we fall back to cancelling the UIDT
|
|
21
|
+
* job on its own.
|
|
22
|
+
*/
|
|
23
|
+
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
|
|
24
|
+
class CancelDownloadReceiver : BroadcastReceiver() {
|
|
25
|
+
|
|
26
|
+
override fun onReceive(context: Context, intent: Intent) {
|
|
27
|
+
if (intent.action != ACTION_CANCEL_DOWNLOAD) return
|
|
28
|
+
val configId = intent.getStringExtra(EXTRA_CONFIG_ID) ?: return
|
|
29
|
+
|
|
30
|
+
RNBackgroundDownloaderModuleImpl.logD(
|
|
31
|
+
UIDTConstants.TAG,
|
|
32
|
+
"CancelDownloadReceiver: cancelling $configId",
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
// Snapshot liveness first: stopTask tears the job down, so afterwards we
|
|
36
|
+
// can no longer tell an active download from an already-finished one.
|
|
37
|
+
val wasActive = UIDTJobRegistry.isActiveJob(configId)
|
|
38
|
+
|
|
39
|
+
if (!RNBackgroundDownloaderModuleImpl.stopTaskFromNative(configId)) {
|
|
40
|
+
RNBackgroundDownloaderModuleImpl.logD(
|
|
41
|
+
UIDTConstants.TAG,
|
|
42
|
+
"CancelDownloadReceiver: module not initialized, cancelling job directly",
|
|
43
|
+
)
|
|
44
|
+
UIDTJobManager.cancelJob(context, configId)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Only notify JS when a live job was actually cancelled. If the download
|
|
48
|
+
// already finished there is nothing to clean up, and dispatching here
|
|
49
|
+
// would emit a spurious downloadFailed for an already-completed task.
|
|
50
|
+
if (wasActive) {
|
|
51
|
+
// Notify JS so the in-memory task map can be cleaned and the
|
|
52
|
+
// .error() handler runs (lib uses CANCELLED errorCode = -1).
|
|
53
|
+
UIDTJobRegistry.downloadListener?.onError(configId, CANCELLED_MESSAGE, CANCELLED_ERROR_CODE)
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
companion object {
|
|
58
|
+
const val ACTION_CANCEL_DOWNLOAD = "com.eko.uidt.ACTION_CANCEL_DOWNLOAD"
|
|
59
|
+
const val EXTRA_CONFIG_ID = "config_id"
|
|
60
|
+
|
|
61
|
+
private const val CANCELLED_MESSAGE = "Download cancelled by user"
|
|
62
|
+
private const val CANCELLED_ERROR_CODE = -1
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
package com.eko.uidt
|
|
2
|
+
|
|
3
|
+
import androidx.core.content.FileProvider
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Library-owned [FileProvider] subclass.
|
|
7
|
+
*
|
|
8
|
+
* Using a dedicated subclass (rather than registering
|
|
9
|
+
* `androidx.core.content.FileProvider` directly) gives the provider a unique
|
|
10
|
+
* component class name. This avoids a manifest-merger collision with a host
|
|
11
|
+
* app that also declares an `androidx.core.content.FileProvider`, while a
|
|
12
|
+
* unique authority (`${applicationId}.rnbackgrounddownloader.fileprovider`)
|
|
13
|
+
* keeps the authority from clashing too.
|
|
14
|
+
*
|
|
15
|
+
* Paths it can serve are declared in `res/xml/rnbgd_file_paths.xml`.
|
|
16
|
+
*/
|
|
17
|
+
class RNBGDFileProvider : FileProvider()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
package com.eko.uidt
|
|
2
|
+
|
|
3
|
+
import android.app.job.JobInfo
|
|
4
|
+
import android.os.Build
|
|
5
|
+
import androidx.annotation.RequiresApi
|
|
6
|
+
import com.eko.UIDTDownloadJobService
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Assigns the JobScheduler job IDs used for UIDT downloads.
|
|
10
|
+
*
|
|
11
|
+
* Job IDs used to be derived as `JOB_ID_BASE + hash(configId) % JOB_ID_RANGE`.
|
|
12
|
+
* Two config IDs landing on the same ID is not a rare edge case - with the 150
|
|
13
|
+
* concurrent downloads the app-wide job quota allows, the birthday bound puts a
|
|
14
|
+
* collision at roughly two chances in three - and `JobScheduler.schedule()` on
|
|
15
|
+
* an ID that already exists *replaces* that job, silently killing the download
|
|
16
|
+
* it belonged to.
|
|
17
|
+
*
|
|
18
|
+
* There is no mapping to maintain, though: a scheduled job already carries its
|
|
19
|
+
* download's config ID in its extras, so the JobScheduler itself is the registry.
|
|
20
|
+
* That also makes every lookup correct across process death by construction. The
|
|
21
|
+
* only state kept here is an in-memory reservation covering the window between
|
|
22
|
+
* picking a free ID and `schedule()` accepting it.
|
|
23
|
+
*/
|
|
24
|
+
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
|
|
25
|
+
internal object UIDTJobIds {
|
|
26
|
+
|
|
27
|
+
/** Size of the job-ID range owned by the library: `[JOB_ID_BASE, JOB_ID_BASE + JOB_ID_RANGE)`. */
|
|
28
|
+
private const val JOB_ID_RANGE = 10000
|
|
29
|
+
|
|
30
|
+
private val lock = Any()
|
|
31
|
+
|
|
32
|
+
/** configId -> ID picked but not yet handed to the JobScheduler. */
|
|
33
|
+
private val reservations = mutableMapOf<String, Int>()
|
|
34
|
+
|
|
35
|
+
private val serviceName = UIDTDownloadJobService::class.java.name
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The ID a download would have had before IDs were assigned. Still the
|
|
39
|
+
* starting point of the allocation scan, so IDs stay spread over the range
|
|
40
|
+
* instead of clustering at its start, and the fallback for a cancel when the
|
|
41
|
+
* pending jobs can't be read.
|
|
42
|
+
*/
|
|
43
|
+
fun legacyJobIdFor(configId: String): Int =
|
|
44
|
+
UIDTConstants.JOB_ID_BASE + (configId.hashCode() and 0x7FFFFFFF) % JOB_ID_RANGE
|
|
45
|
+
|
|
46
|
+
/** The download a scheduled job belongs to, or null if it isn't one of ours. */
|
|
47
|
+
fun configIdOf(job: JobInfo): String? {
|
|
48
|
+
if (job.service.className != serviceName) return null
|
|
49
|
+
return job.extras.getString(UIDTConstants.KEY_DOWNLOAD_ID)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Every download job the app currently has scheduled, running ones included. */
|
|
53
|
+
fun ourJobs(pendingJobs: List<JobInfo>?): List<JobInfo> =
|
|
54
|
+
pendingJobs.orEmpty().filter { configIdOf(it) != null }
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The job ID a download currently holds, or null when it has none - i.e.
|
|
58
|
+
* there is no job to cancel, pause or look up.
|
|
59
|
+
*
|
|
60
|
+
* @param pendingJobs snapshot of the app's pending jobs, or null when it
|
|
61
|
+
* could not be read.
|
|
62
|
+
*/
|
|
63
|
+
fun jobIdFor(configId: String, pendingJobs: List<JobInfo>?): Int? {
|
|
64
|
+
pendingJobs?.firstOrNull { configIdOf(it) == configId }?.let { return it.id }
|
|
65
|
+
return synchronized(lock) { reservations[configId] }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The ID to cancel for a download. With the pending jobs unreadable we fall
|
|
70
|
+
* back to the legacy ID: cancelling an ID that holds no job is a no-op, and
|
|
71
|
+
* for a download that never collided it is the right one.
|
|
72
|
+
*/
|
|
73
|
+
fun jobIdToCancel(configId: String, pendingJobs: List<JobInfo>?): Int =
|
|
74
|
+
jobIdFor(configId, pendingJobs) ?: legacyJobIdFor(configId)
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Reserve the ID to schedule a download under, or null when every ID in the
|
|
78
|
+
* range is taken - which leaves the caller to fall back to the foreground
|
|
79
|
+
* service rather than evict somebody else's job.
|
|
80
|
+
*
|
|
81
|
+
* A download that already holds a job keeps that ID, so re-scheduling
|
|
82
|
+
* replaces its job instead of adding a second one for the same download.
|
|
83
|
+
* Otherwise the first ID not held by a live job (ours or the host app's) or
|
|
84
|
+
* by another reservation is taken. Release it with [endReservation] once
|
|
85
|
+
* `schedule()` has returned, whatever the outcome.
|
|
86
|
+
*/
|
|
87
|
+
fun reserveJobId(configId: String, pendingJobs: List<JobInfo>?): Int? {
|
|
88
|
+
synchronized(lock) {
|
|
89
|
+
jobIdFor(configId, pendingJobs)?.let {
|
|
90
|
+
reservations[configId] = it
|
|
91
|
+
return it
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
val used = pendingJobs.orEmpty().mapTo(mutableSetOf()) { it.id }
|
|
95
|
+
used.addAll(reservations.values)
|
|
96
|
+
|
|
97
|
+
val start = legacyJobIdFor(configId) - UIDTConstants.JOB_ID_BASE
|
|
98
|
+
for (offset in 0 until JOB_ID_RANGE) {
|
|
99
|
+
val candidate = UIDTConstants.JOB_ID_BASE + (start + offset) % JOB_ID_RANGE
|
|
100
|
+
if (candidate in used) continue
|
|
101
|
+
reservations[configId] = candidate
|
|
102
|
+
return candidate
|
|
103
|
+
}
|
|
104
|
+
return null
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Drop a reservation: once `schedule()` has returned, the system knows about the job. */
|
|
109
|
+
fun endReservation(configId: String) {
|
|
110
|
+
synchronized(lock) { reservations.remove(configId) }
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
package com.eko.uidt
|
|
2
2
|
|
|
3
|
+
import android.app.DownloadManager
|
|
3
4
|
import android.app.NotificationManager
|
|
4
5
|
import android.app.job.JobInfo
|
|
5
6
|
import android.app.job.JobScheduler
|
|
@@ -24,6 +25,20 @@ object UIDTJobManager {
|
|
|
24
25
|
private val config: NotificationConfig
|
|
25
26
|
get() = UIDTJobRegistry.notificationConfig
|
|
26
27
|
|
|
28
|
+
/**
|
|
29
|
+
* JobScheduler refuses to hold more than this many distinct jobs per app
|
|
30
|
+
* (AOSP `JobSchedulerService.MAX_JOBS_PER_APP`) and throws
|
|
31
|
+
* `IllegalStateException` from `schedule()` once the quota is full.
|
|
32
|
+
*/
|
|
33
|
+
private const val JOB_SCHEDULER_APP_LIMIT = 150
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Slots left to the rest of the app. The quota is app-wide - WorkManager and
|
|
37
|
+
* any other library scheduling jobs draw from the same pool - so a download
|
|
38
|
+
* batch must not be allowed to consume all of it.
|
|
39
|
+
*/
|
|
40
|
+
private const val JOB_SCHEDULER_HEADROOM = 30
|
|
41
|
+
|
|
27
42
|
/**
|
|
28
43
|
* Check if UIDT is available on this device.
|
|
29
44
|
*/
|
|
@@ -31,9 +46,83 @@ object UIDTJobManager {
|
|
|
31
46
|
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
|
|
32
47
|
}
|
|
33
48
|
|
|
34
|
-
/**
|
|
35
|
-
|
|
36
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Snapshot of every job the app currently has scheduled, or null when it
|
|
51
|
+
* can't be read - callers treat null as "unknown", not as "none".
|
|
52
|
+
*/
|
|
53
|
+
private fun pendingJobs(jobScheduler: JobScheduler): List<JobInfo>? {
|
|
54
|
+
return try {
|
|
55
|
+
jobScheduler.allPendingJobs
|
|
56
|
+
} catch (e: Exception) {
|
|
57
|
+
RNBackgroundDownloaderModuleImpl.logW(UIDTConstants.TAG, "Could not read pending JobScheduler jobs: ${e.message}")
|
|
58
|
+
null
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Whether a new UIDT job can be handed to the JobScheduler without eating
|
|
64
|
+
* into the app's remaining job quota. With the pending jobs unknown we return
|
|
65
|
+
* true and let the guarded `schedule()` call decide.
|
|
66
|
+
*
|
|
67
|
+
* A download that already holds a job doesn't go through here: re-scheduling
|
|
68
|
+
* replaces that job rather than adding one, so it needs no free slot.
|
|
69
|
+
*/
|
|
70
|
+
private fun hasFreeJobSlot(pendingJobs: List<JobInfo>?): Boolean {
|
|
71
|
+
if (pendingJobs == null) return true
|
|
72
|
+
if (pendingJobs.size < JOB_SCHEDULER_APP_LIMIT - JOB_SCHEDULER_HEADROOM) return true
|
|
73
|
+
|
|
74
|
+
RNBackgroundDownloaderModuleImpl.logW(
|
|
75
|
+
UIDTConstants.TAG,
|
|
76
|
+
"JobScheduler quota nearly exhausted (${pendingJobs.size} pending jobs, app limit $JOB_SCHEDULER_APP_LIMIT)"
|
|
77
|
+
)
|
|
78
|
+
return false
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Whether a download has a job with the JobScheduler that hasn't started yet -
|
|
83
|
+
* e.g. one held by its unmetered-network constraint. Such a job has no entry
|
|
84
|
+
* in [UIDTJobRegistry.activeJobs] (that is only filled in `onStartJob`), and
|
|
85
|
+
* after a process restart the registry is empty for running jobs too, so the
|
|
86
|
+
* system is the only place that knows.
|
|
87
|
+
*/
|
|
88
|
+
fun isScheduledJob(context: Context, configId: String): Boolean {
|
|
89
|
+
if (!isUIDTAvailable()) return false
|
|
90
|
+
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
|
|
91
|
+
return pendingJobs(jobScheduler)?.any { UIDTJobIds.configIdOf(it) == configId } ?: false
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Downloads that have a scheduled job but haven't started transferring, so
|
|
96
|
+
* they can be surfaced alongside the running ones. Jobs already tracked in
|
|
97
|
+
* [UIDTJobRegistry.activeJobs] are left out - those carry live progress and
|
|
98
|
+
* are reported from there instead.
|
|
99
|
+
*/
|
|
100
|
+
fun getScheduledJobs(context: Context): List<UIDTJobInfo> {
|
|
101
|
+
if (!isUIDTAvailable()) return emptyList()
|
|
102
|
+
|
|
103
|
+
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
|
|
104
|
+
return pendingJobs(jobScheduler).orEmpty().mapNotNull { job ->
|
|
105
|
+
val configId = UIDTJobIds.configIdOf(job) ?: return@mapNotNull null
|
|
106
|
+
if (UIDTJobRegistry.isActiveJob(configId)) return@mapNotNull null
|
|
107
|
+
|
|
108
|
+
val extras = job.extras
|
|
109
|
+
// The persisted resume state can be ahead of the extras: it is
|
|
110
|
+
// rewritten whenever the job is stopped and rescheduled
|
|
111
|
+
val persistedBytes = UIDTJobRegistry.loadResumeState(context, configId)?.second ?: 0L
|
|
112
|
+
|
|
113
|
+
UIDTJobInfo(
|
|
114
|
+
id = configId,
|
|
115
|
+
// Same status DownloadManager reports for a queued download, so a
|
|
116
|
+
// download waiting to start looks the same whichever mechanism runs it
|
|
117
|
+
status = DownloadManager.STATUS_PENDING,
|
|
118
|
+
bytesDownloaded = maxOf(persistedBytes, extras.getLong(UIDTConstants.KEY_START_BYTE, 0)),
|
|
119
|
+
bytesTotal = extras.getLong(UIDTConstants.KEY_TOTAL_BYTES, -1),
|
|
120
|
+
url = extras.getString(UIDTConstants.KEY_URL) ?: "",
|
|
121
|
+
destination = extras.getString(UIDTConstants.KEY_DESTINATION) ?: "",
|
|
122
|
+
metadata = extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
37
126
|
|
|
38
127
|
/**
|
|
39
128
|
* Everything needed to persist a scheduled-but-not-yet-running job as a
|
|
@@ -61,11 +150,12 @@ object UIDTJobManager {
|
|
|
61
150
|
if (UIDTJobRegistry.isActiveJob(configId)) return null
|
|
62
151
|
|
|
63
152
|
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
|
|
64
|
-
val jobId = jobIdFor(configId)
|
|
153
|
+
val jobId = UIDTJobIds.jobIdFor(configId, pendingJobs(jobScheduler)) ?: return null
|
|
65
154
|
val pendingJob = jobScheduler.getPendingJob(jobId) ?: return null
|
|
66
155
|
|
|
67
156
|
val extras = pendingJob.extras
|
|
68
|
-
//
|
|
157
|
+
// Defensive: the ID came from this job's own extras, but never act on a
|
|
158
|
+
// job that turns out to belong to another download
|
|
69
159
|
if (extras.getString(UIDTConstants.KEY_DOWNLOAD_ID) != configId) return null
|
|
70
160
|
val url = extras.getString(UIDTConstants.KEY_URL) ?: return null
|
|
71
161
|
val destination = extras.getString(UIDTConstants.KEY_DESTINATION) ?: return null
|
|
@@ -107,7 +197,9 @@ object UIDTJobManager {
|
|
|
107
197
|
* @param isAllowedOverMetered Whether the transfer may use metered networks (cellular).
|
|
108
198
|
* When false the job requires an unmetered network, matching
|
|
109
199
|
* DownloadManager.Request.setAllowedOverMetered(false) semantics.
|
|
110
|
-
* @return true if job was scheduled successfully
|
|
200
|
+
* @return true if job was scheduled successfully. Returns false - never throws -
|
|
201
|
+
* when the app's JobScheduler quota leaves no room for the job, so the
|
|
202
|
+
* caller falls back to the foreground service.
|
|
111
203
|
*/
|
|
112
204
|
fun scheduleDownload(
|
|
113
205
|
context: Context,
|
|
@@ -126,11 +218,52 @@ object UIDTJobManager {
|
|
|
126
218
|
}
|
|
127
219
|
|
|
128
220
|
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
|
|
221
|
+
val pendingJobs = pendingJobs(jobScheduler)
|
|
129
222
|
|
|
130
|
-
//
|
|
131
|
-
|
|
223
|
+
// A download that already has a job replaces it and needs no extra slot;
|
|
224
|
+
// any other one has to fit in the quota. Bail out before touching any
|
|
225
|
+
// state - the caller falls back to the foreground service.
|
|
226
|
+
if (UIDTJobIds.jobIdFor(configId, pendingJobs) == null && !hasFreeJobSlot(pendingJobs)) {
|
|
227
|
+
RNBackgroundDownloaderModuleImpl.logW(UIDTConstants.TAG, "No JobScheduler slot left for $configId, falling back to foreground service")
|
|
228
|
+
return false
|
|
229
|
+
}
|
|
132
230
|
|
|
133
|
-
//
|
|
231
|
+
// Reserve an ID no live job and no concurrent schedule is using
|
|
232
|
+
val jobId = UIDTJobIds.reserveJobId(configId, pendingJobs)
|
|
233
|
+
if (jobId == null) {
|
|
234
|
+
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "No free JobScheduler job ID left for $configId, falling back to foreground service")
|
|
235
|
+
return false
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
try {
|
|
239
|
+
return scheduleJob(context, jobScheduler, jobId, configId, url, destination, headers, startByte, totalBytes, metadata, isAllowedOverMetered)
|
|
240
|
+
} finally {
|
|
241
|
+
// The job is in the system now (or was rejected), so the reservation
|
|
242
|
+
// has done its job either way
|
|
243
|
+
UIDTJobIds.endReservation(configId)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Build and hand over the job for an already reserved ID. Split out of
|
|
249
|
+
* [scheduleDownload] only so the reservation can be released in one place.
|
|
250
|
+
*/
|
|
251
|
+
private fun scheduleJob(
|
|
252
|
+
context: Context,
|
|
253
|
+
jobScheduler: JobScheduler,
|
|
254
|
+
jobId: Int,
|
|
255
|
+
configId: String,
|
|
256
|
+
url: String,
|
|
257
|
+
destination: String,
|
|
258
|
+
headers: Map<String, String>,
|
|
259
|
+
startByte: Long,
|
|
260
|
+
totalBytes: Long,
|
|
261
|
+
metadata: String,
|
|
262
|
+
isAllowedOverMetered: Boolean
|
|
263
|
+
): Boolean {
|
|
264
|
+
// Store headers for later retrieval (PersistableBundle can't store Map<String, String>).
|
|
265
|
+
// Written before scheduling, not after: onStartJob can run on the main thread
|
|
266
|
+
// as soon as schedule() registers the job, and it must find the headers.
|
|
134
267
|
UIDTJobRegistry.pendingHeaders[configId] = headers
|
|
135
268
|
// Also persist to disk so headers survive process death and are available
|
|
136
269
|
// in onStartJob even when the process is restarted by the JobScheduler.
|
|
@@ -164,14 +297,28 @@ object UIDTJobManager {
|
|
|
164
297
|
)
|
|
165
298
|
.build()
|
|
166
299
|
|
|
167
|
-
|
|
300
|
+
// Every rejection here is recoverable for us - the caller falls back to the
|
|
301
|
+
// foreground service - but schedule() signals some of them by throwing:
|
|
302
|
+
// IllegalStateException once the app is over its job quota (the check above
|
|
303
|
+
// races with jobs scheduled elsewhere in the app), and SecurityException when
|
|
304
|
+
// the app can't run user-initiated jobs at all, e.g. a host app that strips
|
|
305
|
+
// RUN_USER_INITIATED_JOBS from the merged manifest.
|
|
306
|
+
val result = try {
|
|
307
|
+
jobScheduler.schedule(jobInfo)
|
|
308
|
+
} catch (e: RuntimeException) {
|
|
309
|
+
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "JobScheduler rejected the UIDT job for $configId: ${e.message}")
|
|
310
|
+
JobScheduler.RESULT_FAILURE
|
|
311
|
+
}
|
|
168
312
|
val success = result == JobScheduler.RESULT_SUCCESS
|
|
169
313
|
|
|
170
314
|
if (success) {
|
|
171
315
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Scheduled UIDT job for $configId (jobId=$jobId, isAllowedOverMetered=$isAllowedOverMetered)")
|
|
172
316
|
} else {
|
|
173
317
|
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "Failed to schedule UIDT job for $configId")
|
|
318
|
+
// Nothing will consume the state written above - the download runs
|
|
319
|
+
// through the foreground service instead - so don't leave it on disk
|
|
174
320
|
UIDTJobRegistry.pendingHeaders.remove(configId)
|
|
321
|
+
UIDTJobRegistry.clearResumeState(context, configId)
|
|
175
322
|
}
|
|
176
323
|
|
|
177
324
|
return success
|
|
@@ -179,9 +326,13 @@ object UIDTJobManager {
|
|
|
179
326
|
|
|
180
327
|
/**
|
|
181
328
|
* Cancel a scheduled UIDT job.
|
|
329
|
+
*
|
|
330
|
+
* @return `true` if a live (active) job was found and cancelled, `false`
|
|
331
|
+
* if there was nothing to cancel (e.g. the download already completed).
|
|
332
|
+
* Callers can use this to avoid dispatching a spurious downloadFailed event.
|
|
182
333
|
*/
|
|
183
|
-
fun cancelJob(context: Context, configId: String) {
|
|
184
|
-
if (!isUIDTAvailable()) return
|
|
334
|
+
fun cancelJob(context: Context, configId: String): Boolean {
|
|
335
|
+
if (!isUIDTAvailable()) return false
|
|
185
336
|
|
|
186
337
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "cancelJob called for $configId")
|
|
187
338
|
|
|
@@ -211,13 +362,13 @@ object UIDTJobManager {
|
|
|
211
362
|
|
|
212
363
|
// Also cancel via NotificationManager as a fallback
|
|
213
364
|
UIDTNotificationManager.cancelNotification(context, jobState.notificationId)
|
|
365
|
+
// Its notification is gone, so the ID offset can go back to the pool
|
|
366
|
+
UIDTNotificationIds.release(configId)
|
|
214
367
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Cancelled notification ${jobState.notificationId} for $configId")
|
|
215
368
|
}
|
|
216
369
|
|
|
217
370
|
val jobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
jobScheduler.cancel(jobId)
|
|
371
|
+
jobScheduler.cancel(UIDTJobIds.jobIdToCancel(configId, pendingJobs(jobScheduler)))
|
|
221
372
|
UIDTJobRegistry.pendingHeaders.remove(configId)
|
|
222
373
|
UIDTJobRegistry.activeJobs.remove(configId)
|
|
223
374
|
// Clear persisted resume state so stale headers/bytes don't affect future downloads
|
|
@@ -229,6 +380,7 @@ object UIDTJobManager {
|
|
|
229
380
|
}
|
|
230
381
|
|
|
231
382
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Cancelled UIDT job for $configId")
|
|
383
|
+
return jobState != null
|
|
232
384
|
}
|
|
233
385
|
|
|
234
386
|
/**
|
|
@@ -294,15 +446,24 @@ object UIDTJobManager {
|
|
|
294
446
|
/**
|
|
295
447
|
* Configure notification settings.
|
|
296
448
|
*/
|
|
297
|
-
fun setNotificationConfig(
|
|
449
|
+
fun setNotificationConfig(
|
|
450
|
+
enabled: Boolean,
|
|
451
|
+
showNotifications: Boolean,
|
|
452
|
+
showCompletionNotification: Boolean,
|
|
453
|
+
showCancelAction: Boolean,
|
|
454
|
+
mode: String,
|
|
455
|
+
texts: Map<String, String>
|
|
456
|
+
) {
|
|
298
457
|
config.groupingEnabled = enabled
|
|
299
458
|
config.showNotificationsEnabled = showNotifications
|
|
459
|
+
config.showCompletionNotification = showCompletionNotification
|
|
460
|
+
config.showCancelAction = showCancelAction
|
|
300
461
|
config.mode = when (mode) {
|
|
301
462
|
"summaryOnly" -> NotificationGroupingMode.SUMMARY_ONLY
|
|
302
463
|
else -> NotificationGroupingMode.INDIVIDUAL
|
|
303
464
|
}
|
|
304
465
|
config.updateTexts(texts)
|
|
305
|
-
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Notification config updated: grouping=$enabled, showNotificationsEnabled=$showNotifications, mode=${config.mode}, texts=$texts")
|
|
466
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Notification config updated: grouping=$enabled, showNotificationsEnabled=$showNotifications, showCompletionNotification=$showCompletionNotification, showCancelAction=$showCancelAction, mode=${config.mode}, texts=$texts")
|
|
306
467
|
}
|
|
307
468
|
|
|
308
469
|
/**
|