@kesha-antonov/react-native-background-downloader 4.8.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +10 -5
  2. package/android/build.gradle +5 -1
  3. package/android/consumer-rules.pro +14 -0
  4. package/android/src/main/AndroidManifest.xml +18 -1
  5. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +5 -567
  6. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +4 -58
  7. package/android/src/main/java/com/{eko → kesha_antonov}/DownloadConstants.kt +1 -1
  8. package/android/src/main/java/com/{eko → kesha_antonov}/DownloadEventEmitter.kt +1 -1
  9. package/android/src/main/java/com/{eko → kesha_antonov}/DownloadResult.kt +1 -1
  10. package/android/src/main/java/com/{eko → kesha_antonov}/Downloader.kt +2 -2
  11. package/android/src/main/java/com/{eko → kesha_antonov}/ProgressReporter.kt +1 -1
  12. package/android/src/main/java/com/{eko → kesha_antonov}/PromiseExtensions.kt +1 -1
  13. package/android/src/main/java/com/{eko → kesha_antonov}/RNBGDTaskConfig.kt +1 -1
  14. package/android/src/main/java/com/{eko → kesha_antonov}/RNBGDUploadTaskConfig.kt +1 -1
  15. package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModuleImpl.kt +9 -9
  16. package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderPackage.kt +1 -1
  17. package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloadService.kt +11 -9
  18. package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloader.kt +2 -2
  19. package/android/src/main/java/com/kesha_antonov/UIDTDownloadJobService.kt +590 -0
  20. package/android/src/main/java/com/{eko → kesha_antonov}/UnmeteredNetworkGate.kt +2 -2
  21. package/android/src/main/java/com/{eko → kesha_antonov}/UploadEventEmitter.kt +1 -1
  22. package/android/src/main/java/com/{eko → kesha_antonov}/Uploader.kt +2 -2
  23. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBegin.kt +4 -4
  24. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBeginState.kt +1 -1
  25. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgress.kt +4 -4
  26. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgressState.kt +1 -1
  27. package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/BeginCallback.kt +1 -1
  28. package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/ProgressCallback.kt +1 -1
  29. package/android/src/main/java/com/kesha_antonov/uidt/CancelDownloadReceiver.kt +68 -0
  30. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/RNBGDFileProvider.kt +1 -1
  31. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobIds.kt +9 -4
  32. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobManager.kt +6 -6
  33. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobState.kt +7 -5
  34. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIds.kt +1 -1
  35. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationManager.kt +18 -10
  36. package/android/src/main/java/com/{eko → kesha_antonov}/utils/FileUtils.kt +1 -1
  37. package/android/src/main/java/com/{eko → kesha_antonov}/utils/HeaderUtils.kt +2 -2
  38. package/android/src/main/java/com/{eko → kesha_antonov}/utils/NetworkRequestUtils.kt +1 -1
  39. package/android/src/main/java/com/kesha_antonov/utils/NotificationUtils.kt +24 -0
  40. package/android/src/main/java/com/{eko → kesha_antonov}/utils/ProgressUtils.kt +1 -1
  41. package/android/src/main/java/com/{eko → kesha_antonov}/utils/ReadableConverters.kt +1 -1
  42. package/android/src/main/java/com/{eko → kesha_antonov}/utils/RedirectResolver.kt +3 -3
  43. package/android/src/main/java/com/{eko → kesha_antonov}/utils/StorageManager.kt +5 -5
  44. package/android/src/main/java/com/{eko → kesha_antonov}/utils/TempFileUtils.kt +2 -2
  45. package/android/src/newarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
  46. package/android/src/oldarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
  47. package/android/src/test/java/com/{eko → kesha_antonov}/DownloadCompleteReceiverTest.kt +1 -1
  48. package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderRecoveryTest.kt +2 -2
  49. package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderResumeTest.kt +3 -3
  50. package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderConcurrencyTest.kt +1 -1
  51. package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderRedirectTest.kt +1 -1
  52. package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderStallTest.kt +1 -1
  53. package/android/src/test/java/com/{eko → kesha_antonov}/UnmeteredNetworkGateTest.kt +1 -1
  54. package/android/src/test/java/com/{eko → kesha_antonov}/UploadPartRangesTest.kt +1 -1
  55. package/android/src/test/java/com/{eko → kesha_antonov}/UploaderMultipartTest.kt +1 -1
  56. package/android/src/test/java/com/{eko → kesha_antonov}/UploaderPartsTest.kt +1 -1
  57. package/android/src/test/java/com/{eko → kesha_antonov}/UploaderResponseTest.kt +1 -1
  58. package/android/src/test/java/com/{eko → kesha_antonov}/handlers/OnBeginTest.kt +2 -2
  59. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/CancelDownloadReceiverTest.kt +25 -2
  60. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobIdsTest.kt +13 -2
  61. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobManagerTest.kt +1 -1
  62. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIdsTest.kt +1 -1
  63. package/android/src/test/java/com/{eko → kesha_antonov}/utils/RedirectResolverTest.kt +1 -1
  64. package/bin/react-native-background-downloader.js +197 -0
  65. package/ios/RNBackgroundDownloader.mm +25 -5
  66. package/package.json +5 -2
@@ -1,575 +1,13 @@
1
1
  package com.eko
2
2
 
3
- import android.app.job.JobParameters
4
- import android.app.job.JobService
5
- import android.content.Context
6
3
  import android.os.Build
7
- import android.os.PowerManager
8
4
  import androidx.annotation.RequiresApi
9
- import com.eko.uidt.JobState
10
- import com.eko.uidt.NotificationGroupingMode
11
- import com.eko.uidt.UIDTConstants
12
- import com.eko.uidt.UIDTJobInfo
13
- import com.eko.uidt.UIDTJobManager
14
- import com.eko.uidt.UIDTJobRegistry
15
- import com.eko.uidt.UIDTNotificationIds
16
- import com.eko.uidt.UIDTNotificationManager
17
- import com.eko.utils.ProgressUtils
18
- import com.eko.utils.StorageManager
19
- import org.json.JSONObject
20
- import java.io.File
21
5
 
22
6
  /**
23
- * A JobService that uses User-Initiated Data Transfer (UIDT) for background downloads.
24
- *
25
- * UIDT was introduced in Android 14 (API 34) and is required for reliable background
26
- * downloads on Android 16+ where foreground services are more restricted.
27
- *
28
- * Key benefits of UIDT:
29
- * - Not affected by App Standby Buckets quotas
30
- * - Can run for extended periods as system conditions allow
31
- * - Shows in Task Manager for user visibility
32
- * - Properly handles thermal throttling and system health restrictions
33
- *
34
- * This class handles only the JobService lifecycle. Job management, notifications,
35
- * and state are delegated to:
36
- * - [UIDTJobManager] - Job scheduling, cancellation, pause/resume
37
- * - [UIDTNotificationManager] - Notification creation and updates
38
- * - [UIDTJobRegistry] - Active job state tracking
39
- *
40
- * @see <a href="https://developer.android.com/develop/background-work/background-tasks/uidt">UIDT Documentation</a>
7
+ * The job service under its name before v5.0.0. A download that v4.x scheduled
8
+ * with the JobScheduler names this class, and the system runs it here after the
9
+ * app is updated; without it that job has no service to run in and the download
10
+ * is lost. New jobs use [com.kesha_antonov.UIDTDownloadJobService].
41
11
  */
42
12
  @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
43
- class UIDTDownloadJobService : JobService() {
44
-
45
- companion object {
46
- // Delegate static methods to UIDTJobManager and UIDTJobRegistry for backward compatibility
47
-
48
- /**
49
- * Schedule a UIDT download job.
50
- */
51
- fun scheduleDownload(
52
- context: Context,
53
- configId: String,
54
- url: String,
55
- destination: String,
56
- headers: Map<String, String>,
57
- startByte: Long = 0,
58
- totalBytes: Long = -1,
59
- metadata: String = "{}",
60
- isAllowedOverMetered: Boolean
61
- ): Boolean = UIDTJobManager.scheduleDownload(context, configId, url, destination, headers, startByte, totalBytes, metadata, isAllowedOverMetered)
62
-
63
- /**
64
- * Cancel a scheduled UIDT job.
65
- */
66
- fun cancelJob(context: Context, configId: String) = UIDTJobManager.cancelJob(context, configId)
67
-
68
- /**
69
- * Check if a download is active as a UIDT job.
70
- */
71
- fun isActiveJob(configId: String): Boolean = UIDTJobRegistry.isActiveJob(configId)
72
-
73
- /**
74
- * Check if a download is paused in a UIDT job.
75
- */
76
- fun isPausedJob(configId: String): Boolean = UIDTJobRegistry.isPausedJob(configId)
77
-
78
- /**
79
- * Get the download state for a UIDT job.
80
- */
81
- fun getJobDownloadState(configId: String): ResumableDownloader.DownloadState? = UIDTJobRegistry.getJobDownloadState(configId)
82
-
83
- /**
84
- * Get the metered-network permission of an active UIDT job (null if not active).
85
- */
86
- fun getJobIsAllowedOverMetered(configId: String): Boolean? = UIDTJobRegistry.getJobIsAllowedOverMetered(configId)
87
-
88
- /**
89
- * Pause an active UIDT download.
90
- */
91
- fun pauseJob(context: Context, configId: String): Boolean = UIDTJobManager.pauseJob(context, configId)
92
-
93
- /**
94
- * Cancel a scheduled-but-not-running UIDT job (e.g. held pending by its
95
- * unmetered-network constraint) and return its persistable info.
96
- */
97
- fun cancelPendingJob(context: Context, configId: String): UIDTJobManager.PendingJobInfo? =
98
- UIDTJobManager.cancelPendingJob(context, configId)
99
-
100
- /**
101
- * Resume a paused UIDT download.
102
- */
103
- fun resumeJob(context: Context, configId: String, listener: ResumableDownloader.DownloadListener): Boolean =
104
- UIDTJobManager.resumeJob(context, configId, listener)
105
-
106
- /**
107
- * Configure notification grouping and texts.
108
- */
109
- fun setNotificationGroupingConfig(
110
- enabled: Boolean,
111
- showNotificationsEnabled: Boolean,
112
- showCompletionNotification: Boolean,
113
- showCancelAction: Boolean,
114
- mode: String,
115
- texts: Map<String, String>
116
- ) = UIDTJobManager.setNotificationConfig(
117
- enabled,
118
- showNotificationsEnabled,
119
- showCompletionNotification,
120
- showCancelAction,
121
- mode,
122
- texts
123
- )
124
-
125
- /**
126
- * Set notification update interval.
127
- */
128
- fun setNotificationUpdateInterval(interval: Long) = UIDTJobManager.setNotificationUpdateInterval(interval)
129
-
130
- /**
131
- * Check if notifications are enabled globally.
132
- */
133
- fun isNotificationsEnabled(): Boolean = UIDTJobManager.isNotificationsEnabled()
134
-
135
- /**
136
- * Cancel notification for a specific download.
137
- */
138
- fun cancelNotification(context: Context, configId: String) = UIDTNotificationManager.cancelNotification(context, configId)
139
-
140
- /**
141
- * Returns a snapshot of all currently active UIDT jobs.
142
- * Used by the module to populate getExistingDownloads on Android 14+.
143
- */
144
- fun getAllActiveJobs(): List<UIDTJobInfo> = UIDTJobRegistry.getAllActiveJobs()
145
-
146
- /**
147
- * Returns the downloads whose job is scheduled but hasn't started yet.
148
- * These have no registry entry, so they are invisible to [getAllActiveJobs].
149
- */
150
- fun getScheduledJobs(context: Context): List<UIDTJobInfo> = UIDTJobManager.getScheduledJobs(context)
151
-
152
- /**
153
- * Whether a download has a job with the JobScheduler, running or not yet started.
154
- */
155
- fun isScheduledJob(context: Context, configId: String): Boolean =
156
- UIDTJobManager.isScheduledJob(context, configId)
157
-
158
- /**
159
- * Set download listener.
160
- */
161
- var downloadListener: ResumableDownloader.DownloadListener?
162
- get() = UIDTJobRegistry.downloadListener
163
- set(value) { UIDTJobRegistry.downloadListener = value }
164
-
165
- /**
166
- * The byte a job continues from. When resuming, the partial file is the source of
167
- * truth: a saved offset can lag the bytes written (it's recorded when the job stops,
168
- * or not at all if the process died), and appending from a lower offset duplicates
169
- * data. No file means start over.
170
- */
171
- internal fun resumeStartByte(savedStartByte: Long, destination: String): Long =
172
- if (savedStartByte > 0) File(destination).let { if (it.exists()) it.length() else 0L } else 0L
173
- }
174
-
175
- private var wakeLock: PowerManager.WakeLock? = null
176
-
177
- override fun onCreate() {
178
- super.onCreate()
179
- UIDTJobRegistry.serviceInstance = this
180
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDTDownloadJobService created")
181
- UIDTNotificationManager.createNotificationChannels(this)
182
- }
183
-
184
- override fun onDestroy() {
185
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDTDownloadJobService destroyed")
186
- UIDTJobRegistry.serviceInstance = null
187
- releaseWakeLock()
188
- super.onDestroy()
189
- }
190
-
191
- override fun onStartJob(params: JobParameters): Boolean {
192
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob called")
193
-
194
- val extras = params.extras
195
- val configId = extras.getString(UIDTConstants.KEY_DOWNLOAD_ID) ?: run {
196
- RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "No download ID in job extras")
197
- return false
198
- }
199
- val url = extras.getString(UIDTConstants.KEY_URL) ?: return false
200
- val destination = extras.getString(UIDTConstants.KEY_DESTINATION) ?: return false
201
- val startByteFromExtras = extras.getLong(UIDTConstants.KEY_START_BYTE, 0)
202
- val totalBytes = extras.getLong(UIDTConstants.KEY_TOTAL_BYTES, -1)
203
- val isAllowedOverMetered = extras.getBoolean(UIDTConstants.KEY_IS_ALLOWED_OVER_METERED, true)
204
-
205
- // Extract group info from metadata (for notification grouping)
206
- val metadataJson = extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
207
- var groupId = ""
208
- var groupName = ""
209
- var customTitle = ""
210
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob: configId=$configId, metadataJson=$metadataJson")
211
- try {
212
- val json = JSONObject(metadataJson)
213
- groupId = json.optString("groupId", "")
214
- groupName = json.optString("groupName", "")
215
- customTitle = json.optString("notificationTitle", "")
216
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Parsed metadata: groupId='$groupId', groupName='$groupName', customTitle='$customTitle'")
217
- } catch (e: Exception) {
218
- RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "Failed to parse metadata: ${e.message}")
219
- }
220
-
221
- // Resolve headers and start byte.
222
- // In-memory pendingHeaders is populated in the same process (scheduleDownload / onStopJob).
223
- // The disk-persisted resume state is the fallback for a fresh process after a restart.
224
- val inMemoryHeaders = UIDTJobRegistry.pendingHeaders.remove(configId)
225
- // Kept on disk until the download completes, fails or is cancelled (those clear it):
226
- // if the process dies mid-transfer, the restarted job still needs the headers
227
- val diskResumeState = UIDTJobRegistry.loadResumeState(this, configId)
228
-
229
- val headers: Map<String, String>
230
- val savedStartByte: Long
231
- when {
232
- inMemoryHeaders != null -> {
233
- // Same-process restart: use in-memory headers.
234
- // Prefer the disk byte position if it is more advanced than the extras
235
- // (written by onStopJob with the actual download offset).
236
- headers = inMemoryHeaders
237
- savedStartByte = if (diskResumeState != null && diskResumeState.second > startByteFromExtras)
238
- diskResumeState.second else startByteFromExtras
239
- }
240
- diskResumeState != null -> {
241
- // Cross-process restart: use the persisted state.
242
- headers = diskResumeState.first
243
- savedStartByte = diskResumeState.second
244
- }
245
- else -> {
246
- headers = emptyMap()
247
- savedStartByte = startByteFromExtras
248
- }
249
- }
250
- val startByte = resumeStartByte(savedStartByte, destination)
251
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob: configId=$configId, startByte=$startByte, headers=${headers.size}")
252
-
253
- // Create notification for UIDT job (required)
254
- val notificationId = UIDTNotificationManager.getNotificationIdForConfig(configId)
255
- val notification = UIDTNotificationManager.createDownloadNotification(this, configId, groupId, groupName, customTitle)
256
-
257
- // Set the notification for this job (required for UIDT)
258
- setNotification(params, notificationId, notification, JOB_END_NOTIFICATION_POLICY_DETACH)
259
-
260
- // Acquire wake lock
261
- acquireWakeLock()
262
-
263
- // Create ResumableDownloader for this job
264
- val resumableDownloader = ResumableDownloader()
265
-
266
- // Unmark group as finalized if it was previously (in case of new batch with same groupId)
267
- if (groupId.isNotEmpty()) {
268
- UIDTJobRegistry.unmarkGroupFinalized(groupId)
269
- }
270
-
271
- // Store job state BEFORE updating summary (so count includes this job)
272
- UIDTJobRegistry.activeJobs[configId] = JobState(params, resumableDownloader, notificationId, groupId, groupName, customTitle)
273
-
274
- // Update summary notification if grouping enabled (now includes new job in count)
275
- UIDTNotificationManager.updateSummaryNotificationForGroup(this, groupId, groupName)
276
-
277
- // Create listener that will notify completion
278
- val jobListener = createJobListener(configId, params, groupId, groupName, customTitle)
279
-
280
- // Start the download asynchronously. The network constraint is enforced by
281
- // the JobScheduler; the flag is passed so the DownloadState stays truthful
282
- // (it is a fallback source for pause/snapshot persistence in the module).
283
- // Bind the transfer to the network that satisfied the job's constraint -
284
- // otherwise the sockets use the DEFAULT network, which can be metered
285
- // cellular even while the satisfying unmetered network is connected.
286
- resumableDownloader.startDownload(
287
- id = configId,
288
- url = url,
289
- destination = destination,
290
- headers = headers,
291
- listener = jobListener,
292
- startByte = startByte,
293
- totalBytes = totalBytes,
294
- isAllowedOverMetered = isAllowedOverMetered,
295
- network = params.network
296
- )
297
-
298
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Started UIDT download: $configId from byte $startByte")
299
-
300
- // Return true - work is being done asynchronously
301
- return true
302
- }
303
-
304
- override fun onStopJob(params: JobParameters): Boolean {
305
- val extras = params.extras
306
- val configId = extras.getString(UIDTConstants.KEY_DOWNLOAD_ID)
307
-
308
- val stopReason = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
309
- params.stopReason
310
- } else {
311
- -1
312
- }
313
-
314
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStopJob called for $configId, reason: $stopReason")
315
-
316
- if (configId != null) {
317
- val jobState = UIDTJobRegistry.activeJobs[configId]
318
- if (jobState != null) {
319
- // Pause the download - it can be resumed later
320
- jobState.resumableDownloader.pause(configId)
321
-
322
- // Save state for potential resume
323
- val state = jobState.resumableDownloader.getState(configId)
324
- if (state != null) {
325
- val bytesDownloaded = state.bytesDownloaded.get()
326
- // Keep in-memory headers so the same-process reschedule works.
327
- UIDTJobRegistry.pendingHeaders[configId] = state.headers
328
- // Persist to disk so a fresh process can resume from the right position.
329
- UIDTJobRegistry.saveResumeState(this, configId, state.headers, bytesDownloaded)
330
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStopJob: saved resume state for $configId at $bytesDownloaded bytes")
331
- }
332
- }
333
- UIDTJobRegistry.activeJobs.remove(configId)
334
- }
335
-
336
- releaseWakeLock()
337
-
338
- // Return true to reschedule the job if it was stopped by system
339
- return true
340
- }
341
-
342
- private fun createJobListener(
343
- configId: String,
344
- params: JobParameters,
345
- groupId: String,
346
- groupName: String,
347
- customTitle: String = ""
348
- ): ResumableDownloader.DownloadListener {
349
- return object : ResumableDownloader.DownloadListener {
350
- override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) {
351
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDT download begin: $id, expectedBytes: $expectedBytes")
352
-
353
- // Update notification with size info
354
- val jobState = UIDTJobRegistry.activeJobs[id]
355
- if (jobState != null) {
356
- // Store total bytes for summary progress calculation
357
- jobState.bytesTotal = expectedBytes
358
- UIDTNotificationManager.updateProgressNotification(this@UIDTDownloadJobService, id, jobState, 0, expectedBytes)
359
- }
360
-
361
- // Notify external listener
362
- UIDTJobRegistry.downloadListener?.onBegin(id, expectedBytes, headers)
363
- }
364
-
365
- override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) {
366
- val jobState = UIDTJobRegistry.activeJobs[id]
367
- if (jobState != null) {
368
- // Always update progress tracking in JobState for summary calculation
369
- jobState.bytesDownloaded = bytesDownloaded
370
- if (bytesTotal > 0) {
371
- jobState.bytesTotal = bytesTotal
372
- }
373
-
374
- // Check if download is paused - don't update notification with progress
375
- val isPaused = jobState.resumableDownloader.isPaused(id)
376
- if (isPaused) {
377
- // Still notify external listener for state tracking, but don't update notification
378
- UIDTJobRegistry.downloadListener?.onProgress(id, bytesDownloaded, bytesTotal)
379
- return
380
- }
381
-
382
- val config = UIDTJobRegistry.notificationConfig
383
- val isSummaryOnlyMode = config.mode == NotificationGroupingMode.SUMMARY_ONLY
384
-
385
- if (bytesTotal > 0) {
386
- val progress = ProgressUtils.calculateProgress(bytesDownloaded, bytesTotal)
387
- val currentTime = System.currentTimeMillis()
388
-
389
- val shouldUpdate = ProgressUtils.shouldUpdateProgress(
390
- progress,
391
- jobState.lastNotifiedProgress,
392
- currentTime,
393
- jobState.lastNotificationUpdateTime,
394
- config.updateInterval
395
- )
396
-
397
- if (shouldUpdate) {
398
- jobState.lastNotifiedProgress = progress
399
- jobState.lastNotificationUpdateTime = currentTime
400
-
401
- if (isSummaryOnlyMode && config.groupingEnabled && jobState.groupId.isNotEmpty()) {
402
- // In summaryOnly mode, update only the summary notification
403
- UIDTNotificationManager.updateSummaryNotificationForGroup(
404
- this@UIDTDownloadJobService, jobState.groupId, jobState.groupName
405
- )
406
- } else {
407
- // Update individual notification
408
- UIDTNotificationManager.updateProgressNotification(
409
- this@UIDTDownloadJobService, id, jobState, bytesDownloaded, bytesTotal
410
- )
411
- }
412
- }
413
- }
414
- }
415
-
416
- // Notify external listener (always - JS handles its own throttling)
417
- UIDTJobRegistry.downloadListener?.onProgress(id, bytesDownloaded, bytesTotal)
418
- }
419
-
420
- override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) {
421
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDT download complete: $id, groupId=$groupId")
422
-
423
- val jobState = UIDTJobRegistry.activeJobs[id]
424
- val notificationId = jobState?.notificationId
425
-
426
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onComplete: notificationId=$notificationId, jobState groupId=${jobState?.groupId}")
427
-
428
- // Resolve a display name for the completion notification.
429
- // Prefer metadata.fileName (set from JS), fall back to the
430
- // saved file's basename.
431
- val displayName = try {
432
- val metadataStr = params.extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
433
- val metadata = JSONObject(metadataStr)
434
- metadata.optString("fileName", "").ifEmpty { location.substringAfterLast('/') }
435
- } catch (e: Exception) {
436
- location.substringAfterLast('/')
437
- }
438
-
439
- // Post a standalone "download complete" notification BEFORE
440
- // we tear down the UIDT-controlled one so it persists. Tap
441
- // opens the saved file via FileProvider (system file viewer).
442
- UIDTNotificationManager.showFinishedNotification(
443
- this@UIDTDownloadJobService,
444
- id,
445
- location,
446
- displayName,
447
- jobState?.groupId ?: groupId,
448
- jobState?.customTitle ?: customTitle,
449
- )
450
-
451
- // Clean up - remove from activeJobs first
452
- UIDTJobRegistry.activeJobs.remove(id)
453
- releaseWakeLock()
454
-
455
- // Check if this was the last job in the group
456
- val remainingInGroup = UIDTJobRegistry.activeJobs.values.count { it.groupId == groupId }
457
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Jobs remaining in group '$groupId': $remainingInGroup, activeJobs count=${UIDTJobRegistry.activeJobs.size}")
458
-
459
- if (remainingInGroup == 0 && groupId.isNotEmpty()) {
460
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Last job in group completed. Marking finalized and cancelling summary.")
461
- // Mark group as finalized FIRST to prevent race conditions
462
- // where delayed progress callbacks might recreate the notification
463
- UIDTJobRegistry.markGroupFinalized(groupId)
464
- // Last job in group - cancel summary notification
465
- UIDTNotificationManager.cancelSummaryNotification(this@UIDTDownloadJobService, groupId)
466
- } else if (groupId.isEmpty()) {
467
- RNBackgroundDownloaderModuleImpl.logW(UIDTConstants.TAG, "groupId is empty in onComplete for $id")
468
- } else {
469
- // Update summary notification for this group (update count/progress)
470
- UIDTNotificationManager.updateSummaryNotificationForGroup(this@UIDTDownloadJobService, groupId, groupName)
471
- }
472
-
473
- // Use setNotification with REMOVE policy to tell Android to remove the UIDT-controlled notification
474
- // This is required because UIDT notifications are managed by the system, not NotificationManager
475
- if (notificationId != null) {
476
- val emptyNotification = UIDTNotificationManager.createEmptyNotification(this@UIDTDownloadJobService)
477
- setNotification(params, notificationId, emptyNotification, JOB_END_NOTIFICATION_POLICY_REMOVE)
478
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Set REMOVE policy for notification $notificationId")
479
- }
480
-
481
- // Signal job completion - this triggers the REMOVE policy
482
- jobFinished(params, false)
483
-
484
- // Clear persisted resume state - no longer needed after successful completion
485
- UIDTJobRegistry.clearResumeState(this@UIDTDownloadJobService, id)
486
- // The progress notification is gone; the completion one above already
487
- // took its ID from this offset, so it can go back to the pool
488
- UIDTNotificationIds.release(id)
489
-
490
- // Notify external listener. With none (the job ran in a process without the
491
- // app), record it so the next launch reports it as done, not as paused
492
- val listener = UIDTJobRegistry.downloadListener
493
- if (listener != null) {
494
- listener.onComplete(id, location, bytesDownloaded, bytesTotal)
495
- } else {
496
- recordFinishedWithoutApp(id, bytesDownloaded)
497
- }
498
- }
499
-
500
- override fun onError(id: String, error: String, errorCode: Int) {
501
- RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "UIDT download error: $id - $error ($errorCode)")
502
-
503
- val jobState = UIDTJobRegistry.activeJobs[id]
504
- val notificationId = jobState?.notificationId
505
-
506
- // Clean up - remove from activeJobs first
507
- UIDTJobRegistry.activeJobs.remove(id)
508
- releaseWakeLock()
509
-
510
- // Check if this was the last job in the group
511
- val remainingInGroup = UIDTJobRegistry.activeJobs.values.count { it.groupId == groupId }
512
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Jobs remaining in group '$groupId' after error: $remainingInGroup")
513
-
514
- if (remainingInGroup == 0 && groupId.isNotEmpty()) {
515
- // Mark group as finalized FIRST to prevent race conditions
516
- UIDTJobRegistry.markGroupFinalized(groupId)
517
- // Last job in group - cancel summary notification
518
- UIDTNotificationManager.cancelSummaryNotification(this@UIDTDownloadJobService, groupId)
519
- } else {
520
- // Update summary notification for this group (update count/progress)
521
- UIDTNotificationManager.updateSummaryNotificationForGroup(this@UIDTDownloadJobService, groupId, groupName)
522
- }
523
-
524
- // Use setNotification with REMOVE policy to tell Android to remove the UIDT-controlled notification
525
- if (notificationId != null) {
526
- val emptyNotification = UIDTNotificationManager.createEmptyNotification(this@UIDTDownloadJobService)
527
- setNotification(params, notificationId, emptyNotification, JOB_END_NOTIFICATION_POLICY_REMOVE)
528
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Set REMOVE policy for notification $notificationId (error)")
529
- }
530
-
531
- // Signal job completion with no reschedule - this triggers the REMOVE policy
532
- jobFinished(params, false)
533
-
534
- // Clear persisted resume state - no longer needed after failure
535
- UIDTJobRegistry.clearResumeState(this@UIDTDownloadJobService, id)
536
- UIDTNotificationIds.release(id)
537
-
538
- // Notify external listener
539
- UIDTJobRegistry.downloadListener?.onError(id, error, errorCode)
540
- }
541
- }
542
- }
543
-
544
- // The download's recovery snapshot (saved while the app was running) gets its final size,
545
- // which recovery on the next launch takes as a finished download
546
- private fun recordFinishedWithoutApp(configId: String, bytesDownloaded: Long) {
547
- val storage = StorageManager(this, RNBackgroundDownloaderModuleImpl.NAME)
548
- val snapshot = storage.loadActiveDownloads()[configId] ?: return
549
- storage.saveActiveDownload(snapshot.copy(bytesDownloaded = bytesDownloaded, bytesTotal = bytesDownloaded))
550
- }
551
-
552
- private fun acquireWakeLock() {
553
- if (wakeLock == null) {
554
- val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
555
- wakeLock = powerManager.newWakeLock(
556
- PowerManager.PARTIAL_WAKE_LOCK,
557
- "UIDTDownloadJobService::WakeLock"
558
- ).apply {
559
- setReferenceCounted(false)
560
- acquire(DownloadConstants.WAKELOCK_TIMEOUT_MS)
561
- }
562
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "WakeLock acquired")
563
- }
564
- }
565
-
566
- private fun releaseWakeLock() {
567
- wakeLock?.let {
568
- if (it.isHeld) {
569
- it.release()
570
- RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "WakeLock released")
571
- }
572
- }
573
- wakeLock = null
574
- }
575
- }
13
+ class UIDTDownloadJobService : com.kesha_antonov.UIDTDownloadJobService()
@@ -1,66 +1,12 @@
1
1
  package com.eko.uidt
2
2
 
3
- import android.content.BroadcastReceiver
4
- import android.content.Context
5
- import android.content.Intent
6
3
  import android.os.Build
7
4
  import androidx.annotation.RequiresApi
8
- import com.eko.RNBackgroundDownloaderModuleImpl
9
5
 
10
6
  /**
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.
7
+ * The notification "Cancel" receiver under its name before v5.0.0. A progress
8
+ * notification posted by v4.x can still be in the shade after the app is
9
+ * updated, and its Cancel button targets this class.
22
10
  */
23
11
  @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
- // A job the system stopped (e.g. waiting for Wi-Fi) is no longer active but still
38
- // scheduled, and its notification with this action stays up - that counts too.
39
- val wasActive = UIDTJobRegistry.isActiveJob(configId) || UIDTJobManager.isScheduledJob(context, configId)
40
-
41
- if (!RNBackgroundDownloaderModuleImpl.stopTaskFromNative(configId)) {
42
- RNBackgroundDownloaderModuleImpl.logD(
43
- UIDTConstants.TAG,
44
- "CancelDownloadReceiver: module not initialized, cancelling job directly",
45
- )
46
- UIDTJobManager.cancelJob(context, configId)
47
- }
48
-
49
- // Only notify JS when a live job was actually cancelled. If the download
50
- // already finished there is nothing to clean up, and dispatching here
51
- // would emit a spurious downloadFailed for an already-completed task.
52
- if (wasActive) {
53
- // Notify JS so the in-memory task map can be cleaned and the
54
- // .error() handler runs (lib uses CANCELLED errorCode = -1).
55
- UIDTJobRegistry.downloadListener?.onError(configId, CANCELLED_MESSAGE, CANCELLED_ERROR_CODE)
56
- }
57
- }
58
-
59
- companion object {
60
- const val ACTION_CANCEL_DOWNLOAD = "com.eko.uidt.ACTION_CANCEL_DOWNLOAD"
61
- const val EXTRA_CONFIG_ID = "config_id"
62
-
63
- private const val CANCELLED_MESSAGE = "Download cancelled by user"
64
- private const val CANCELLED_ERROR_CODE = -1
65
- }
66
- }
12
+ class CancelDownloadReceiver : com.kesha_antonov.uidt.CancelDownloadReceiver()
@@ -1,4 +1,4 @@
1
- package com.eko
1
+ package com.kesha_antonov
2
2
 
3
3
  /**
4
4
  * Centralized constants for the download library.
@@ -1,4 +1,4 @@
1
- package com.eko
1
+ package com.kesha_antonov
2
2
 
3
3
  import com.facebook.react.bridge.Arguments
4
4
  import com.facebook.react.bridge.WritableMap
@@ -1,4 +1,4 @@
1
- package com.eko
1
+ package com.kesha_antonov
2
2
 
3
3
  /**
4
4
  * Sealed class representing the possible outcomes of a download operation.