@kesha-antonov/react-native-background-downloader 4.6.4 → 4.8.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 +95 -30
- package/android/src/main/java/com/eko/DownloadConstants.kt +18 -2
- package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
- package/android/src/main/java/com/eko/Downloader.kt +37 -9
- package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
- package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +36 -1
- package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +243 -117
- package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
- package/android/src/main/java/com/eko/ResumableDownloader.kt +109 -16
- package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
- package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +134 -17
- package/android/src/main/java/com/eko/UploadEventEmitter.kt +26 -1
- package/android/src/main/java/com/eko/Uploader.kt +202 -28
- package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
- package/android/src/main/java/com/eko/handlers/OnProgress.kt +1 -1
- package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
- package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
- package/android/src/main/java/com/eko/utils/HeaderUtils.kt +9 -0
- package/android/src/main/java/com/eko/utils/RedirectResolver.kt +32 -12
- package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
- package/android/src/test/java/com/eko/DownloadCompleteReceiverTest.kt +57 -0
- package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
- package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
- package/android/src/test/java/com/eko/ResumableDownloaderRedirectTest.kt +77 -0
- package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
- package/android/src/test/java/com/eko/UnmeteredNetworkGateTest.kt +248 -0
- package/android/src/test/java/com/eko/UploadPartRangesTest.kt +33 -0
- package/android/src/test/java/com/eko/UploaderMultipartTest.kt +93 -0
- package/android/src/test/java/com/eko/UploaderPartsTest.kt +222 -0
- package/android/src/test/java/com/eko/UploaderResponseTest.kt +26 -0
- package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
- package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
- package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +133 -0
- package/ios/RNBGDTaskConfig.h +2 -0
- package/ios/RNBGDTaskConfig.mm +6 -0
- package/ios/RNBGDUploadTaskConfig.h +26 -0
- package/ios/RNBGDUploadTaskConfig.mm +69 -3
- package/ios/RNBackgroundDownloader.mm +1203 -133
- package/lib/DownloadTask.d.ts +2 -0
- package/lib/DownloadTask.js +17 -1
- package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
- package/lib/UploadTask.d.ts +7 -1
- package/lib/UploadTask.js +38 -4
- package/lib/index.d.ts +1 -1
- package/lib/index.js +105 -61
- package/lib/types.d.ts +33 -2
- package/package.json +14 -11
- package/plugin/build/index.d.ts +1 -0
- package/plugin/build/index.js +18 -10
- package/react-native-background-downloader.podspec +8 -0
- package/src/DownloadTask.ts +18 -1
- package/src/NativeRNBackgroundDownloader.ts +23 -0
- package/src/UploadTask.ts +41 -2
- package/src/index.ts +131 -66
- package/src/types.ts +42 -2
|
@@ -44,7 +44,21 @@ class Uploader(private val context: Context) {
|
|
|
44
44
|
interface UploadListener {
|
|
45
45
|
fun onBegin(id: String, expectedBytes: Long)
|
|
46
46
|
fun onProgress(id: String, bytesUploaded: Long, bytesTotal: Long)
|
|
47
|
-
|
|
47
|
+
/** A part of an upload with partUrls was accepted (persist it, so a resume skips it). */
|
|
48
|
+
fun onPartComplete(id: String, part: UploadPartResult)
|
|
49
|
+
/**
|
|
50
|
+
* [responseCode], [responseBody] and [responseHeaders] are the last part's for an
|
|
51
|
+
* upload with partUrls; [parts] lists every part in order then.
|
|
52
|
+
*/
|
|
53
|
+
fun onComplete(
|
|
54
|
+
id: String,
|
|
55
|
+
responseCode: Int,
|
|
56
|
+
responseBody: String,
|
|
57
|
+
responseHeaders: Map<String, String>,
|
|
58
|
+
parts: List<UploadPartResult>?,
|
|
59
|
+
bytesUploaded: Long,
|
|
60
|
+
bytesTotal: Long
|
|
61
|
+
)
|
|
48
62
|
fun onError(id: String, error: String, errorCode: Int)
|
|
49
63
|
}
|
|
50
64
|
|
|
@@ -182,6 +196,11 @@ class Uploader(private val context: Context) {
|
|
|
182
196
|
return
|
|
183
197
|
}
|
|
184
198
|
|
|
199
|
+
if (config.partUrls != null) {
|
|
200
|
+
executePartUpload(state, listener)
|
|
201
|
+
return
|
|
202
|
+
}
|
|
203
|
+
|
|
185
204
|
val file = File(config.source)
|
|
186
205
|
val fileSize = file.length()
|
|
187
206
|
state.bytesTotal = fileSize
|
|
@@ -204,7 +223,8 @@ class Uploader(private val context: Context) {
|
|
|
204
223
|
// Apply custom headers
|
|
205
224
|
config.headers?.forEach { (key, value) ->
|
|
206
225
|
connection.setRequestProperty(key, value)
|
|
207
|
-
|
|
226
|
+
// Name only: values carry tokens, and apps forward logs to their services
|
|
227
|
+
RNBackgroundDownloaderModuleImpl.logD(TAG, "Set upload header: $key")
|
|
208
228
|
}
|
|
209
229
|
|
|
210
230
|
if (useMultipart) {
|
|
@@ -254,23 +274,13 @@ class Uploader(private val context: Context) {
|
|
|
254
274
|
|
|
255
275
|
// Get response
|
|
256
276
|
val responseCode = connection.responseCode
|
|
257
|
-
val responseBody =
|
|
258
|
-
val reader = BufferedReader(InputStreamReader(
|
|
259
|
-
if (responseCode in 200..299) connection.inputStream else connection.errorStream
|
|
260
|
-
))
|
|
261
|
-
val response = StringBuilder()
|
|
262
|
-
var line: String?
|
|
263
|
-
while (reader.readLine().also { line = it } != null) {
|
|
264
|
-
response.append(line)
|
|
265
|
-
}
|
|
266
|
-
reader.close()
|
|
267
|
-
response.toString()
|
|
268
|
-
} catch (e: Exception) {
|
|
269
|
-
""
|
|
270
|
-
}
|
|
277
|
+
val responseBody = readResponseBody(connection, responseCode)
|
|
271
278
|
|
|
272
279
|
if (responseCode in 200..299) {
|
|
273
|
-
listener.onComplete(
|
|
280
|
+
listener.onComplete(
|
|
281
|
+
config.id, responseCode, responseBody, lowercasedResponseHeaders(connection), null,
|
|
282
|
+
state.bytesUploaded.get(), state.bytesTotal
|
|
283
|
+
)
|
|
274
284
|
} else {
|
|
275
285
|
listener.onError(config.id, "HTTP error: $responseCode - $responseBody", responseCode)
|
|
276
286
|
}
|
|
@@ -302,6 +312,138 @@ class Uploader(private val context: Context) {
|
|
|
302
312
|
}
|
|
303
313
|
}
|
|
304
314
|
|
|
315
|
+
/**
|
|
316
|
+
* Upload the source in byte ranges, one request per part URL, in order. Parts the
|
|
317
|
+
* server already accepted (config.completedParts, kept across pause and restart) are
|
|
318
|
+
* skipped. Any part that isn't accepted fails the whole upload.
|
|
319
|
+
*/
|
|
320
|
+
private fun executePartUpload(state: UploadState, listener: UploadListener) {
|
|
321
|
+
val config = state.config
|
|
322
|
+
val partUrls = config.partUrls ?: return
|
|
323
|
+
val file = File(config.source)
|
|
324
|
+
val fileSize = file.length()
|
|
325
|
+
val ranges = uploadPartRanges(fileSize, partUrls.size, config.partSize)
|
|
326
|
+
if (ranges == null) {
|
|
327
|
+
val sizeNote = if (config.partSize > 0) " of ${config.partSize} bytes" else ""
|
|
328
|
+
listener.onError(state.id, "The file ($fileSize bytes) can't be split into ${partUrls.size} parts$sizeNote", -1)
|
|
329
|
+
activeUploads.remove(state.id)
|
|
330
|
+
return
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
val results = config.completedParts.orEmpty().toMutableList()
|
|
334
|
+
state.bytesTotal = fileSize
|
|
335
|
+
state.bytesUploaded.set(results.sumOf { it.bytes })
|
|
336
|
+
if (!state.hasReportedBegin) {
|
|
337
|
+
state.hasReportedBegin = true
|
|
338
|
+
listener.onBegin(state.id, fileSize)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
for ((index, range) in ranges.withIndex()) {
|
|
342
|
+
val partNumber = index + 1
|
|
343
|
+
if (results.any { it.partNumber == partNumber }) continue
|
|
344
|
+
if (state.isCancelled.get() || state.isPaused.get()) return
|
|
345
|
+
|
|
346
|
+
val part = uploadPart(state, listener, file, partUrls[index], partNumber, range) ?: return
|
|
347
|
+
if (part.responseCode !in 200..299) {
|
|
348
|
+
listener.onError(
|
|
349
|
+
state.id,
|
|
350
|
+
"Part $partNumber failed: HTTP ${part.responseCode} - ${part.responseBody}",
|
|
351
|
+
part.responseCode
|
|
352
|
+
)
|
|
353
|
+
activeUploads.remove(state.id)
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
results.add(part)
|
|
357
|
+
listener.onPartComplete(state.id, part)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
val parts = results.sortedBy { it.partNumber }
|
|
361
|
+
val last = parts.last()
|
|
362
|
+
listener.onComplete(
|
|
363
|
+
state.id, last.responseCode, last.responseBody, last.responseHeaders, parts,
|
|
364
|
+
state.bytesUploaded.get(), state.bytesTotal
|
|
365
|
+
)
|
|
366
|
+
activeUploads.remove(state.id)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Send one part as the raw body. Null when the upload was paused or cancelled meanwhile. */
|
|
370
|
+
private fun uploadPart(
|
|
371
|
+
state: UploadState,
|
|
372
|
+
listener: UploadListener,
|
|
373
|
+
file: File,
|
|
374
|
+
url: String,
|
|
375
|
+
partNumber: Int,
|
|
376
|
+
range: LongRange
|
|
377
|
+
): UploadPartResult? {
|
|
378
|
+
val config = state.config
|
|
379
|
+
val length = range.last - range.first + 1
|
|
380
|
+
val connection = URL(url).openConnection() as HttpURLConnection
|
|
381
|
+
state.connection = connection
|
|
382
|
+
try {
|
|
383
|
+
connection.requestMethod = config.method
|
|
384
|
+
connection.doOutput = true
|
|
385
|
+
connection.doInput = true
|
|
386
|
+
connection.useCaches = false
|
|
387
|
+
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
|
388
|
+
connection.readTimeout = READ_TIMEOUT_MS
|
|
389
|
+
config.headers?.forEach { (key, value) -> connection.setRequestProperty(key, value) }
|
|
390
|
+
connection.setRequestProperty("Content-Type", config.mimeType ?: "application/octet-stream")
|
|
391
|
+
connection.setFixedLengthStreamingMode(length)
|
|
392
|
+
RNBackgroundDownloaderModuleImpl.logD(TAG, "Uploading part $partNumber of ${config.id}: bytes ${range.first}-${range.last}")
|
|
393
|
+
|
|
394
|
+
// Partial progress of this part is dropped if it has to be sent again
|
|
395
|
+
val bytesBefore = state.bytesUploaded.get()
|
|
396
|
+
java.io.RandomAccessFile(file, "r").use { input ->
|
|
397
|
+
input.seek(range.first)
|
|
398
|
+
connection.outputStream.use { output ->
|
|
399
|
+
val buffer = ByteArray(BUFFER_SIZE)
|
|
400
|
+
var remaining = length
|
|
401
|
+
while (remaining > 0) {
|
|
402
|
+
if (state.isCancelled.get() || state.isPaused.get()) {
|
|
403
|
+
state.bytesUploaded.set(bytesBefore)
|
|
404
|
+
return null
|
|
405
|
+
}
|
|
406
|
+
val read = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
|
|
407
|
+
if (read == -1) throw java.io.EOFException("Source file shrank while uploading part $partNumber")
|
|
408
|
+
output.write(buffer, 0, read)
|
|
409
|
+
remaining -= read
|
|
410
|
+
listener.onProgress(state.id, state.bytesUploaded.addAndGet(read.toLong()), state.bytesTotal)
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (state.isCancelled.get() || state.isPaused.get()) {
|
|
415
|
+
state.bytesUploaded.set(bytesBefore)
|
|
416
|
+
return null
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
val responseCode = connection.responseCode
|
|
420
|
+
return UploadPartResult(
|
|
421
|
+
partNumber = partNumber,
|
|
422
|
+
responseCode = responseCode,
|
|
423
|
+
responseBody = readResponseBody(connection, responseCode),
|
|
424
|
+
responseHeaders = lowercasedResponseHeaders(connection),
|
|
425
|
+
bytes = length
|
|
426
|
+
)
|
|
427
|
+
} finally {
|
|
428
|
+
try {
|
|
429
|
+
connection.disconnect()
|
|
430
|
+
} catch (e: Exception) {
|
|
431
|
+
// Ignore
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
private fun readResponseBody(connection: HttpURLConnection, responseCode: Int): String = try {
|
|
437
|
+
val stream = if (responseCode in 200..299) connection.inputStream else connection.errorStream
|
|
438
|
+
stream?.let {
|
|
439
|
+
BufferedReader(InputStreamReader(it)).use { reader ->
|
|
440
|
+
readCapped(reader, DownloadConstants.MAX_UPLOAD_RESPONSE_CHARS)
|
|
441
|
+
}
|
|
442
|
+
} ?: ""
|
|
443
|
+
} catch (e: Exception) {
|
|
444
|
+
""
|
|
445
|
+
}
|
|
446
|
+
|
|
305
447
|
private fun calculateMultipartSize(config: RNBGDUploadTaskConfig, file: File, boundary: String): Long {
|
|
306
448
|
var size = 0L
|
|
307
449
|
val crlf = "\r\n"
|
|
@@ -312,20 +454,20 @@ class Uploader(private val context: Context) {
|
|
|
312
454
|
|
|
313
455
|
// Parameters
|
|
314
456
|
config.parameters?.forEach { (key, value) ->
|
|
315
|
-
size += "$twoHyphens$boundary$crlf".
|
|
316
|
-
size += "Content-Disposition: form-data; name=\"$key\"$crlf$crlf".
|
|
317
|
-
size += "$value$crlf".
|
|
457
|
+
size += "$twoHyphens$boundary$crlf".utf8Size()
|
|
458
|
+
size += "Content-Disposition: form-data; name=\"$key\"$crlf$crlf".utf8Size()
|
|
459
|
+
size += "$value$crlf".utf8Size()
|
|
318
460
|
}
|
|
319
461
|
|
|
320
462
|
// File
|
|
321
|
-
size += "$twoHyphens$boundary$crlf".
|
|
322
|
-
size += "Content-Disposition: form-data; name=\"$fieldName\"; filename=\"$fileName\"$crlf".
|
|
323
|
-
size += "Content-Type: $mimeType$crlf$crlf".
|
|
463
|
+
size += "$twoHyphens$boundary$crlf".utf8Size()
|
|
464
|
+
size += "Content-Disposition: form-data; name=\"$fieldName\"; filename=\"$fileName\"$crlf".utf8Size()
|
|
465
|
+
size += "Content-Type: $mimeType$crlf$crlf".utf8Size()
|
|
324
466
|
size += file.length()
|
|
325
467
|
size += crlf.length
|
|
326
468
|
|
|
327
469
|
// End boundary
|
|
328
|
-
size += "$twoHyphens$boundary$twoHyphens$crlf".
|
|
470
|
+
size += "$twoHyphens$boundary$twoHyphens$crlf".utf8Size()
|
|
329
471
|
|
|
330
472
|
return size
|
|
331
473
|
}
|
|
@@ -351,8 +493,8 @@ class Uploader(private val context: Context) {
|
|
|
351
493
|
val paramPart = "$twoHyphens$boundary$crlf" +
|
|
352
494
|
"Content-Disposition: form-data; name=\"$key\"$crlf$crlf" +
|
|
353
495
|
"$value$crlf"
|
|
354
|
-
outputStream.
|
|
355
|
-
val bytesWritten = state.bytesUploaded.addAndGet(paramPart.
|
|
496
|
+
outputStream.write(paramPart.toByteArray(Charsets.UTF_8))
|
|
497
|
+
val bytesWritten = state.bytesUploaded.addAndGet(paramPart.utf8Size().toLong())
|
|
356
498
|
listener.onProgress(config.id, bytesWritten, state.bytesTotal)
|
|
357
499
|
}
|
|
358
500
|
|
|
@@ -360,8 +502,8 @@ class Uploader(private val context: Context) {
|
|
|
360
502
|
val fileHeader = "$twoHyphens$boundary$crlf" +
|
|
361
503
|
"Content-Disposition: form-data; name=\"$fieldName\"; filename=\"$fileName\"$crlf" +
|
|
362
504
|
"Content-Type: $mimeType$crlf$crlf"
|
|
363
|
-
outputStream.
|
|
364
|
-
state.bytesUploaded.addAndGet(fileHeader.
|
|
505
|
+
outputStream.write(fileHeader.toByteArray(Charsets.UTF_8))
|
|
506
|
+
state.bytesUploaded.addAndGet(fileHeader.utf8Size().toLong())
|
|
365
507
|
|
|
366
508
|
// Write file content
|
|
367
509
|
FileInputStream(file).use { fileInputStream ->
|
|
@@ -407,3 +549,35 @@ class Uploader(private val context: Context) {
|
|
|
407
549
|
}
|
|
408
550
|
}
|
|
409
551
|
}
|
|
552
|
+
|
|
553
|
+
// Multipart text is sent as UTF-8 (DataOutputStream.writeBytes would keep only each
|
|
554
|
+
// char's low byte, garbling non-ASCII names and values), so sizes count UTF-8 bytes
|
|
555
|
+
private fun String.utf8Size(): Int = toByteArray(Charsets.UTF_8).size
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Read at most [maxChars] characters: the body goes to JS as one string, and an
|
|
559
|
+
* unbounded one from a hostile or broken server would run the app out of memory.
|
|
560
|
+
*/
|
|
561
|
+
internal fun readCapped(reader: java.io.Reader, maxChars: Int): String {
|
|
562
|
+
val response = StringBuilder()
|
|
563
|
+
val buffer = CharArray(8192)
|
|
564
|
+
while (response.length < maxChars) {
|
|
565
|
+
val read = reader.read(buffer, 0, minOf(buffer.size, maxChars - response.length))
|
|
566
|
+
if (read == -1) break
|
|
567
|
+
response.append(buffer, 0, read)
|
|
568
|
+
}
|
|
569
|
+
return response.toString()
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** Response headers with lowercased names; repeated headers are joined with ", ". */
|
|
573
|
+
internal fun lowercasedResponseHeaders(connection: HttpURLConnection): Map<String, String> {
|
|
574
|
+
val headers = mutableMapOf<String, String>()
|
|
575
|
+
for ((name, values) in connection.headerFields.orEmpty()) {
|
|
576
|
+
// The status line comes with a null name
|
|
577
|
+
if (name == null || values == null) continue
|
|
578
|
+
val key = name.lowercase()
|
|
579
|
+
val value = values.joinToString(", ")
|
|
580
|
+
headers[key] = headers[key]?.let { "$it, $value" } ?: value
|
|
581
|
+
}
|
|
582
|
+
return headers
|
|
583
|
+
}
|
|
@@ -16,7 +16,9 @@ import java.util.concurrent.Callable
|
|
|
16
16
|
*/
|
|
17
17
|
class OnBegin(
|
|
18
18
|
private val config: RNBGDTaskConfig,
|
|
19
|
-
private val callback: BeginCallback
|
|
19
|
+
private val callback: BeginCallback,
|
|
20
|
+
// The download's own headers, so auth-protected URLs answer the HEAD request too
|
|
21
|
+
private val requestHeaders: Map<String, String> = emptyMap()
|
|
20
22
|
) : Callable<OnBeginState> {
|
|
21
23
|
|
|
22
24
|
override fun call(): OnBeginState {
|
|
@@ -44,6 +46,9 @@ class OnBegin(
|
|
|
44
46
|
// Requests only headers from the server.
|
|
45
47
|
// Prevents memory leaks for invalid connections.
|
|
46
48
|
urlConnection.requestMethod = "HEAD"
|
|
49
|
+
for ((key, value) in requestHeaders) {
|
|
50
|
+
urlConnection.setRequestProperty(key, value)
|
|
51
|
+
}
|
|
47
52
|
|
|
48
53
|
// Set timeout values to prevent downloads from staying in PENDING state
|
|
49
54
|
// when URLs are slow to respond (e.g., taking 2-6 minutes)
|
|
@@ -90,7 +90,7 @@ class OnProgress(
|
|
|
90
90
|
} catch (e: Exception) {
|
|
91
91
|
stopLoopWithFail()
|
|
92
92
|
// if reached maximum memory while downloading, the downloader broadcast can not receive event normally
|
|
93
|
-
downloader.
|
|
93
|
+
downloader.reportDownloadEnded(downloadId)
|
|
94
94
|
throw e
|
|
95
95
|
}
|
|
96
96
|
|
|
@@ -34,7 +34,9 @@ class CancelDownloadReceiver : BroadcastReceiver() {
|
|
|
34
34
|
|
|
35
35
|
// Snapshot liveness first: stopTask tears the job down, so afterwards we
|
|
36
36
|
// can no longer tell an active download from an already-finished one.
|
|
37
|
-
|
|
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)
|
|
38
40
|
|
|
39
41
|
if (!RNBackgroundDownloaderModuleImpl.stopTaskFromNative(configId)) {
|
|
40
42
|
RNBackgroundDownloaderModuleImpl.logD(
|
|
@@ -375,14 +375,29 @@ object UIDTJobManager {
|
|
|
375
375
|
UIDTJobRegistry.clearResumeState(context, configId)
|
|
376
376
|
|
|
377
377
|
// Update summary notification if grouping was enabled
|
|
378
|
-
if (jobState != null && config.groupingEnabled
|
|
379
|
-
|
|
378
|
+
if (jobState != null && config.groupingEnabled) {
|
|
379
|
+
refreshGroupSummaryAfterJobLeft(context, jobState.groupId, jobState.groupName)
|
|
380
380
|
}
|
|
381
381
|
|
|
382
382
|
RNBackgroundDownloaderModuleImpl.logD(UIDTConstants.TAG, "Cancelled UIDT job for $configId")
|
|
383
383
|
return jobState != null
|
|
384
384
|
}
|
|
385
385
|
|
|
386
|
+
/**
|
|
387
|
+
* Update a group's summary notification after a job left it (cancelled or paused),
|
|
388
|
+
* mode-aware like the completion and error paths: remove it with the last job,
|
|
389
|
+
* otherwise refresh its count and progress. Nothing else would remove it.
|
|
390
|
+
*/
|
|
391
|
+
private fun refreshGroupSummaryAfterJobLeft(context: Context, groupId: String, groupName: String) {
|
|
392
|
+
if (groupId.isEmpty()) return
|
|
393
|
+
if (UIDTJobRegistry.activeJobs.values.none { it.groupId == groupId }) {
|
|
394
|
+
UIDTJobRegistry.markGroupFinalized(groupId)
|
|
395
|
+
UIDTNotificationManager.cancelSummaryNotification(context, groupId)
|
|
396
|
+
} else {
|
|
397
|
+
UIDTNotificationManager.updateSummaryNotificationForGroup(context, groupId, groupName)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
386
401
|
/**
|
|
387
402
|
* Pause an active UIDT download.
|
|
388
403
|
* This will pause the download, cancel the UIDT job, but keep a detached notification showing paused state.
|
|
@@ -416,6 +431,7 @@ object UIDTJobManager {
|
|
|
416
431
|
|
|
417
432
|
// Remove from activeJobs - will create new job on resume
|
|
418
433
|
UIDTJobRegistry.activeJobs.remove(configId)
|
|
434
|
+
refreshGroupSummaryAfterJobLeft(context, jobState.groupId, jobState.groupName)
|
|
419
435
|
|
|
420
436
|
// Show detached paused notification (not tied to UIDT job)
|
|
421
437
|
if (config.showNotificationsEnabled) {
|
|
@@ -10,6 +10,15 @@ import java.net.HttpURLConnection
|
|
|
10
10
|
*/
|
|
11
11
|
object HeaderUtils {
|
|
12
12
|
|
|
13
|
+
// Headers that carry credentials and must not be sent to another host
|
|
14
|
+
private val CREDENTIAL_HEADERS = setOf("authorization", "cookie", "proxy-authorization")
|
|
15
|
+
|
|
16
|
+
fun isCredentialHeader(name: String): Boolean = name.lowercase() in CREDENTIAL_HEADERS
|
|
17
|
+
|
|
18
|
+
/** The headers without Authorization, Cookie and Proxy-Authorization (case-insensitive). */
|
|
19
|
+
fun withoutCredentials(headers: Map<String, String>): Map<String, String> =
|
|
20
|
+
headers.filterKeys { !isCredentialHeader(it) }
|
|
21
|
+
|
|
13
22
|
/**
|
|
14
23
|
* Check if the provided headers already contain a User-Agent header (case-insensitive).
|
|
15
24
|
*/
|
|
@@ -55,20 +55,20 @@ object RedirectResolver {
|
|
|
55
55
|
break
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
//
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
else -> location
|
|
58
|
+
// Resolve relative locations against the current URL, keeping its port,
|
|
59
|
+
// path and scheme (for "//host/path")
|
|
60
|
+
val previousUrl = currentUrl
|
|
61
|
+
val nextUrl = URL(URL(currentUrl), location)
|
|
62
|
+
if (!isSafeHop(URL(currentUrl), nextUrl, headers)) {
|
|
63
|
+
// Leave this hop to the downloader: the platform's own redirect
|
|
64
|
+
// handling drops credentials across hosts and refuses downgrades
|
|
65
|
+
RNBackgroundDownloaderModuleImpl.logW(TAG, "Not following redirect from $previousUrl to $nextUrl")
|
|
66
|
+
connection.disconnect()
|
|
67
|
+
break
|
|
69
68
|
}
|
|
69
|
+
currentUrl = nextUrl.toString()
|
|
70
70
|
|
|
71
|
-
RNBackgroundDownloaderModuleImpl.logD(TAG, "Redirect ${redirectCount + 1}/$maxRedirects: $
|
|
71
|
+
RNBackgroundDownloaderModuleImpl.logD(TAG, "Redirect ${redirectCount + 1}/$maxRedirects: $previousUrl -> $currentUrl")
|
|
72
72
|
redirectCount++
|
|
73
73
|
} else {
|
|
74
74
|
// Not a redirect, we've found the final URL
|
|
@@ -94,4 +94,24 @@ object RedirectResolver {
|
|
|
94
94
|
return originalUrl
|
|
95
95
|
}
|
|
96
96
|
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Whether the resolver may probe [next] with the request's headers. Only http(s),
|
|
100
|
+
* never https -> http, and no other origin while credentials are attached -
|
|
101
|
+
* every probe resends all headers, and the resolved URL is downloaded with them.
|
|
102
|
+
*/
|
|
103
|
+
internal fun isSafeHop(current: URL, next: URL, headers: Map<String, String>): Boolean {
|
|
104
|
+
val scheme = next.protocol.lowercase()
|
|
105
|
+
if (scheme != "http" && scheme != "https") return false
|
|
106
|
+
if (current.protocol.equals("https", ignoreCase = true) && scheme == "http") return false
|
|
107
|
+
val sameOrigin = current.protocol.equals(next.protocol, ignoreCase = true) &&
|
|
108
|
+
current.host.equals(next.host, ignoreCase = true) &&
|
|
109
|
+
effectivePort(current) == effectivePort(next)
|
|
110
|
+
return sameOrigin || headers.keys.none { HeaderUtils.isCredentialHeader(it) }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private fun isSafeHop(current: URL, next: URL, headers: ReadableMap?): Boolean =
|
|
114
|
+
isSafeHop(current, next, HeaderUtils.toMap(headers))
|
|
115
|
+
|
|
116
|
+
private fun effectivePort(url: URL): Int = if (url.port != -1) url.port else url.defaultPort
|
|
97
117
|
}
|
|
@@ -352,6 +352,9 @@ class StorageManager(context: Context, private val name: String) {
|
|
|
352
352
|
/**
|
|
353
353
|
* Upsert a single in-progress resumable download recovery snapshot.
|
|
354
354
|
*/
|
|
355
|
+
// Synchronized: download threads save while others remove, and an unguarded
|
|
356
|
+
// load-modify-save can write back a snapshot another thread just removed
|
|
357
|
+
@Synchronized
|
|
355
358
|
fun saveActiveDownload(info: Downloader.PausedDownloadInfo) {
|
|
356
359
|
val map = loadActiveDownloads()
|
|
357
360
|
map[info.configId] = info
|
|
@@ -361,6 +364,7 @@ class StorageManager(context: Context, private val name: String) {
|
|
|
361
364
|
/**
|
|
362
365
|
* Remove a single recovery snapshot by config ID.
|
|
363
366
|
*/
|
|
367
|
+
@Synchronized
|
|
364
368
|
fun removeActiveDownload(configId: String) {
|
|
365
369
|
val map = loadActiveDownloads()
|
|
366
370
|
if (map.remove(configId) != null) {
|
|
@@ -371,6 +375,7 @@ class StorageManager(context: Context, private val name: String) {
|
|
|
371
375
|
/**
|
|
372
376
|
* Clear all recovery snapshots.
|
|
373
377
|
*/
|
|
378
|
+
@Synchronized
|
|
374
379
|
fun clearActiveDownloads() {
|
|
375
380
|
saveActiveDownloads(emptyMap())
|
|
376
381
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import android.app.Application
|
|
4
|
+
import android.app.DownloadManager
|
|
5
|
+
import androidx.test.core.app.ApplicationProvider
|
|
6
|
+
import com.facebook.react.bridge.BridgeReactContext
|
|
7
|
+
import org.junit.Assert.assertEquals
|
|
8
|
+
import org.junit.Assert.assertTrue
|
|
9
|
+
import org.junit.Test
|
|
10
|
+
import org.junit.runner.RunWith
|
|
11
|
+
import org.robolectric.RobolectricTestRunner
|
|
12
|
+
import org.robolectric.Shadows.shadowOf
|
|
13
|
+
import org.robolectric.annotation.Config
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The DOWNLOAD_COMPLETE receiver has to be exported for DownloadManager to reach it,
|
|
17
|
+
* and the action isn't protected on every Android version. Without a sender
|
|
18
|
+
* permission any app could send one and end (and remove) a running download.
|
|
19
|
+
*/
|
|
20
|
+
@RunWith(RobolectricTestRunner::class)
|
|
21
|
+
class DownloadCompleteReceiverTest {
|
|
22
|
+
|
|
23
|
+
private val app: Application get() = ApplicationProvider.getApplicationContext()
|
|
24
|
+
|
|
25
|
+
private fun registeredDownloadReceivers() = shadowOf(app).registeredReceivers.filter {
|
|
26
|
+
it.intentFilter.hasAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
private fun registerReceiver() {
|
|
30
|
+
val module = RNBackgroundDownloaderModuleImpl(BridgeReactContext(app))
|
|
31
|
+
RNBackgroundDownloaderModuleImpl::class.java.getDeclaredMethod("registerDownloadReceiver").apply {
|
|
32
|
+
isAccessible = true
|
|
33
|
+
invoke(module)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
@Test
|
|
38
|
+
@Config(sdk = [33])
|
|
39
|
+
fun `only DownloadProvider may send it before Android 14`() {
|
|
40
|
+
registerReceiver()
|
|
41
|
+
|
|
42
|
+
val receivers = registeredDownloadReceivers()
|
|
43
|
+
assertEquals(1, receivers.size)
|
|
44
|
+
assertEquals("android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", receivers[0].broadcastPermission)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
@Test
|
|
48
|
+
@Config(sdk = [34])
|
|
49
|
+
fun `only DownloadProvider may send it on Android 14+`() {
|
|
50
|
+
registerReceiver()
|
|
51
|
+
|
|
52
|
+
val receivers = registeredDownloadReceivers()
|
|
53
|
+
assertEquals(1, receivers.size)
|
|
54
|
+
assertEquals("android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS", receivers[0].broadcastPermission)
|
|
55
|
+
assertTrue(receivers[0].flags and android.content.Context.RECEIVER_EXPORTED != 0)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import androidx.test.core.app.ApplicationProvider
|
|
5
|
+
import com.eko.utils.StorageManager
|
|
6
|
+
import org.junit.Assert.assertEquals
|
|
7
|
+
import org.junit.Assert.assertTrue
|
|
8
|
+
import org.junit.Rule
|
|
9
|
+
import org.junit.Test
|
|
10
|
+
import org.junit.rules.TemporaryFolder
|
|
11
|
+
import org.junit.runner.RunWith
|
|
12
|
+
import org.robolectric.RobolectricTestRunner
|
|
13
|
+
import org.robolectric.annotation.Config
|
|
14
|
+
import java.util.UUID
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* On launch, downloads that were running when the app died are recovered from their
|
|
18
|
+
* snapshots. One whose file is complete finished without the app (an Android 14+ job
|
|
19
|
+
* records its final size then): it's done, not paused - resuming it would fail with 416.
|
|
20
|
+
*/
|
|
21
|
+
@RunWith(RobolectricTestRunner::class)
|
|
22
|
+
@Config(sdk = [34])
|
|
23
|
+
class DownloaderRecoveryTest {
|
|
24
|
+
|
|
25
|
+
@get:Rule
|
|
26
|
+
val tempFolder = TemporaryFolder()
|
|
27
|
+
|
|
28
|
+
private val context: Context get() = ApplicationProvider.getApplicationContext()
|
|
29
|
+
|
|
30
|
+
// A store of its own, so tests don't see each other's snapshots
|
|
31
|
+
private val storage = StorageManager(context, "recovery-${UUID.randomUUID()}")
|
|
32
|
+
|
|
33
|
+
private fun snapshot(configId: String, fileBytes: Int, bytesTotal: Long) {
|
|
34
|
+
val file = tempFolder.newFile(configId).apply { writeBytes(ByteArray(fileBytes)) }
|
|
35
|
+
storage.saveActiveDownload(
|
|
36
|
+
Downloader.PausedDownloadInfo(
|
|
37
|
+
configId = configId,
|
|
38
|
+
url = "https://example.com/$configId",
|
|
39
|
+
destination = file.absolutePath,
|
|
40
|
+
headers = emptyMap(),
|
|
41
|
+
bytesDownloaded = 0,
|
|
42
|
+
bytesTotal = bytesTotal
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
@Test
|
|
48
|
+
fun `a download whose file is complete is recovered as finished, once`() {
|
|
49
|
+
snapshot("complete", fileBytes = 100, bytesTotal = 100)
|
|
50
|
+
|
|
51
|
+
val downloader = Downloader(context, storage)
|
|
52
|
+
|
|
53
|
+
assertEquals(setOf("complete"), downloader.takeFinishedDownloads().keys)
|
|
54
|
+
assertTrue(downloader.getAllPausedDownloads().isEmpty())
|
|
55
|
+
assertTrue(downloader.takeFinishedDownloads().isEmpty())
|
|
56
|
+
assertTrue(storage.loadActiveDownloads().isEmpty())
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
@Test
|
|
60
|
+
fun `a download with part of its file is recovered as paused`() {
|
|
61
|
+
snapshot("partial", fileBytes = 40, bytesTotal = 100)
|
|
62
|
+
|
|
63
|
+
val downloader = Downloader(context, storage)
|
|
64
|
+
|
|
65
|
+
assertEquals(40L, downloader.getAllPausedDownloads()["partial"]?.bytesDownloaded)
|
|
66
|
+
assertTrue(downloader.takeFinishedDownloads().isEmpty())
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
@Test
|
|
70
|
+
fun `a download of unknown size is recovered as paused`() {
|
|
71
|
+
snapshot("unknown-size", fileBytes = 40, bytesTotal = -1)
|
|
72
|
+
|
|
73
|
+
val downloader = Downloader(context, storage)
|
|
74
|
+
|
|
75
|
+
assertTrue(downloader.getAllPausedDownloads().containsKey("unknown-size"))
|
|
76
|
+
assertTrue(downloader.takeFinishedDownloads().isEmpty())
|
|
77
|
+
}
|
|
78
|
+
}
|