@kesha-antonov/react-native-background-downloader 4.5.8 → 4.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -3
- package/android/build.gradle +17 -0
- package/android/src/main/AndroidManifest.xml +24 -0
- package/android/src/main/java/com/eko/DownloadConstants.kt +14 -2
- package/android/src/main/java/com/eko/Downloader.kt +77 -12
- package/android/src/main/java/com/eko/PromiseExtensions.kt +36 -0
- package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +82 -134
- package/android/src/main/java/com/eko/ResumableDownloadService.kt +0 -4
- package/android/src/main/java/com/eko/ResumableDownloader.kt +121 -12
- package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +65 -9
- package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +64 -0
- package/android/src/main/java/com/eko/uidt/RNBGDFileProvider.kt +17 -0
- package/android/src/main/java/com/eko/uidt/UIDTJobIds.kt +112 -0
- package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +178 -17
- package/android/src/main/java/com/eko/uidt/UIDTJobState.kt +23 -1
- package/android/src/main/java/com/eko/uidt/UIDTNotificationIds.kt +73 -0
- package/android/src/main/java/com/eko/uidt/UIDTNotificationManager.kt +246 -19
- package/android/src/main/java/com/eko/utils/ReadableConverters.kt +55 -0
- package/android/src/main/java/com/eko/utils/RedirectResolver.kt +97 -0
- package/android/src/main/java/com/eko/utils/StorageManager.kt +13 -0
- package/android/src/main/res/xml/rnbgd_file_paths.xml +23 -0
- package/android/src/newarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
- package/android/src/oldarch/java/com/eko/RNBackgroundDownloaderModule.kt +18 -70
- package/android/src/test/java/com/eko/ResumableDownloaderConcurrencyTest.kt +199 -0
- package/android/src/test/java/com/eko/uidt/UIDTJobIdsTest.kt +159 -0
- package/android/src/test/java/com/eko/uidt/UIDTJobManagerTest.kt +192 -0
- package/android/src/test/java/com/eko/uidt/UIDTNotificationIdsTest.kt +99 -0
- package/ios/RNBackgroundDownloader.mm +187 -91
- package/lib/DownloadTask.js +8 -7
- package/lib/NativeRNBackgroundDownloader.d.ts +2 -0
- package/lib/UploadTask.js +11 -10
- package/lib/config.d.ts +3 -10
- package/lib/config.js +4 -44
- package/lib/index.d.ts +1 -1
- package/lib/index.js +43 -34
- package/lib/logger.d.ts +2 -0
- package/lib/logger.js +16 -0
- package/lib/notifications.d.ts +8 -0
- package/lib/notifications.js +35 -0
- package/lib/types.d.ts +19 -0
- package/package.json +8 -3
- package/src/DownloadTask.ts +2 -1
- package/src/NativeRNBackgroundDownloader.ts +8 -1
- package/src/UploadTask.ts +2 -1
- package/src/config.ts +9 -45
- package/src/index.ts +22 -2
- package/src/logger.ts +16 -0
- package/src/notifications.ts +32 -0
- package/src/types.ts +19 -0
|
@@ -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
|
/**
|
|
@@ -16,6 +16,9 @@ data class JobState(
|
|
|
16
16
|
var notificationId: Int,
|
|
17
17
|
val groupId: String = "",
|
|
18
18
|
val groupName: String = "",
|
|
19
|
+
// Optional per-download notification title (read from metadata.notificationTitle).
|
|
20
|
+
// When non-empty, overrides both groupName and the config's default downloadTitle.
|
|
21
|
+
val customTitle: String = "",
|
|
19
22
|
var lastNotifiedProgress: Int = -1,
|
|
20
23
|
var lastNotificationUpdateTime: Long = 0,
|
|
21
24
|
// Track download progress for summary notification
|
|
@@ -37,6 +40,12 @@ enum class NotificationGroupingMode {
|
|
|
37
40
|
data class NotificationConfig(
|
|
38
41
|
var groupingEnabled: Boolean = false,
|
|
39
42
|
var showNotificationsEnabled: Boolean = false,
|
|
43
|
+
// Post a "download complete" notification when a download finishes.
|
|
44
|
+
// Opt-in: it alerts on its own channel, unlike the silent progress one.
|
|
45
|
+
var showCompletionNotification: Boolean = false,
|
|
46
|
+
// Add a Cancel button to the progress notification. Opt-in: cancelling
|
|
47
|
+
// from the shade surfaces in JS as a downloadFailed the app has to handle.
|
|
48
|
+
var showCancelAction: Boolean = false,
|
|
40
49
|
var mode: NotificationGroupingMode = NotificationGroupingMode.INDIVIDUAL,
|
|
41
50
|
var updateInterval: Long = 500L,
|
|
42
51
|
val texts: MutableMap<String, String> = mutableMapOf(
|
|
@@ -45,6 +54,7 @@ data class NotificationConfig(
|
|
|
45
54
|
"downloadProgress" to "Downloading... {progress}%",
|
|
46
55
|
"downloadPaused" to "Paused",
|
|
47
56
|
"downloadFinished" to "Download complete",
|
|
57
|
+
"downloadCancel" to "Cancel",
|
|
48
58
|
"groupTitle" to "Downloads",
|
|
49
59
|
"groupText" to "{count} download(s) in progress"
|
|
50
60
|
)
|
|
@@ -83,7 +93,8 @@ data class GroupProgress(
|
|
|
83
93
|
object UIDTConstants {
|
|
84
94
|
const val TAG = "UIDTDownloadJobService"
|
|
85
95
|
|
|
86
|
-
//
|
|
96
|
+
// Start of the job-ID range owned by the library. IDs inside it are handed
|
|
97
|
+
// out per download by UIDTJobIds.
|
|
87
98
|
const val JOB_ID_BASE = 10000
|
|
88
99
|
|
|
89
100
|
// PersistableBundle keys
|
|
@@ -104,6 +115,11 @@ object UIDTConstants {
|
|
|
104
115
|
// Notification channel for UIDT jobs (ultra-silent for summaryOnly mode)
|
|
105
116
|
const val NOTIFICATION_CHANNEL_ULTRA_SILENT_ID = "uidt_download_channel_ultra_silent"
|
|
106
117
|
|
|
118
|
+
// Notification channel for the one-shot "download complete" notification.
|
|
119
|
+
// Uses IMPORTANCE_DEFAULT so completion is actually surfaced to the user
|
|
120
|
+
// (the progress channel is IMPORTANCE_LOW and never alerts).
|
|
121
|
+
const val NOTIFICATION_CHANNEL_FINISHED_ID = "uidt_download_channel_finished"
|
|
122
|
+
|
|
107
123
|
// Notification group for grouping all download notifications together
|
|
108
124
|
const val NOTIFICATION_GROUP_KEY = "com.eko.DOWNLOAD_GROUP"
|
|
109
125
|
|
|
@@ -112,6 +128,12 @@ object UIDTConstants {
|
|
|
112
128
|
|
|
113
129
|
// Base for individual notification IDs
|
|
114
130
|
const val NOTIFICATION_ID_BASE = 20000
|
|
131
|
+
|
|
132
|
+
// Base for one-shot "download complete" notification IDs. Kept in a
|
|
133
|
+
// disjoint range from NOTIFICATION_ID_BASE (which spans 20000..119999 via
|
|
134
|
+
// hash % 100000) so a finished notification can never collide with another
|
|
135
|
+
// download's in-progress notification.
|
|
136
|
+
const val FINISHED_NOTIFICATION_ID_BASE = 200000
|
|
115
137
|
}
|
|
116
138
|
|
|
117
139
|
/**
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
package com.eko.uidt
|
|
2
|
+
|
|
3
|
+
import android.os.Build
|
|
4
|
+
import androidx.annotation.RequiresApi
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Assigns the notification IDs used for download notifications.
|
|
8
|
+
*
|
|
9
|
+
* IDs used to be derived as `NOTIFICATION_ID_BASE + hash(configId) % RANGE`, so
|
|
10
|
+
* two downloads whose config IDs hash to the same slot shared one notification:
|
|
11
|
+
* their progress updates overwrote each other, and whichever ended first took
|
|
12
|
+
* the notification down for the other - on the UIDT path for good, since the
|
|
13
|
+
* job's end policy removes it. Across a batch of 150 downloads that is about a
|
|
14
|
+
* one-in-ten chance.
|
|
15
|
+
*
|
|
16
|
+
* The hash is still where the search starts, so a download keeps the ID it has
|
|
17
|
+
* always had unless another live download already holds it. Only the collided
|
|
18
|
+
* one moves, and only for as long as it is running.
|
|
19
|
+
*/
|
|
20
|
+
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
|
|
21
|
+
internal object UIDTNotificationIds {
|
|
22
|
+
|
|
23
|
+
/** Size of each notification-ID range (progress, and the finished one). */
|
|
24
|
+
private const val RANGE = 100000
|
|
25
|
+
|
|
26
|
+
private val lock = Any()
|
|
27
|
+
|
|
28
|
+
/** configId -> offset into the range, held while the download has notifications. */
|
|
29
|
+
private val assigned = mutableMapOf<String, Int>()
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The in-progress notification ID for a download - stable for as long as the
|
|
33
|
+
* download is live, and only ever held by one download at a time.
|
|
34
|
+
*/
|
|
35
|
+
fun progressIdFor(configId: String): Int =
|
|
36
|
+
UIDTConstants.NOTIFICATION_ID_BASE + offsetFor(configId)
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The ID for the one-shot "download complete" notification. Taken from a
|
|
40
|
+
* disjoint range at the same offset, so it inherits the same uniqueness and
|
|
41
|
+
* can never collide with an in-progress notification.
|
|
42
|
+
*/
|
|
43
|
+
fun finishedIdFor(configId: String): Int =
|
|
44
|
+
UIDTConstants.FINISHED_NOTIFICATION_ID_BASE + offsetFor(configId)
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Give the offset back once the download's notifications are gone. Called on
|
|
48
|
+
* the paths that remove them - completion, failure and cancellation.
|
|
49
|
+
*/
|
|
50
|
+
fun release(configId: String) {
|
|
51
|
+
synchronized(lock) { assigned.remove(configId) }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private fun offsetFor(configId: String): Int {
|
|
55
|
+
synchronized(lock) {
|
|
56
|
+
assigned[configId]?.let { return it }
|
|
57
|
+
|
|
58
|
+
val taken = assigned.values.toSet()
|
|
59
|
+
val start = (configId.hashCode() and 0x7FFFFFFF) % RANGE
|
|
60
|
+
for (probe in 0 until RANGE) {
|
|
61
|
+
val candidate = (start + probe) % RANGE
|
|
62
|
+
if (candidate in taken) continue
|
|
63
|
+
assigned[configId] = candidate
|
|
64
|
+
return candidate
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Every offset in use at once is not a real state (it would mean
|
|
68
|
+
// 100000 live downloads), but never return a colliding ID silently
|
|
69
|
+
assigned[configId] = start
|
|
70
|
+
return start
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|