@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
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import android.app.job.JobScheduler
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import androidx.test.core.app.ApplicationProvider
|
|
6
|
+
import com.eko.uidt.UIDTConstants
|
|
7
|
+
import com.eko.uidt.UIDTJobRegistry
|
|
8
|
+
import org.junit.Assert.assertEquals
|
|
9
|
+
import org.junit.Assert.assertTrue
|
|
10
|
+
import org.junit.Before
|
|
11
|
+
import org.junit.Rule
|
|
12
|
+
import org.junit.Test
|
|
13
|
+
import org.junit.rules.TemporaryFolder
|
|
14
|
+
import org.junit.runner.RunWith
|
|
15
|
+
import org.robolectric.RobolectricTestRunner
|
|
16
|
+
import org.robolectric.annotation.Config
|
|
17
|
+
import java.io.File
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A resumed download appends to the partial file, so it has to continue from the
|
|
21
|
+
* file's length. Continuing from a saved count that doesn't match it either keeps
|
|
22
|
+
* only the tail (no file) or duplicates bytes (the count lags the file).
|
|
23
|
+
*/
|
|
24
|
+
@RunWith(RobolectricTestRunner::class)
|
|
25
|
+
@Config(sdk = [34])
|
|
26
|
+
class DownloaderResumeTest {
|
|
27
|
+
|
|
28
|
+
@get:Rule
|
|
29
|
+
val tempFolder = TemporaryFolder()
|
|
30
|
+
|
|
31
|
+
private val context: Context get() = ApplicationProvider.getApplicationContext()
|
|
32
|
+
private val jobScheduler: JobScheduler
|
|
33
|
+
get() = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
|
|
34
|
+
|
|
35
|
+
private val listener = object : ResumableDownloader.DownloadListener {
|
|
36
|
+
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
|
|
37
|
+
override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
38
|
+
override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
39
|
+
override fun onError(id: String, error: String, errorCode: Int) = Unit
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
@Before
|
|
43
|
+
fun clearScheduler() {
|
|
44
|
+
jobScheduler.cancelAll()
|
|
45
|
+
UIDTJobRegistry.activeJobs.clear()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
private fun pauseAndResume(destination: File, bytesDownloaded: Long): Long {
|
|
49
|
+
val downloader = Downloader(context)
|
|
50
|
+
downloader.savePausedDownloadState(
|
|
51
|
+
Downloader.PausedDownloadInfo(
|
|
52
|
+
configId = "paused",
|
|
53
|
+
url = "https://example.com/file",
|
|
54
|
+
destination = destination.absolutePath,
|
|
55
|
+
headers = emptyMap(),
|
|
56
|
+
bytesDownloaded = bytesDownloaded,
|
|
57
|
+
bytesTotal = 1000,
|
|
58
|
+
metadata = "{}",
|
|
59
|
+
isAllowedOverMetered = true
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
assertTrue(downloader.resume("paused", listener))
|
|
63
|
+
return jobScheduler.allPendingJobs.single().extras.getLong(UIDTConstants.KEY_START_BYTE)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@Test
|
|
67
|
+
fun `a paused DownloadManager download whose file is gone starts over`() {
|
|
68
|
+
// Pausing a DownloadManager download removes it, and its partial file with it
|
|
69
|
+
assertEquals(0L, pauseAndResume(File(tempFolder.root, "removed.bin"), bytesDownloaded = 400))
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@Test
|
|
73
|
+
fun `a resume continues from the partial file, not a lagging saved count`() {
|
|
74
|
+
val partial = tempFolder.newFile("partial.bin").apply { writeBytes(ByteArray(600)) }
|
|
75
|
+
|
|
76
|
+
assertEquals(600L, pauseAndResume(partial, bytesDownloaded = 400))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
@Test
|
|
80
|
+
fun `a UIDT job continues from the partial file's length`() {
|
|
81
|
+
val partial = tempFolder.newFile("job.bin").apply { writeBytes(ByteArray(700)) }
|
|
82
|
+
|
|
83
|
+
assertEquals(700L, UIDTDownloadJobService.resumeStartByte(500, partial.absolutePath))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
@Test
|
|
87
|
+
fun `a UIDT job whose partial file is gone starts over`() {
|
|
88
|
+
assertEquals(0L, UIDTDownloadJobService.resumeStartByte(500, File(tempFolder.root, "gone.bin").absolutePath))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
@Test
|
|
92
|
+
fun `a UIDT job with nothing saved starts from zero even if a file is there`() {
|
|
93
|
+
val stale = tempFolder.newFile("stale.bin").apply { writeBytes(ByteArray(300)) }
|
|
94
|
+
|
|
95
|
+
assertEquals(0L, UIDTDownloadJobService.resumeStartByte(0, stale.absolutePath))
|
|
96
|
+
}
|
|
97
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import okhttp3.mockwebserver.MockResponse
|
|
4
|
+
import okhttp3.mockwebserver.MockWebServer
|
|
5
|
+
import org.junit.After
|
|
6
|
+
import org.junit.Assert.assertEquals
|
|
7
|
+
import org.junit.Assert.assertTrue
|
|
8
|
+
import org.junit.Before
|
|
9
|
+
import org.junit.Rule
|
|
10
|
+
import org.junit.Test
|
|
11
|
+
import org.junit.rules.TemporaryFolder
|
|
12
|
+
import org.junit.runner.RunWith
|
|
13
|
+
import org.robolectric.RobolectricTestRunner
|
|
14
|
+
import org.robolectric.annotation.Config
|
|
15
|
+
import java.io.File
|
|
16
|
+
import java.util.concurrent.CountDownLatch
|
|
17
|
+
import java.util.concurrent.TimeUnit
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* HttpURLConnection follows same-scheme redirects itself and refuses the others on
|
|
21
|
+
* purpose. The downloader may only add http -> https upgrades on top of that, so a
|
|
22
|
+
* redirect elsewhere is a plain HTTP error.
|
|
23
|
+
*/
|
|
24
|
+
@RunWith(RobolectricTestRunner::class)
|
|
25
|
+
@Config(sdk = [34])
|
|
26
|
+
class ResumableDownloaderRedirectTest {
|
|
27
|
+
|
|
28
|
+
@get:Rule
|
|
29
|
+
val tempFolder = TemporaryFolder()
|
|
30
|
+
|
|
31
|
+
private lateinit var server: MockWebServer
|
|
32
|
+
private val finished = CountDownLatch(1)
|
|
33
|
+
@Volatile private var errorCode: Int? = null
|
|
34
|
+
|
|
35
|
+
private val listener = object : ResumableDownloader.DownloadListener {
|
|
36
|
+
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
|
|
37
|
+
override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
38
|
+
override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) {
|
|
39
|
+
finished.countDown()
|
|
40
|
+
}
|
|
41
|
+
override fun onError(id: String, error: String, errorCode: Int) {
|
|
42
|
+
this@ResumableDownloaderRedirectTest.errorCode = errorCode
|
|
43
|
+
finished.countDown()
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
@Before
|
|
48
|
+
fun startServer() {
|
|
49
|
+
server = MockWebServer()
|
|
50
|
+
server.start()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
@After
|
|
54
|
+
fun stopServer() {
|
|
55
|
+
server.shutdown()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
@Test
|
|
59
|
+
fun `a redirect to a non-http scheme fails with the redirect status`() {
|
|
60
|
+
server.enqueue(MockResponse().setResponseCode(302).setHeader("Location", "ftp://example.com/file"))
|
|
61
|
+
|
|
62
|
+
ResumableDownloader().apply {
|
|
63
|
+
networkRetryDelaysMs = longArrayOf(10)
|
|
64
|
+
}.startDownload(
|
|
65
|
+
id = "ftp",
|
|
66
|
+
url = server.url("/file").toString(),
|
|
67
|
+
destination = File(tempFolder.root, "ftp").absolutePath,
|
|
68
|
+
headers = mapOf("Authorization" to "Bearer secret"),
|
|
69
|
+
listener = listener,
|
|
70
|
+
isAllowedOverMetered = true
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
assertTrue("the download didn't finish", finished.await(10, TimeUnit.SECONDS))
|
|
74
|
+
assertEquals(302, errorCode)
|
|
75
|
+
assertEquals(1, server.requestCount)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import okhttp3.mockwebserver.Dispatcher
|
|
4
|
+
import okhttp3.mockwebserver.MockResponse
|
|
5
|
+
import okhttp3.mockwebserver.MockWebServer
|
|
6
|
+
import okhttp3.mockwebserver.RecordedRequest
|
|
7
|
+
import okhttp3.mockwebserver.SocketPolicy
|
|
8
|
+
import org.junit.After
|
|
9
|
+
import org.junit.Assert.assertEquals
|
|
10
|
+
import org.junit.Assert.assertNull
|
|
11
|
+
import org.junit.Assert.assertTrue
|
|
12
|
+
import org.junit.Before
|
|
13
|
+
import org.junit.Rule
|
|
14
|
+
import org.junit.Test
|
|
15
|
+
import org.junit.rules.TemporaryFolder
|
|
16
|
+
import org.junit.runner.RunWith
|
|
17
|
+
import org.robolectric.RobolectricTestRunner
|
|
18
|
+
import org.robolectric.annotation.Config
|
|
19
|
+
import java.io.File
|
|
20
|
+
import java.util.concurrent.CopyOnWriteArrayList
|
|
21
|
+
import java.util.concurrent.CountDownLatch
|
|
22
|
+
import java.util.concurrent.TimeUnit
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A transfer the network cuts off (a stall that times out, a dropped connection) continues
|
|
26
|
+
* from the partial file with a Range request, as DownloadManager and iOS do. Only when the
|
|
27
|
+
* retries get nothing through does the app get an error.
|
|
28
|
+
*/
|
|
29
|
+
@RunWith(RobolectricTestRunner::class)
|
|
30
|
+
@Config(sdk = [34])
|
|
31
|
+
class ResumableDownloaderStallTest {
|
|
32
|
+
|
|
33
|
+
@get:Rule
|
|
34
|
+
val tempFolder = TemporaryFolder()
|
|
35
|
+
|
|
36
|
+
private lateinit var server: MockWebServer
|
|
37
|
+
private val ranges = CopyOnWriteArrayList<String?>()
|
|
38
|
+
|
|
39
|
+
private val body = ByteArray(200_000) { (it % 251).toByte() }
|
|
40
|
+
|
|
41
|
+
private val finished = CountDownLatch(1)
|
|
42
|
+
@Volatile private var errorCode: Int? = null
|
|
43
|
+
@Volatile private var completed = false
|
|
44
|
+
|
|
45
|
+
private val listener = object : ResumableDownloader.DownloadListener {
|
|
46
|
+
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
|
|
47
|
+
override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
48
|
+
override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) {
|
|
49
|
+
completed = true
|
|
50
|
+
finished.countDown()
|
|
51
|
+
}
|
|
52
|
+
override fun onError(id: String, error: String, errorCode: Int) {
|
|
53
|
+
this@ResumableDownloaderStallTest.errorCode = errorCode
|
|
54
|
+
finished.countDown()
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
@Before
|
|
59
|
+
fun startServer() {
|
|
60
|
+
server = MockWebServer()
|
|
61
|
+
server.start()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
@After
|
|
65
|
+
fun stopServer() {
|
|
66
|
+
server.shutdown()
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// The first request gets part of the body and then fails as `firstResponse` says;
|
|
70
|
+
// later ones get the rest, from their Range
|
|
71
|
+
private fun serve(firstResponse: MockResponse.() -> MockResponse) {
|
|
72
|
+
server.dispatcher = object : Dispatcher() {
|
|
73
|
+
override fun dispatch(request: RecordedRequest): MockResponse {
|
|
74
|
+
val range = request.getHeader("Range")
|
|
75
|
+
ranges.add(range)
|
|
76
|
+
if (range == null) {
|
|
77
|
+
return MockResponse()
|
|
78
|
+
.setHeader("Content-Length", body.size.toString())
|
|
79
|
+
.setHeader("Accept-Ranges", "bytes")
|
|
80
|
+
.setBody(okio.Buffer().write(body))
|
|
81
|
+
.firstResponse()
|
|
82
|
+
}
|
|
83
|
+
val start = range.removePrefix("bytes=").removeSuffix("-").toInt()
|
|
84
|
+
return MockResponse()
|
|
85
|
+
.setResponseCode(206)
|
|
86
|
+
.setHeader("Content-Length", (body.size - start).toString())
|
|
87
|
+
.setHeader("Content-Range", "bytes $start-${body.size - 1}/${body.size}")
|
|
88
|
+
.setBody(okio.Buffer().write(body, start, body.size - start))
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private fun download(id: String): File {
|
|
94
|
+
val destination = File(tempFolder.root, id)
|
|
95
|
+
ResumableDownloader().apply {
|
|
96
|
+
readTimeoutMs = 300
|
|
97
|
+
networkRetryDelaysMs = longArrayOf(10, 10, 10)
|
|
98
|
+
}.startDownload(
|
|
99
|
+
id = id,
|
|
100
|
+
url = server.url("/file").toString(),
|
|
101
|
+
destination = destination.absolutePath,
|
|
102
|
+
headers = emptyMap(),
|
|
103
|
+
listener = listener,
|
|
104
|
+
isAllowedOverMetered = true
|
|
105
|
+
)
|
|
106
|
+
assertTrue("the download didn't finish", finished.await(10, TimeUnit.SECONDS))
|
|
107
|
+
return destination
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
@Test
|
|
111
|
+
fun `a dropped connection continues from the partial file`() {
|
|
112
|
+
serve { setSocketPolicy(SocketPolicy.DISCONNECT_DURING_RESPONSE_BODY) }
|
|
113
|
+
|
|
114
|
+
val file = download("dropped")
|
|
115
|
+
|
|
116
|
+
assertNull(errorCode)
|
|
117
|
+
assertTrue(completed)
|
|
118
|
+
assertTrue(ranges.size >= 2)
|
|
119
|
+
assertTrue("the retry didn't continue from the partial file", ranges.last()!!.removePrefix("bytes=").removeSuffix("-").toInt() > 0)
|
|
120
|
+
assertTrue(file.readBytes().contentEquals(body))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
@Test
|
|
124
|
+
fun `a stalled transfer continues from the partial file`() {
|
|
125
|
+
// Some of the body, then nothing for longer than the read timeout
|
|
126
|
+
serve { throttleBody(50_000, 1, TimeUnit.SECONDS) }
|
|
127
|
+
|
|
128
|
+
val file = download("stalled")
|
|
129
|
+
|
|
130
|
+
assertNull(errorCode)
|
|
131
|
+
assertTrue(file.readBytes().contentEquals(body))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
@Test
|
|
135
|
+
fun `a transfer that keeps failing reports the timeout`() {
|
|
136
|
+
server.dispatcher = object : Dispatcher() {
|
|
137
|
+
override fun dispatch(request: RecordedRequest): MockResponse =
|
|
138
|
+
MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
download("unreachable")
|
|
142
|
+
|
|
143
|
+
assertEquals(DownloadConstants.ERR_TIMED_OUT, errorCode)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.net.ConnectivityManager
|
|
5
|
+
import android.net.Network
|
|
6
|
+
import android.net.NetworkCapabilities
|
|
7
|
+
import androidx.test.core.app.ApplicationProvider
|
|
8
|
+
import okhttp3.mockwebserver.Dispatcher
|
|
9
|
+
import okhttp3.mockwebserver.MockResponse
|
|
10
|
+
import okhttp3.mockwebserver.MockWebServer
|
|
11
|
+
import okhttp3.mockwebserver.RecordedRequest
|
|
12
|
+
import org.junit.After
|
|
13
|
+
import org.junit.Assert.assertEquals
|
|
14
|
+
import org.junit.Assert.assertNull
|
|
15
|
+
import org.junit.Before
|
|
16
|
+
import org.junit.Rule
|
|
17
|
+
import org.junit.Test
|
|
18
|
+
import org.junit.rules.TemporaryFolder
|
|
19
|
+
import org.junit.runner.RunWith
|
|
20
|
+
import org.robolectric.RobolectricTestRunner
|
|
21
|
+
import org.robolectric.Shadows.shadowOf
|
|
22
|
+
import org.robolectric.annotation.Config
|
|
23
|
+
import org.robolectric.shadows.ShadowNetwork
|
|
24
|
+
import org.robolectric.shadows.ShadowNetworkCapabilities
|
|
25
|
+
import java.util.concurrent.CountDownLatch
|
|
26
|
+
import java.util.concurrent.TimeUnit
|
|
27
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The unmetered gate binds transfers to a specific network. While a VPN is the
|
|
31
|
+
* app's default network, binding to the WiFi underneath it fails with EPERM, so
|
|
32
|
+
* the gate has to use the VPN itself (or wait when the VPN is metered).
|
|
33
|
+
*
|
|
34
|
+
* The tests drive the gate's network callbacks directly with the networks and
|
|
35
|
+
* capabilities ConnectivityService would report.
|
|
36
|
+
*/
|
|
37
|
+
@RunWith(RobolectricTestRunner::class)
|
|
38
|
+
@Config(sdk = [33])
|
|
39
|
+
class UnmeteredNetworkGateTest {
|
|
40
|
+
|
|
41
|
+
@get:Rule
|
|
42
|
+
val tempFolder = TemporaryFolder()
|
|
43
|
+
|
|
44
|
+
private val context: Context get() = ApplicationProvider.getApplicationContext()
|
|
45
|
+
private val connectivityManager: ConnectivityManager
|
|
46
|
+
get() = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
|
47
|
+
|
|
48
|
+
private val wifi = ShadowNetwork.newInstance(125)
|
|
49
|
+
private val vpn = ShadowNetwork.newInstance(126)
|
|
50
|
+
|
|
51
|
+
private lateinit var server: MockWebServer
|
|
52
|
+
private val holdResponses = CountDownLatch(1)
|
|
53
|
+
private lateinit var downloader: ResumableDownloader
|
|
54
|
+
private lateinit var gate: UnmeteredNetworkGate
|
|
55
|
+
private val gateStateChanges = AtomicInteger()
|
|
56
|
+
|
|
57
|
+
private val listener = object : ResumableDownloader.DownloadListener {
|
|
58
|
+
override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
|
|
59
|
+
override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
60
|
+
override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
|
|
61
|
+
override fun onError(id: String, error: String, errorCode: Int) = Unit
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
@Before
|
|
65
|
+
fun setUp() {
|
|
66
|
+
server = MockWebServer()
|
|
67
|
+
server.dispatcher = object : Dispatcher() {
|
|
68
|
+
override fun dispatch(request: RecordedRequest): MockResponse {
|
|
69
|
+
// Keep transfers in flight: only the gate's bookkeeping is under test
|
|
70
|
+
holdResponses.await(20, TimeUnit.SECONDS)
|
|
71
|
+
return MockResponse().setBody("payload")
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
server.start()
|
|
75
|
+
downloader = ResumableDownloader()
|
|
76
|
+
gate = UnmeteredNetworkGate(context, downloader, object : UnmeteredNetworkGate.Host {
|
|
77
|
+
override fun createGateListener(id: String) = listener
|
|
78
|
+
override fun onGatedTransferStarting() = Unit
|
|
79
|
+
override fun onGateStateChanged() {
|
|
80
|
+
gateStateChanges.incrementAndGet()
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
shadowOf(connectivityManager).setNetworkCapabilities(wifi, capabilities(unmetered = true))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
@After
|
|
87
|
+
fun tearDown() {
|
|
88
|
+
gate.shutdown()
|
|
89
|
+
downloader.getActiveDownloads().keys.forEach { downloader.cancel(it) }
|
|
90
|
+
holdResponses.countDown()
|
|
91
|
+
server.shutdown()
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
private fun capabilities(unmetered: Boolean, vpn: Boolean = false, downstreamKbps: Int = 0): NetworkCapabilities {
|
|
95
|
+
val capabilities = ShadowNetworkCapabilities.newInstance()
|
|
96
|
+
val shadow = shadowOf(capabilities)
|
|
97
|
+
shadow.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
98
|
+
if (unmetered) shadow.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
|
|
99
|
+
shadow.addTransportType(if (vpn) NetworkCapabilities.TRANSPORT_VPN else NetworkCapabilities.TRANSPORT_WIFI)
|
|
100
|
+
// Stands in for the signal-strength updates that change capabilities constantly
|
|
101
|
+
if (downstreamKbps > 0) shadow.setLinkDownstreamBandwidthKbps(downstreamKbps)
|
|
102
|
+
return capabilities
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private fun park(id: String) {
|
|
106
|
+
val parked = gate.parkNewDownload(id) {
|
|
107
|
+
downloader.prepareWaitingDownload(
|
|
108
|
+
id,
|
|
109
|
+
server.url("/$id").toString(),
|
|
110
|
+
tempFolder.root.resolve(id).absolutePath,
|
|
111
|
+
emptyMap()
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
assertEquals(true, parked)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private val unmeteredCallback: ConnectivityManager.NetworkCallback
|
|
118
|
+
get() = checkNotNull(gate.registeredCallbacks().first)
|
|
119
|
+
|
|
120
|
+
private val defaultCallback: ConnectivityManager.NetworkCallback
|
|
121
|
+
get() = checkNotNull(gate.registeredCallbacks().second)
|
|
122
|
+
|
|
123
|
+
private fun boundNetwork(id: String): Network? = downloader.getState(id)?.network
|
|
124
|
+
|
|
125
|
+
/** WiFi with the VPN on top, as delivered to an app the VPN applies to. */
|
|
126
|
+
private fun connectWifiAndVpn(vpnUnmetered: Boolean) {
|
|
127
|
+
// The default network callback is registered first, so its replay comes first.
|
|
128
|
+
// Both networks satisfy the unmetered request (it allows VPNs) when the VPN is
|
|
129
|
+
// unmetered; WiFi is reported before the VPN, which is what the gate used to bind to
|
|
130
|
+
defaultCallback.onCapabilitiesChanged(vpn, capabilities(unmetered = vpnUnmetered, vpn = true))
|
|
131
|
+
unmeteredCallback.onAvailable(wifi)
|
|
132
|
+
if (vpnUnmetered) unmeteredCallback.onAvailable(vpn)
|
|
133
|
+
gate.awaitCallbacks()
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
@Test
|
|
137
|
+
fun `moves off the WiFi when the VPN is reported after it`() {
|
|
138
|
+
park("a")
|
|
139
|
+
// The other order: WiFi shows up before the default network callback
|
|
140
|
+
// says the VPN is the default
|
|
141
|
+
unmeteredCallback.onAvailable(wifi)
|
|
142
|
+
unmeteredCallback.onAvailable(vpn)
|
|
143
|
+
defaultCallback.onCapabilitiesChanged(vpn, capabilities(unmetered = true, vpn = true))
|
|
144
|
+
gate.awaitCallbacks()
|
|
145
|
+
|
|
146
|
+
assertEquals(vpn, boundNetwork("a"))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
@Test
|
|
150
|
+
fun `binds to an unmetered VPN instead of the WiFi underneath it`() {
|
|
151
|
+
park("a")
|
|
152
|
+
connectWifiAndVpn(vpnUnmetered = true)
|
|
153
|
+
|
|
154
|
+
assertEquals(vpn, boundNetwork("a"))
|
|
155
|
+
assertEquals(emptySet<String>(), gate.waitingIds())
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
@Test
|
|
159
|
+
fun `waits while the default network is a metered VPN`() {
|
|
160
|
+
park("a")
|
|
161
|
+
connectWifiAndVpn(vpnUnmetered = false)
|
|
162
|
+
|
|
163
|
+
assertNull(boundNetwork("a"))
|
|
164
|
+
assertEquals(setOf("a"), gate.waitingIds())
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
@Test
|
|
168
|
+
fun `parking with the networks already known binds to the VPN`() {
|
|
169
|
+
park("first")
|
|
170
|
+
connectWifiAndVpn(vpnUnmetered = true)
|
|
171
|
+
|
|
172
|
+
park("second")
|
|
173
|
+
gate.awaitCallbacks()
|
|
174
|
+
|
|
175
|
+
assertEquals(vpn, boundNetwork("second"))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
@Test
|
|
179
|
+
fun `moves a running transfer onto a VPN that connects mid-download`() {
|
|
180
|
+
park("a")
|
|
181
|
+
unmeteredCallback.onAvailable(wifi)
|
|
182
|
+
defaultCallback.onCapabilitiesChanged(wifi, capabilities(unmetered = true))
|
|
183
|
+
gate.awaitCallbacks()
|
|
184
|
+
assertEquals(wifi, boundNetwork("a"))
|
|
185
|
+
|
|
186
|
+
unmeteredCallback.onAvailable(vpn)
|
|
187
|
+
defaultCallback.onCapabilitiesChanged(vpn, capabilities(unmetered = true, vpn = true))
|
|
188
|
+
gate.awaitCallbacks()
|
|
189
|
+
|
|
190
|
+
assertEquals(vpn, boundNetwork("a"))
|
|
191
|
+
assertEquals(emptySet<String>(), gate.waitingIds())
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
@Test
|
|
195
|
+
fun `parks a running transfer when a metered VPN connects mid-download`() {
|
|
196
|
+
park("a")
|
|
197
|
+
unmeteredCallback.onAvailable(wifi)
|
|
198
|
+
defaultCallback.onCapabilitiesChanged(wifi, capabilities(unmetered = true))
|
|
199
|
+
gate.awaitCallbacks()
|
|
200
|
+
assertEquals(wifi, boundNetwork("a"))
|
|
201
|
+
|
|
202
|
+
defaultCallback.onCapabilitiesChanged(vpn, capabilities(unmetered = false, vpn = true))
|
|
203
|
+
gate.awaitCallbacks()
|
|
204
|
+
|
|
205
|
+
assertNull(boundNetwork("a"))
|
|
206
|
+
assertEquals(setOf("a"), gate.waitingIds())
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
@Test
|
|
210
|
+
fun `a capability update that changes nothing the gate uses doesn't refresh the notification`() {
|
|
211
|
+
park("a")
|
|
212
|
+
unmeteredCallback.onAvailable(wifi)
|
|
213
|
+
defaultCallback.onCapabilitiesChanged(wifi, capabilities(unmetered = true))
|
|
214
|
+
gate.awaitCallbacks()
|
|
215
|
+
val before = gateStateChanges.get()
|
|
216
|
+
|
|
217
|
+
repeat(5) { i ->
|
|
218
|
+
defaultCallback.onCapabilitiesChanged(wifi, capabilities(unmetered = true, downstreamKbps = 1000 + i))
|
|
219
|
+
}
|
|
220
|
+
gate.awaitCallbacks()
|
|
221
|
+
|
|
222
|
+
assertEquals(before, gateStateChanges.get())
|
|
223
|
+
assertEquals(wifi, boundNetwork("a"))
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
@Test
|
|
227
|
+
fun `callbacks delivered after unregistering don't leak into the next registration`() {
|
|
228
|
+
park("a")
|
|
229
|
+
val staleUnmetered = unmeteredCallback
|
|
230
|
+
val staleDefault = defaultCallback
|
|
231
|
+
// Clearing the only download unregisters the callbacks
|
|
232
|
+
gate.clear("a")
|
|
233
|
+
assertNull(gate.registeredCallbacks().first)
|
|
234
|
+
|
|
235
|
+
// Events ConnectivityService had already queued for the old callbacks
|
|
236
|
+
staleUnmetered.onAvailable(wifi)
|
|
237
|
+
staleDefault.onCapabilitiesChanged(wifi, capabilities(unmetered = true))
|
|
238
|
+
gate.awaitCallbacks()
|
|
239
|
+
|
|
240
|
+
// A new download must wait for the new callbacks to report a network
|
|
241
|
+
// instead of starting on the stale one
|
|
242
|
+
park("b")
|
|
243
|
+
gate.awaitCallbacks()
|
|
244
|
+
|
|
245
|
+
assertNull(boundNetwork("b"))
|
|
246
|
+
assertEquals(setOf("b"), gate.waitingIds())
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import org.junit.Assert.assertEquals
|
|
4
|
+
import org.junit.Assert.assertNull
|
|
5
|
+
import org.junit.Test
|
|
6
|
+
|
|
7
|
+
class UploadPartRangesTest {
|
|
8
|
+
|
|
9
|
+
@Test
|
|
10
|
+
fun `defaults to ceil of size over count, the last part taking what's left`() {
|
|
11
|
+
assertEquals(listOf(0L until 4L, 4L until 8L, 8L until 10L), uploadPartRanges(10, 3, 0))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
@Test
|
|
15
|
+
fun `one part is the whole file`() {
|
|
16
|
+
assertEquals(listOf(0L until 10L), uploadPartRanges(10, 1, 0))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
@Test
|
|
20
|
+
fun `an explicit size must cover the file exactly`() {
|
|
21
|
+
assertEquals(listOf(0L until 5L, 5L until 7L), uploadPartRanges(7, 2, 5))
|
|
22
|
+
// Too small: the last part would be bigger than the part size
|
|
23
|
+
assertNull(uploadPartRanges(11, 2, 5))
|
|
24
|
+
// Too big: the last part would be empty
|
|
25
|
+
assertNull(uploadPartRanges(5, 2, 5))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
@Test
|
|
29
|
+
fun `no parts or an empty file`() {
|
|
30
|
+
assertNull(uploadPartRanges(10, 0, 0))
|
|
31
|
+
assertNull(uploadPartRanges(0, 2, 0))
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
package com.eko
|
|
2
|
+
|
|
3
|
+
import androidx.test.core.app.ApplicationProvider
|
|
4
|
+
import okhttp3.mockwebserver.MockResponse
|
|
5
|
+
import okhttp3.mockwebserver.MockWebServer
|
|
6
|
+
import org.junit.After
|
|
7
|
+
import org.junit.Assert.assertEquals
|
|
8
|
+
import org.junit.Assert.assertNull
|
|
9
|
+
import org.junit.Assert.assertTrue
|
|
10
|
+
import org.junit.Before
|
|
11
|
+
import org.junit.Rule
|
|
12
|
+
import org.junit.Test
|
|
13
|
+
import org.junit.rules.TemporaryFolder
|
|
14
|
+
import org.junit.runner.RunWith
|
|
15
|
+
import org.robolectric.RobolectricTestRunner
|
|
16
|
+
import org.robolectric.annotation.Config
|
|
17
|
+
import java.util.concurrent.CountDownLatch
|
|
18
|
+
import java.util.concurrent.TimeUnit
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The body is sent with a fixed Content-Length, so the length counted up front has to
|
|
22
|
+
* be the number of bytes written. Non-ASCII text is more than one byte per character.
|
|
23
|
+
*/
|
|
24
|
+
@RunWith(RobolectricTestRunner::class)
|
|
25
|
+
@Config(sdk = [34])
|
|
26
|
+
class UploaderMultipartTest {
|
|
27
|
+
|
|
28
|
+
@get:Rule
|
|
29
|
+
val tempFolder = TemporaryFolder()
|
|
30
|
+
|
|
31
|
+
private lateinit var server: MockWebServer
|
|
32
|
+
|
|
33
|
+
@Before
|
|
34
|
+
fun startServer() {
|
|
35
|
+
server = MockWebServer()
|
|
36
|
+
server.enqueue(MockResponse().setBody("ok"))
|
|
37
|
+
server.start()
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
@After
|
|
41
|
+
fun stopServer() {
|
|
42
|
+
server.shutdown()
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
@Test
|
|
46
|
+
fun `non-ASCII field values and file names are sent as UTF-8`() {
|
|
47
|
+
val file = tempFolder.newFile("отчёт.txt").apply { writeText("payload") }
|
|
48
|
+
val done = CountDownLatch(1)
|
|
49
|
+
var failedWith: String? = null
|
|
50
|
+
var completedWith = 0
|
|
51
|
+
|
|
52
|
+
Uploader(ApplicationProvider.getApplicationContext()).startUpload(
|
|
53
|
+
RNBGDUploadTaskConfig(
|
|
54
|
+
id = "upload",
|
|
55
|
+
url = server.url("/upload").toString(),
|
|
56
|
+
source = file.absolutePath,
|
|
57
|
+
fieldName = "file",
|
|
58
|
+
parameters = mapOf("title" to "Привет, 世界"),
|
|
59
|
+
),
|
|
60
|
+
object : Uploader.UploadListener {
|
|
61
|
+
override fun onBegin(id: String, expectedBytes: Long) = Unit
|
|
62
|
+
override fun onProgress(id: String, bytesUploaded: Long, bytesTotal: Long) = Unit
|
|
63
|
+
override fun onPartComplete(id: String, part: UploadPartResult) = Unit
|
|
64
|
+
override fun onComplete(
|
|
65
|
+
id: String,
|
|
66
|
+
responseCode: Int,
|
|
67
|
+
responseBody: String,
|
|
68
|
+
responseHeaders: Map<String, String>,
|
|
69
|
+
parts: List<UploadPartResult>?,
|
|
70
|
+
bytesUploaded: Long,
|
|
71
|
+
bytesTotal: Long
|
|
72
|
+
) {
|
|
73
|
+
completedWith = responseCode
|
|
74
|
+
done.countDown()
|
|
75
|
+
}
|
|
76
|
+
override fun onError(id: String, error: String, errorCode: Int) {
|
|
77
|
+
failedWith = error
|
|
78
|
+
done.countDown()
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
assertTrue(done.await(10, TimeUnit.SECONDS))
|
|
84
|
+
assertNull(failedWith)
|
|
85
|
+
assertEquals(200, completedWith)
|
|
86
|
+
|
|
87
|
+
val request = server.takeRequest(5, TimeUnit.SECONDS)!!
|
|
88
|
+
val body = request.body.readUtf8()
|
|
89
|
+
assertEquals(request.getHeader("Content-Length")!!.toLong(), request.bodySize)
|
|
90
|
+
assertTrue(body.contains("Привет, 世界"))
|
|
91
|
+
assertTrue(body.contains("filename=\"отчёт.txt\""))
|
|
92
|
+
}
|
|
93
|
+
}
|