@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
|
@@ -12,8 +12,6 @@ import android.os.IBinder
|
|
|
12
12
|
import android.os.PowerManager
|
|
13
13
|
import androidx.core.app.NotificationCompat
|
|
14
14
|
import java.util.concurrent.ConcurrentHashMap
|
|
15
|
-
import java.util.concurrent.ExecutorService
|
|
16
|
-
import java.util.concurrent.Executors
|
|
17
15
|
|
|
18
16
|
/**
|
|
19
17
|
* A foreground service that manages resumable downloads in the background.
|
|
@@ -46,7 +44,6 @@ class ResumableDownloadService : Service() {
|
|
|
46
44
|
}
|
|
47
45
|
|
|
48
46
|
private val binder = LocalBinder()
|
|
49
|
-
private val executorService: ExecutorService = Executors.newFixedThreadPool(DownloadConstants.DOWNLOAD_THREAD_POOL_SIZE)
|
|
50
47
|
private val activeDownloads = ConcurrentHashMap<String, DownloadJob>()
|
|
51
48
|
private var wakeLock: PowerManager.WakeLock? = null
|
|
52
49
|
private var listener: ResumableDownloader.DownloadListener? = null
|
|
@@ -274,7 +271,6 @@ class ResumableDownloadService : Service() {
|
|
|
274
271
|
RNBackgroundDownloaderModuleImpl.logD(TAG, "Service destroyed")
|
|
275
272
|
unmeteredGate.shutdown()
|
|
276
273
|
releaseWakeLock()
|
|
277
|
-
executorService.shutdownNow()
|
|
278
274
|
isForeground = false
|
|
279
275
|
super.onDestroy()
|
|
280
276
|
}
|
|
@@ -19,6 +19,23 @@ class ResumableDownloader {
|
|
|
19
19
|
|
|
20
20
|
companion object {
|
|
21
21
|
private const val TAG = "ResumableDownloader"
|
|
22
|
+
|
|
23
|
+
@Volatile
|
|
24
|
+
private var maxConcurrentTransfers = DownloadConstants.DEFAULT_MAX_PARALLEL_DOWNLOADS
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Cap on transfers running at once, from the JS `maxParallelDownloads`
|
|
28
|
+
* config. Applies to every downloader instance: this path is the one with no
|
|
29
|
+
* scheduler of its own in front of it, so without a cap a batch of downloads
|
|
30
|
+
* takes a thread and a socket each.
|
|
31
|
+
*
|
|
32
|
+
* Raising it lets already waiting downloads start on the next slot release;
|
|
33
|
+
* lowering it never interrupts a transfer that is already running.
|
|
34
|
+
*/
|
|
35
|
+
fun setMaxConcurrentTransfers(max: Int) {
|
|
36
|
+
maxConcurrentTransfers = max.coerceAtLeast(1)
|
|
37
|
+
RNBackgroundDownloaderModuleImpl.logD(TAG, "Max concurrent transfers set to $maxConcurrentTransfers")
|
|
38
|
+
}
|
|
22
39
|
}
|
|
23
40
|
|
|
24
41
|
data class DownloadState(
|
|
@@ -40,11 +57,21 @@ class ResumableDownloader {
|
|
|
40
57
|
val isAllowedOverMetered: Boolean = true,
|
|
41
58
|
// When set, the HTTP connection is opened on this specific network so an
|
|
42
59
|
// unmetered-only download can never leak onto a metered default network
|
|
43
|
-
@Volatile var network: Network? = null
|
|
60
|
+
@Volatile var network: Network? = null,
|
|
61
|
+
// Kept so a download that had to wait for a concurrency slot can be started
|
|
62
|
+
// later without the caller having to hand the listener over again
|
|
63
|
+
@Volatile var listener: DownloadListener? = null
|
|
44
64
|
)
|
|
45
65
|
|
|
46
66
|
private val activeDownloads = ConcurrentHashMap<String, DownloadState>()
|
|
47
67
|
|
|
68
|
+
// Concurrency accounting. `transferring` maps a download to the session ID of
|
|
69
|
+
// the transfer holding its slot, so a restarted download's old thread can't
|
|
70
|
+
// release the slot its replacement took. `waitingForSlot` is FIFO.
|
|
71
|
+
private val transferLock = Any()
|
|
72
|
+
private val transferring = mutableMapOf<String, Long>()
|
|
73
|
+
private val waitingForSlot = ArrayDeque<String>()
|
|
74
|
+
|
|
48
75
|
interface DownloadListener {
|
|
49
76
|
fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>)
|
|
50
77
|
fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long)
|
|
@@ -72,15 +99,91 @@ class ResumableDownloader {
|
|
|
72
99
|
) {
|
|
73
100
|
val state = registerNewDownload(id, url, destination, headers, startByte, totalBytes, isAllowedOverMetered)
|
|
74
101
|
state.network = network
|
|
102
|
+
state.listener = listener
|
|
103
|
+
|
|
104
|
+
beginOrQueueTransfer(state)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Start the download's transfer, or leave it waiting when the concurrency cap
|
|
109
|
+
* is already reached. A waiting download starts as soon as a running transfer
|
|
110
|
+
* ends - completed, failed, paused or cancelled, all of which end its thread.
|
|
111
|
+
*/
|
|
112
|
+
private fun beginOrQueueTransfer(state: DownloadState) {
|
|
113
|
+
val sessionId = state.sessionId.get()
|
|
114
|
+
|
|
115
|
+
synchronized(transferLock) {
|
|
116
|
+
if (transferring.size >= maxConcurrentTransfers) {
|
|
117
|
+
if (!waitingForSlot.contains(state.id)) {
|
|
118
|
+
waitingForSlot.addLast(state.id)
|
|
119
|
+
}
|
|
120
|
+
RNBackgroundDownloaderModuleImpl.logD(
|
|
121
|
+
TAG,
|
|
122
|
+
"Queued download ${state.id}: ${transferring.size} transfer(s) running, max $maxConcurrentTransfers"
|
|
123
|
+
)
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
transferring[state.id] = sessionId
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
startTransferThread(state, sessionId)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private fun startTransferThread(state: DownloadState, sessionId: Long) {
|
|
133
|
+
val listener = state.listener
|
|
134
|
+
if (listener == null) {
|
|
135
|
+
RNBackgroundDownloaderModuleImpl.logW(TAG, "No listener for ${state.id}, cannot start transfer")
|
|
136
|
+
releaseTransferSlot(state.id, sessionId)
|
|
137
|
+
return
|
|
138
|
+
}
|
|
75
139
|
|
|
76
|
-
val currentSessionId = state.sessionId.get()
|
|
77
140
|
val thread = Thread {
|
|
78
|
-
|
|
141
|
+
try {
|
|
142
|
+
downloadWithResume(state, listener, sessionId)
|
|
143
|
+
} finally {
|
|
144
|
+
// The thread ends on every outcome - complete, error, pause, cancel and
|
|
145
|
+
// stale-session exits - so this is the one place a slot is given back
|
|
146
|
+
releaseTransferSlot(state.id, sessionId)
|
|
147
|
+
}
|
|
79
148
|
}
|
|
80
149
|
state.thread = thread
|
|
81
150
|
thread.start()
|
|
82
151
|
}
|
|
83
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Give back the slot held by this transfer and start the next download waiting
|
|
155
|
+
* for one. Ignores a release from a superseded session: a restarted download
|
|
156
|
+
* must not release the slot its replacement is holding.
|
|
157
|
+
*/
|
|
158
|
+
private fun releaseTransferSlot(id: String, sessionId: Long) {
|
|
159
|
+
var next: DownloadState? = null
|
|
160
|
+
var nextSessionId = 0L
|
|
161
|
+
|
|
162
|
+
synchronized(transferLock) {
|
|
163
|
+
if (transferring[id] != sessionId) return
|
|
164
|
+
transferring.remove(id)
|
|
165
|
+
|
|
166
|
+
while (next == null && waitingForSlot.isNotEmpty()) {
|
|
167
|
+
val candidateId = waitingForSlot.removeFirst()
|
|
168
|
+
val candidate = activeDownloads[candidateId] ?: continue
|
|
169
|
+
// Skip downloads that stopped waiting while they were in the queue
|
|
170
|
+
if (candidate.isCancelled.get() || candidate.isPaused.get()) continue
|
|
171
|
+
if (transferring.containsKey(candidateId)) continue
|
|
172
|
+
|
|
173
|
+
nextSessionId = candidate.sessionId.get()
|
|
174
|
+
transferring[candidateId] = nextSessionId
|
|
175
|
+
next = candidate
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
next?.let { startTransferThread(it, nextSessionId) }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Drop a download from the waiting queue (paused, cancelled or restarted). */
|
|
183
|
+
private fun dropFromWaitingQueue(id: String) {
|
|
184
|
+
synchronized(transferLock) { waitingForSlot.remove(id) }
|
|
185
|
+
}
|
|
186
|
+
|
|
84
187
|
/**
|
|
85
188
|
* Register an unmetered-only download in a paused/waiting state WITHOUT
|
|
86
189
|
* starting the transfer. Used by the unmetered-network gate on Android < 14:
|
|
@@ -128,6 +231,9 @@ class ResumableDownloader {
|
|
|
128
231
|
}
|
|
129
232
|
existingState.thread?.interrupt()
|
|
130
233
|
activeDownloads.remove(id)
|
|
234
|
+
// The replacement re-queues itself; the old entry would point at a state
|
|
235
|
+
// that is no longer registered
|
|
236
|
+
dropFromWaitingQueue(id)
|
|
131
237
|
}
|
|
132
238
|
|
|
133
239
|
// Download directly to destination file
|
|
@@ -177,6 +283,10 @@ class ResumableDownloader {
|
|
|
177
283
|
val newSessionId = state.sessionId.incrementAndGet()
|
|
178
284
|
state.isPaused.set(true)
|
|
179
285
|
|
|
286
|
+
// A download still waiting for a concurrency slot has no thread to stop, and
|
|
287
|
+
// must not start once one frees up - the user paused it
|
|
288
|
+
dropFromWaitingQueue(id)
|
|
289
|
+
|
|
180
290
|
// Close input stream to force read to fail immediately
|
|
181
291
|
try {
|
|
182
292
|
state.inputStream?.close()
|
|
@@ -207,17 +317,12 @@ class ResumableDownloader {
|
|
|
207
317
|
return false
|
|
208
318
|
}
|
|
209
319
|
|
|
210
|
-
// Session ID was already incremented in pause(), use current value
|
|
211
|
-
val currentSessionId = state.sessionId.get()
|
|
212
320
|
state.isPaused.set(false)
|
|
321
|
+
state.listener = listener
|
|
322
|
+
// Session ID was already incremented in pause(); beginOrQueueTransfer reads it
|
|
323
|
+
beginOrQueueTransfer(state)
|
|
213
324
|
|
|
214
|
-
|
|
215
|
-
downloadWithResume(state, listener, currentSessionId)
|
|
216
|
-
}
|
|
217
|
-
state.thread = thread
|
|
218
|
-
thread.start()
|
|
219
|
-
|
|
220
|
-
RNBackgroundDownloaderModuleImpl.logD(TAG, "Resuming download: $id from ${state.bytesDownloaded.get()} bytes (session $currentSessionId)")
|
|
325
|
+
RNBackgroundDownloaderModuleImpl.logD(TAG, "Resuming download: $id from ${state.bytesDownloaded.get()} bytes (session ${state.sessionId.get()})")
|
|
221
326
|
return true
|
|
222
327
|
}
|
|
223
328
|
|
|
@@ -232,6 +337,10 @@ class ResumableDownloader {
|
|
|
232
337
|
state.isCancelled.set(true)
|
|
233
338
|
state.isPaused.set(false) // Unblock if paused
|
|
234
339
|
|
|
340
|
+
// Nothing will start it now, but leaving it queued would make the next slot
|
|
341
|
+
// release walk over a dead entry
|
|
342
|
+
dropFromWaitingQueue(id)
|
|
343
|
+
|
|
235
344
|
// Close input stream to force read to fail immediately
|
|
236
345
|
try {
|
|
237
346
|
state.inputStream?.close()
|
|
@@ -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
|
+
}
|