@kesha-antonov/react-native-background-downloader 4.8.0 → 5.0.1
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 +12 -40
- package/android/build.gradle +5 -1
- package/android/consumer-rules.pro +14 -0
- package/android/src/main/AndroidManifest.xml +18 -1
- package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +5 -567
- package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +4 -58
- package/android/src/main/java/com/{eko → kesha_antonov}/DownloadConstants.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/DownloadEventEmitter.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/DownloadResult.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/Downloader.kt +2 -2
- package/android/src/main/java/com/{eko → kesha_antonov}/ProgressReporter.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/PromiseExtensions.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBGDTaskConfig.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBGDUploadTaskConfig.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModuleImpl.kt +9 -9
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderPackage.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloadService.kt +11 -9
- package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloader.kt +2 -2
- package/android/src/main/java/com/kesha_antonov/UIDTDownloadJobService.kt +590 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/UnmeteredNetworkGate.kt +2 -2
- package/android/src/main/java/com/{eko → kesha_antonov}/UploadEventEmitter.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/Uploader.kt +2 -2
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBegin.kt +4 -4
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBeginState.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgress.kt +4 -4
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgressState.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/BeginCallback.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/ProgressCallback.kt +1 -1
- package/android/src/main/java/com/kesha_antonov/uidt/CancelDownloadReceiver.kt +68 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/RNBGDFileProvider.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobIds.kt +9 -4
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobManager.kt +6 -6
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobState.kt +7 -5
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIds.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationManager.kt +18 -10
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/FileUtils.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/HeaderUtils.kt +2 -2
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/NetworkRequestUtils.kt +1 -1
- package/android/src/main/java/com/kesha_antonov/utils/NotificationUtils.kt +24 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/ProgressUtils.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/ReadableConverters.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/RedirectResolver.kt +3 -3
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/StorageManager.kt +5 -5
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/TempFileUtils.kt +2 -2
- package/android/src/newarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
- package/android/src/oldarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/DownloadCompleteReceiverTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderRecoveryTest.kt +2 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderResumeTest.kt +3 -3
- package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderConcurrencyTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderRedirectTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderStallTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/UnmeteredNetworkGateTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/UploadPartRangesTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/UploaderMultipartTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/UploaderPartsTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/UploaderResponseTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/handlers/OnBeginTest.kt +2 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/CancelDownloadReceiverTest.kt +25 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobIdsTest.kt +13 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobManagerTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIdsTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/utils/RedirectResolverTest.kt +1 -1
- package/bin/react-native-background-downloader.js +197 -0
- package/ios/RNBackgroundDownloader.mm +25 -5
- package/package.json +11 -5
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
package com.kesha_antonov
|
|
2
|
+
|
|
3
|
+
import android.app.job.JobParameters
|
|
4
|
+
import android.app.job.JobService
|
|
5
|
+
import android.content.Context
|
|
6
|
+
import android.os.Build
|
|
7
|
+
import android.os.PowerManager
|
|
8
|
+
import androidx.annotation.RequiresApi
|
|
9
|
+
import com.kesha_antonov.uidt.JobState
|
|
10
|
+
import com.kesha_antonov.uidt.NotificationGroupingMode
|
|
11
|
+
import com.kesha_antonov.uidt.UIDTConstants
|
|
12
|
+
import com.kesha_antonov.uidt.UIDTJobInfo
|
|
13
|
+
import com.kesha_antonov.uidt.UIDTJobManager
|
|
14
|
+
import com.kesha_antonov.uidt.UIDTJobRegistry
|
|
15
|
+
import com.kesha_antonov.uidt.UIDTNotificationIds
|
|
16
|
+
import com.kesha_antonov.uidt.UIDTNotificationManager
|
|
17
|
+
import com.kesha_antonov.utils.ProgressUtils
|
|
18
|
+
import com.kesha_antonov.utils.StorageManager
|
|
19
|
+
import org.json.JSONObject
|
|
20
|
+
import java.io.File
|
|
21
|
+
|
|
22
|
+
/**
|
|
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>
|
|
41
|
+
*/
|
|
42
|
+
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
|
|
43
|
+
open 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
|
+
/**
|
|
172
|
+
* How often a running download's byte position is written to disk. The
|
|
173
|
+
* process can be killed without onStopJob (an app update, low memory), and
|
|
174
|
+
* the restarted job resumes from the last saved position instead of byte 0.
|
|
175
|
+
*/
|
|
176
|
+
internal const val RESUME_SAVE_INTERVAL_MS = 5_000L
|
|
177
|
+
|
|
178
|
+
internal fun resumeStartByte(savedStartByte: Long, destination: String): Long =
|
|
179
|
+
if (savedStartByte > 0) File(destination).let { if (it.exists()) it.length() else 0L } else 0L
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private var wakeLock: PowerManager.WakeLock? = null
|
|
183
|
+
|
|
184
|
+
override fun onCreate() {
|
|
185
|
+
super.onCreate()
|
|
186
|
+
UIDTJobRegistry.serviceInstance = this
|
|
187
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDTDownloadJobService created")
|
|
188
|
+
UIDTNotificationManager.createNotificationChannels(this)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
override fun onDestroy() {
|
|
192
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDTDownloadJobService destroyed")
|
|
193
|
+
UIDTJobRegistry.serviceInstance = null
|
|
194
|
+
releaseWakeLock()
|
|
195
|
+
super.onDestroy()
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
override fun onStartJob(params: JobParameters): Boolean {
|
|
199
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob called")
|
|
200
|
+
|
|
201
|
+
val extras = params.extras
|
|
202
|
+
val configId = extras.getString(UIDTConstants.KEY_DOWNLOAD_ID) ?: run {
|
|
203
|
+
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "No download ID in job extras")
|
|
204
|
+
return false
|
|
205
|
+
}
|
|
206
|
+
val url = extras.getString(UIDTConstants.KEY_URL) ?: return false
|
|
207
|
+
val destination = extras.getString(UIDTConstants.KEY_DESTINATION) ?: return false
|
|
208
|
+
val startByteFromExtras = extras.getLong(UIDTConstants.KEY_START_BYTE, 0)
|
|
209
|
+
val totalBytes = extras.getLong(UIDTConstants.KEY_TOTAL_BYTES, -1)
|
|
210
|
+
val isAllowedOverMetered = extras.getBoolean(UIDTConstants.KEY_IS_ALLOWED_OVER_METERED, true)
|
|
211
|
+
|
|
212
|
+
// Extract group info from metadata (for notification grouping)
|
|
213
|
+
val metadataJson = extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
|
|
214
|
+
var groupId = ""
|
|
215
|
+
var groupName = ""
|
|
216
|
+
var customTitle = ""
|
|
217
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob: configId=$configId, metadataJson=$metadataJson")
|
|
218
|
+
try {
|
|
219
|
+
val json = JSONObject(metadataJson)
|
|
220
|
+
groupId = json.optString("groupId", "")
|
|
221
|
+
groupName = json.optString("groupName", "")
|
|
222
|
+
customTitle = json.optString("notificationTitle", "")
|
|
223
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Parsed metadata: groupId='$groupId', groupName='$groupName', customTitle='$customTitle'")
|
|
224
|
+
} catch (e: Exception) {
|
|
225
|
+
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "Failed to parse metadata: ${e.message}")
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Resolve headers and start byte.
|
|
229
|
+
// In-memory pendingHeaders is populated in the same process (scheduleDownload / onStopJob).
|
|
230
|
+
// The disk-persisted resume state is the fallback for a fresh process after a restart.
|
|
231
|
+
val inMemoryHeaders = UIDTJobRegistry.pendingHeaders.remove(configId)
|
|
232
|
+
// Kept on disk until the download completes, fails or is cancelled (those clear it):
|
|
233
|
+
// if the process dies mid-transfer, the restarted job still needs the headers
|
|
234
|
+
val diskResumeState = UIDTJobRegistry.loadResumeState(this, configId)
|
|
235
|
+
|
|
236
|
+
val headers: Map<String, String>
|
|
237
|
+
val savedStartByte: Long
|
|
238
|
+
when {
|
|
239
|
+
inMemoryHeaders != null -> {
|
|
240
|
+
// Same-process restart: use in-memory headers.
|
|
241
|
+
// Prefer the disk byte position if it is more advanced than the extras
|
|
242
|
+
// (written by onStopJob with the actual download offset).
|
|
243
|
+
headers = inMemoryHeaders
|
|
244
|
+
savedStartByte = if (diskResumeState != null && diskResumeState.second > startByteFromExtras)
|
|
245
|
+
diskResumeState.second else startByteFromExtras
|
|
246
|
+
}
|
|
247
|
+
diskResumeState != null -> {
|
|
248
|
+
// Cross-process restart: use the persisted state.
|
|
249
|
+
headers = diskResumeState.first
|
|
250
|
+
savedStartByte = diskResumeState.second
|
|
251
|
+
}
|
|
252
|
+
else -> {
|
|
253
|
+
headers = emptyMap()
|
|
254
|
+
savedStartByte = startByteFromExtras
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
val startByte = resumeStartByte(savedStartByte, destination)
|
|
258
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStartJob: configId=$configId, startByte=$startByte, headers=${headers.size}")
|
|
259
|
+
|
|
260
|
+
// Create notification for UIDT job (required)
|
|
261
|
+
val notificationId = UIDTNotificationManager.getNotificationIdForConfig(configId)
|
|
262
|
+
val notification = UIDTNotificationManager.createDownloadNotification(this, configId, groupId, groupName, customTitle)
|
|
263
|
+
|
|
264
|
+
// Set the notification for this job (required for UIDT)
|
|
265
|
+
setNotification(params, notificationId, notification, JOB_END_NOTIFICATION_POLICY_DETACH)
|
|
266
|
+
|
|
267
|
+
// Acquire wake lock
|
|
268
|
+
acquireWakeLock()
|
|
269
|
+
|
|
270
|
+
// Create ResumableDownloader for this job
|
|
271
|
+
val resumableDownloader = ResumableDownloader()
|
|
272
|
+
|
|
273
|
+
// Unmark group as finalized if it was previously (in case of new batch with same groupId)
|
|
274
|
+
if (groupId.isNotEmpty()) {
|
|
275
|
+
UIDTJobRegistry.unmarkGroupFinalized(groupId)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Store job state BEFORE updating summary (so count includes this job)
|
|
279
|
+
UIDTJobRegistry.activeJobs[configId] = JobState(params, resumableDownloader, notificationId, groupId, groupName, customTitle)
|
|
280
|
+
|
|
281
|
+
// Update summary notification if grouping enabled (now includes new job in count)
|
|
282
|
+
UIDTNotificationManager.updateSummaryNotificationForGroup(this, groupId, groupName)
|
|
283
|
+
|
|
284
|
+
// Create listener that will notify completion
|
|
285
|
+
val jobListener = createJobListener(configId, params, groupId, groupName, customTitle)
|
|
286
|
+
|
|
287
|
+
// Start the download asynchronously. The network constraint is enforced by
|
|
288
|
+
// the JobScheduler; the flag is passed so the DownloadState stays truthful
|
|
289
|
+
// (it is a fallback source for pause/snapshot persistence in the module).
|
|
290
|
+
// Bind the transfer to the network that satisfied the job's constraint -
|
|
291
|
+
// otherwise the sockets use the DEFAULT network, which can be metered
|
|
292
|
+
// cellular even while the satisfying unmetered network is connected.
|
|
293
|
+
resumableDownloader.startDownload(
|
|
294
|
+
id = configId,
|
|
295
|
+
url = url,
|
|
296
|
+
destination = destination,
|
|
297
|
+
headers = headers,
|
|
298
|
+
listener = jobListener,
|
|
299
|
+
startByte = startByte,
|
|
300
|
+
totalBytes = totalBytes,
|
|
301
|
+
isAllowedOverMetered = isAllowedOverMetered,
|
|
302
|
+
network = params.network
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Started UIDT download: $configId from byte $startByte")
|
|
306
|
+
|
|
307
|
+
// Return true - work is being done asynchronously
|
|
308
|
+
return true
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
override fun onStopJob(params: JobParameters): Boolean {
|
|
312
|
+
val extras = params.extras
|
|
313
|
+
val configId = extras.getString(UIDTConstants.KEY_DOWNLOAD_ID)
|
|
314
|
+
|
|
315
|
+
val stopReason = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
316
|
+
params.stopReason
|
|
317
|
+
} else {
|
|
318
|
+
-1
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStopJob called for $configId, reason: $stopReason")
|
|
322
|
+
|
|
323
|
+
if (configId != null) {
|
|
324
|
+
val jobState = UIDTJobRegistry.activeJobs[configId]
|
|
325
|
+
if (jobState != null) {
|
|
326
|
+
// Pause the download - it can be resumed later
|
|
327
|
+
jobState.resumableDownloader.pause(configId)
|
|
328
|
+
|
|
329
|
+
// Save state for potential resume
|
|
330
|
+
val state = jobState.resumableDownloader.getState(configId)
|
|
331
|
+
if (state != null) {
|
|
332
|
+
val bytesDownloaded = state.bytesDownloaded.get()
|
|
333
|
+
// Keep in-memory headers so the same-process reschedule works.
|
|
334
|
+
UIDTJobRegistry.pendingHeaders[configId] = state.headers
|
|
335
|
+
// Persist to disk so a fresh process can resume from the right position.
|
|
336
|
+
UIDTJobRegistry.saveResumeState(this, configId, state.headers, bytesDownloaded)
|
|
337
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onStopJob: saved resume state for $configId at $bytesDownloaded bytes")
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
UIDTJobRegistry.activeJobs.remove(configId)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
releaseWakeLock()
|
|
344
|
+
|
|
345
|
+
// Return true to reschedule the job if it was stopped by system
|
|
346
|
+
return true
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
private fun createJobListener(
|
|
350
|
+
configId: String,
|
|
351
|
+
params: JobParameters,
|
|
352
|
+
groupId: String,
|
|
353
|
+
groupName: String,
|
|
354
|
+
customTitle: String = ""
|
|
355
|
+
): ResumableDownloader.DownloadListener {
|
|
356
|
+
return object : ResumableDownloader.DownloadListener {
|
|
357
|
+
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) {
|
|
358
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDT download begin: $id, expectedBytes: $expectedBytes")
|
|
359
|
+
|
|
360
|
+
// Update notification with size info
|
|
361
|
+
val jobState = UIDTJobRegistry.activeJobs[id]
|
|
362
|
+
if (jobState != null) {
|
|
363
|
+
// Store total bytes for summary progress calculation
|
|
364
|
+
jobState.bytesTotal = expectedBytes
|
|
365
|
+
UIDTNotificationManager.updateProgressNotification(this@UIDTDownloadJobService, id, jobState, 0, expectedBytes)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Notify external listener
|
|
369
|
+
UIDTJobRegistry.downloadListener?.onBegin(id, expectedBytes, headers)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) {
|
|
373
|
+
val jobState = UIDTJobRegistry.activeJobs[id]
|
|
374
|
+
if (jobState != null) {
|
|
375
|
+
// Always update progress tracking in JobState for summary calculation
|
|
376
|
+
jobState.bytesDownloaded = bytesDownloaded
|
|
377
|
+
if (bytesTotal > 0) {
|
|
378
|
+
jobState.bytesTotal = bytesTotal
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
val now = System.currentTimeMillis()
|
|
382
|
+
if (bytesDownloaded > 0 && now - jobState.lastResumeSaveTime >= RESUME_SAVE_INTERVAL_MS) {
|
|
383
|
+
jobState.lastResumeSaveTime = now
|
|
384
|
+
jobState.resumableDownloader.getState(id)?.let { state ->
|
|
385
|
+
UIDTJobRegistry.saveResumeState(this@UIDTDownloadJobService, id, state.headers, bytesDownloaded)
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// Check if download is paused - don't update notification with progress
|
|
390
|
+
val isPaused = jobState.resumableDownloader.isPaused(id)
|
|
391
|
+
if (isPaused) {
|
|
392
|
+
// Still notify external listener for state tracking, but don't update notification
|
|
393
|
+
UIDTJobRegistry.downloadListener?.onProgress(id, bytesDownloaded, bytesTotal)
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
val config = UIDTJobRegistry.notificationConfig
|
|
398
|
+
val isSummaryOnlyMode = config.mode == NotificationGroupingMode.SUMMARY_ONLY
|
|
399
|
+
|
|
400
|
+
if (bytesTotal > 0) {
|
|
401
|
+
val progress = ProgressUtils.calculateProgress(bytesDownloaded, bytesTotal)
|
|
402
|
+
val currentTime = System.currentTimeMillis()
|
|
403
|
+
|
|
404
|
+
val shouldUpdate = ProgressUtils.shouldUpdateProgress(
|
|
405
|
+
progress,
|
|
406
|
+
jobState.lastNotifiedProgress,
|
|
407
|
+
currentTime,
|
|
408
|
+
jobState.lastNotificationUpdateTime,
|
|
409
|
+
config.updateInterval
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
if (shouldUpdate) {
|
|
413
|
+
jobState.lastNotifiedProgress = progress
|
|
414
|
+
jobState.lastNotificationUpdateTime = currentTime
|
|
415
|
+
|
|
416
|
+
if (isSummaryOnlyMode && config.groupingEnabled && jobState.groupId.isNotEmpty()) {
|
|
417
|
+
// In summaryOnly mode, update only the summary notification
|
|
418
|
+
UIDTNotificationManager.updateSummaryNotificationForGroup(
|
|
419
|
+
this@UIDTDownloadJobService, jobState.groupId, jobState.groupName
|
|
420
|
+
)
|
|
421
|
+
} else {
|
|
422
|
+
// Update individual notification
|
|
423
|
+
UIDTNotificationManager.updateProgressNotification(
|
|
424
|
+
this@UIDTDownloadJobService, id, jobState, bytesDownloaded, bytesTotal
|
|
425
|
+
)
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Notify external listener (always - JS handles its own throttling)
|
|
432
|
+
UIDTJobRegistry.downloadListener?.onProgress(id, bytesDownloaded, bytesTotal)
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) {
|
|
436
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "UIDT download complete: $id, groupId=$groupId")
|
|
437
|
+
|
|
438
|
+
val jobState = UIDTJobRegistry.activeJobs[id]
|
|
439
|
+
val notificationId = jobState?.notificationId
|
|
440
|
+
|
|
441
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "onComplete: notificationId=$notificationId, jobState groupId=${jobState?.groupId}")
|
|
442
|
+
|
|
443
|
+
// Resolve a display name for the completion notification.
|
|
444
|
+
// Prefer metadata.fileName (set from JS), fall back to the
|
|
445
|
+
// saved file's basename.
|
|
446
|
+
val displayName = try {
|
|
447
|
+
val metadataStr = params.extras.getString(UIDTConstants.KEY_METADATA) ?: "{}"
|
|
448
|
+
val metadata = JSONObject(metadataStr)
|
|
449
|
+
metadata.optString("fileName", "").ifEmpty { location.substringAfterLast('/') }
|
|
450
|
+
} catch (e: Exception) {
|
|
451
|
+
location.substringAfterLast('/')
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Post a standalone "download complete" notification BEFORE
|
|
455
|
+
// we tear down the UIDT-controlled one so it persists. Tap
|
|
456
|
+
// opens the saved file via FileProvider (system file viewer).
|
|
457
|
+
UIDTNotificationManager.showFinishedNotification(
|
|
458
|
+
this@UIDTDownloadJobService,
|
|
459
|
+
id,
|
|
460
|
+
location,
|
|
461
|
+
displayName,
|
|
462
|
+
jobState?.groupId ?: groupId,
|
|
463
|
+
jobState?.customTitle ?: customTitle,
|
|
464
|
+
)
|
|
465
|
+
|
|
466
|
+
// Clean up - remove from activeJobs first
|
|
467
|
+
UIDTJobRegistry.activeJobs.remove(id)
|
|
468
|
+
releaseWakeLock()
|
|
469
|
+
|
|
470
|
+
// Check if this was the last job in the group
|
|
471
|
+
val remainingInGroup = UIDTJobRegistry.activeJobs.values.count { it.groupId == groupId }
|
|
472
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Jobs remaining in group '$groupId': $remainingInGroup, activeJobs count=${UIDTJobRegistry.activeJobs.size}")
|
|
473
|
+
|
|
474
|
+
if (remainingInGroup == 0 && groupId.isNotEmpty()) {
|
|
475
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Last job in group completed. Marking finalized and cancelling summary.")
|
|
476
|
+
// Mark group as finalized FIRST to prevent race conditions
|
|
477
|
+
// where delayed progress callbacks might recreate the notification
|
|
478
|
+
UIDTJobRegistry.markGroupFinalized(groupId)
|
|
479
|
+
// Last job in group - cancel summary notification
|
|
480
|
+
UIDTNotificationManager.cancelSummaryNotification(this@UIDTDownloadJobService, groupId)
|
|
481
|
+
} else if (groupId.isEmpty()) {
|
|
482
|
+
RNBackgroundDownloaderModuleImpl.logW(UIDTConstants.TAG, "groupId is empty in onComplete for $id")
|
|
483
|
+
} else {
|
|
484
|
+
// Update summary notification for this group (update count/progress)
|
|
485
|
+
UIDTNotificationManager.updateSummaryNotificationForGroup(this@UIDTDownloadJobService, groupId, groupName)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Use setNotification with REMOVE policy to tell Android to remove the UIDT-controlled notification
|
|
489
|
+
// This is required because UIDT notifications are managed by the system, not NotificationManager
|
|
490
|
+
if (notificationId != null) {
|
|
491
|
+
val emptyNotification = UIDTNotificationManager.createEmptyNotification(this@UIDTDownloadJobService)
|
|
492
|
+
setNotification(params, notificationId, emptyNotification, JOB_END_NOTIFICATION_POLICY_REMOVE)
|
|
493
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Set REMOVE policy for notification $notificationId")
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// Signal job completion - this triggers the REMOVE policy
|
|
497
|
+
jobFinished(params, false)
|
|
498
|
+
|
|
499
|
+
// Clear persisted resume state - no longer needed after successful completion
|
|
500
|
+
UIDTJobRegistry.clearResumeState(this@UIDTDownloadJobService, id)
|
|
501
|
+
// The progress notification is gone; the completion one above already
|
|
502
|
+
// took its ID from this offset, so it can go back to the pool
|
|
503
|
+
UIDTNotificationIds.release(id)
|
|
504
|
+
|
|
505
|
+
// Notify external listener. With none (the job ran in a process without the
|
|
506
|
+
// app), record it so the next launch reports it as done, not as paused
|
|
507
|
+
val listener = UIDTJobRegistry.downloadListener
|
|
508
|
+
if (listener != null) {
|
|
509
|
+
listener.onComplete(id, location, bytesDownloaded, bytesTotal)
|
|
510
|
+
} else {
|
|
511
|
+
recordFinishedWithoutApp(id, bytesDownloaded)
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
override fun onError(id: String, error: String, errorCode: Int) {
|
|
516
|
+
RNBackgroundDownloaderModuleImpl.logE(UIDTConstants.TAG, "UIDT download error: $id - $error ($errorCode)")
|
|
517
|
+
|
|
518
|
+
val jobState = UIDTJobRegistry.activeJobs[id]
|
|
519
|
+
val notificationId = jobState?.notificationId
|
|
520
|
+
|
|
521
|
+
// Clean up - remove from activeJobs first
|
|
522
|
+
UIDTJobRegistry.activeJobs.remove(id)
|
|
523
|
+
releaseWakeLock()
|
|
524
|
+
|
|
525
|
+
// Check if this was the last job in the group
|
|
526
|
+
val remainingInGroup = UIDTJobRegistry.activeJobs.values.count { it.groupId == groupId }
|
|
527
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Jobs remaining in group '$groupId' after error: $remainingInGroup")
|
|
528
|
+
|
|
529
|
+
if (remainingInGroup == 0 && groupId.isNotEmpty()) {
|
|
530
|
+
// Mark group as finalized FIRST to prevent race conditions
|
|
531
|
+
UIDTJobRegistry.markGroupFinalized(groupId)
|
|
532
|
+
// Last job in group - cancel summary notification
|
|
533
|
+
UIDTNotificationManager.cancelSummaryNotification(this@UIDTDownloadJobService, groupId)
|
|
534
|
+
} else {
|
|
535
|
+
// Update summary notification for this group (update count/progress)
|
|
536
|
+
UIDTNotificationManager.updateSummaryNotificationForGroup(this@UIDTDownloadJobService, groupId, groupName)
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Use setNotification with REMOVE policy to tell Android to remove the UIDT-controlled notification
|
|
540
|
+
if (notificationId != null) {
|
|
541
|
+
val emptyNotification = UIDTNotificationManager.createEmptyNotification(this@UIDTDownloadJobService)
|
|
542
|
+
setNotification(params, notificationId, emptyNotification, JOB_END_NOTIFICATION_POLICY_REMOVE)
|
|
543
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Set REMOVE policy for notification $notificationId (error)")
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Signal job completion with no reschedule - this triggers the REMOVE policy
|
|
547
|
+
jobFinished(params, false)
|
|
548
|
+
|
|
549
|
+
// Clear persisted resume state - no longer needed after failure
|
|
550
|
+
UIDTJobRegistry.clearResumeState(this@UIDTDownloadJobService, id)
|
|
551
|
+
UIDTNotificationIds.release(id)
|
|
552
|
+
|
|
553
|
+
// Notify external listener
|
|
554
|
+
UIDTJobRegistry.downloadListener?.onError(id, error, errorCode)
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// The download's recovery snapshot (saved while the app was running) gets its final size,
|
|
560
|
+
// which recovery on the next launch takes as a finished download
|
|
561
|
+
private fun recordFinishedWithoutApp(configId: String, bytesDownloaded: Long) {
|
|
562
|
+
val storage = StorageManager(this, RNBackgroundDownloaderModuleImpl.NAME)
|
|
563
|
+
val snapshot = storage.loadActiveDownloads()[configId] ?: return
|
|
564
|
+
storage.saveActiveDownload(snapshot.copy(bytesDownloaded = bytesDownloaded, bytesTotal = bytesDownloaded))
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
private fun acquireWakeLock() {
|
|
568
|
+
if (wakeLock == null) {
|
|
569
|
+
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
|
|
570
|
+
wakeLock = powerManager.newWakeLock(
|
|
571
|
+
PowerManager.PARTIAL_WAKE_LOCK,
|
|
572
|
+
"UIDTDownloadJobService::WakeLock"
|
|
573
|
+
).apply {
|
|
574
|
+
setReferenceCounted(false)
|
|
575
|
+
acquire(DownloadConstants.WAKELOCK_TIMEOUT_MS)
|
|
576
|
+
}
|
|
577
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "WakeLock acquired")
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
private fun releaseWakeLock() {
|
|
582
|
+
wakeLock?.let {
|
|
583
|
+
if (it.isHeld) {
|
|
584
|
+
it.release()
|
|
585
|
+
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "WakeLock released")
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
wakeLock = null
|
|
589
|
+
}
|
|
590
|
+
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
package com.
|
|
1
|
+
package com.kesha_antonov
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
4
|
import android.net.ConnectivityManager
|
|
5
5
|
import android.net.Network
|
|
6
6
|
import android.net.NetworkCapabilities
|
|
7
|
-
import com.
|
|
7
|
+
import com.kesha_antonov.utils.NetworkRequestUtils
|
|
8
8
|
import java.util.concurrent.ExecutorService
|
|
9
9
|
import java.util.concurrent.Executors
|
|
10
10
|
import java.util.concurrent.RejectedExecutionException
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
package com.
|
|
1
|
+
package com.kesha_antonov
|
|
2
2
|
|
|
3
3
|
import android.content.Context
|
|
4
4
|
import android.util.Log
|
|
5
|
-
import com.
|
|
5
|
+
import com.kesha_antonov.utils.HeaderUtils
|
|
6
6
|
import java.io.BufferedReader
|
|
7
7
|
import java.io.DataOutputStream
|
|
8
8
|
import java.io.File
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
package com.
|
|
1
|
+
package com.kesha_antonov.handlers
|
|
2
2
|
|
|
3
|
-
import com.
|
|
4
|
-
import com.
|
|
5
|
-
import com.
|
|
3
|
+
import com.kesha_antonov.DownloadConstants
|
|
4
|
+
import com.kesha_antonov.RNBGDTaskConfig
|
|
5
|
+
import com.kesha_antonov.interfaces.BeginCallback
|
|
6
6
|
import com.facebook.react.bridge.Arguments
|
|
7
7
|
import com.facebook.react.bridge.WritableMap
|
|
8
8
|
import java.net.HttpURLConnection
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
package com.
|
|
1
|
+
package com.kesha_antonov.handlers
|
|
2
2
|
|
|
3
3
|
import android.app.DownloadManager
|
|
4
4
|
import android.database.Cursor
|
|
5
5
|
import android.os.SystemClock
|
|
6
|
-
import com.
|
|
7
|
-
import com.
|
|
8
|
-
import com.
|
|
6
|
+
import com.kesha_antonov.Downloader
|
|
7
|
+
import com.kesha_antonov.RNBGDTaskConfig
|
|
8
|
+
import com.kesha_antonov.interfaces.ProgressCallback
|
|
9
9
|
import java.util.concurrent.Callable
|
|
10
10
|
|
|
11
11
|
/**
|