@kesha-antonov/react-native-background-downloader 4.7.0 → 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.
Files changed (33) hide show
  1. package/README.md +75 -32
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +5 -0
  3. package/android/src/main/java/com/eko/Downloader.kt +12 -5
  4. package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +36 -1
  5. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +94 -54
  6. package/android/src/main/java/com/eko/ResumableDownloader.kt +34 -13
  7. package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +134 -17
  8. package/android/src/main/java/com/eko/UploadEventEmitter.kt +26 -1
  9. package/android/src/main/java/com/eko/Uploader.kt +187 -17
  10. package/android/src/main/java/com/eko/handlers/OnProgress.kt +1 -1
  11. package/android/src/main/java/com/eko/utils/HeaderUtils.kt +9 -0
  12. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +29 -1
  13. package/android/src/test/java/com/eko/DownloadCompleteReceiverTest.kt +57 -0
  14. package/android/src/test/java/com/eko/ResumableDownloaderRedirectTest.kt +77 -0
  15. package/android/src/test/java/com/eko/UnmeteredNetworkGateTest.kt +248 -0
  16. package/android/src/test/java/com/eko/UploadPartRangesTest.kt +33 -0
  17. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +10 -1
  18. package/android/src/test/java/com/eko/UploaderPartsTest.kt +222 -0
  19. package/android/src/test/java/com/eko/UploaderResponseTest.kt +26 -0
  20. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +66 -0
  21. package/ios/RNBGDUploadTaskConfig.h +26 -0
  22. package/ios/RNBGDUploadTaskConfig.mm +69 -3
  23. package/ios/RNBackgroundDownloader.mm +563 -43
  24. package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
  25. package/lib/UploadTask.d.ts +5 -1
  26. package/lib/UploadTask.js +22 -4
  27. package/lib/index.js +57 -27
  28. package/lib/types.d.ts +33 -2
  29. package/package.json +1 -1
  30. package/src/NativeRNBackgroundDownloader.ts +23 -0
  31. package/src/UploadTask.ts +23 -1
  32. package/src/index.ts +60 -27
  33. package/src/types.ts +42 -2
@@ -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,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
+ }
@@ -60,7 +60,16 @@ class UploaderMultipartTest {
60
60
  object : Uploader.UploadListener {
61
61
  override fun onBegin(id: String, expectedBytes: Long) = Unit
62
62
  override fun onProgress(id: String, bytesUploaded: Long, bytesTotal: Long) = Unit
63
- override fun onComplete(id: String, responseCode: Int, responseBody: String, bytesUploaded: Long, bytesTotal: Long) {
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
+ ) {
64
73
  completedWith = responseCode
65
74
  done.countDown()
66
75
  }
@@ -0,0 +1,222 @@
1
+ package com.eko
2
+
3
+ import androidx.test.core.app.ApplicationProvider
4
+ import okhttp3.mockwebserver.Dispatcher
5
+ import okhttp3.mockwebserver.MockResponse
6
+ import okhttp3.mockwebserver.MockWebServer
7
+ import okhttp3.mockwebserver.RecordedRequest
8
+ import org.junit.After
9
+ import org.junit.Assert.assertArrayEquals
10
+ import org.junit.Assert.assertEquals
11
+ import org.junit.Assert.assertNull
12
+ import org.junit.Assert.assertTrue
13
+ import org.junit.Before
14
+ import org.junit.Rule
15
+ import org.junit.Test
16
+ import org.junit.rules.TemporaryFolder
17
+ import org.junit.runner.RunWith
18
+ import org.robolectric.RobolectricTestRunner
19
+ import org.robolectric.annotation.Config
20
+ import java.io.File
21
+ import java.util.concurrent.ConcurrentHashMap
22
+ import java.util.concurrent.CopyOnWriteArrayList
23
+ import java.util.concurrent.CountDownLatch
24
+ import java.util.concurrent.TimeUnit
25
+
26
+ /**
27
+ * S3-style multipart upload: one file sent in byte ranges to one URL per part, with
28
+ * each part's ETag (a response header) reported back.
29
+ */
30
+ @RunWith(RobolectricTestRunner::class)
31
+ @Config(sdk = [34])
32
+ class UploaderPartsTest {
33
+
34
+ @get:Rule
35
+ val tempFolder = TemporaryFolder()
36
+
37
+ private lateinit var server: MockWebServer
38
+ // Body each part path received
39
+ private val received = ConcurrentHashMap<String, ByteArray>()
40
+ // Part paths that answer with this status instead of 200
41
+ private val failing = ConcurrentHashMap<String, Int>()
42
+
43
+ private val body = ByteArray(25_000) { (it % 251).toByte() }
44
+
45
+ private val finished = CountDownLatch(1)
46
+ @Volatile private var error: Pair<String, Int>? = null
47
+ @Volatile private var completion: Completion? = null
48
+ private val partEvents = CopyOnWriteArrayList<UploadPartResult>()
49
+ private val begins = CopyOnWriteArrayList<Long>()
50
+
51
+ data class Completion(
52
+ val responseCode: Int,
53
+ val responseHeaders: Map<String, String>,
54
+ val parts: List<UploadPartResult>?,
55
+ val bytesUploaded: Long,
56
+ val bytesTotal: Long
57
+ )
58
+
59
+ private val listener = object : Uploader.UploadListener {
60
+ override fun onBegin(id: String, expectedBytes: Long) {
61
+ begins.add(expectedBytes)
62
+ }
63
+ override fun onProgress(id: String, bytesUploaded: Long, bytesTotal: Long) = Unit
64
+ override fun onPartComplete(id: String, part: UploadPartResult) {
65
+ partEvents.add(part)
66
+ }
67
+ override fun onComplete(
68
+ id: String,
69
+ responseCode: Int,
70
+ responseBody: String,
71
+ responseHeaders: Map<String, String>,
72
+ parts: List<UploadPartResult>?,
73
+ bytesUploaded: Long,
74
+ bytesTotal: Long
75
+ ) {
76
+ completion = Completion(responseCode, responseHeaders, parts, bytesUploaded, bytesTotal)
77
+ finished.countDown()
78
+ }
79
+ override fun onError(id: String, error: String, errorCode: Int) {
80
+ this@UploaderPartsTest.error = error to errorCode
81
+ finished.countDown()
82
+ }
83
+ }
84
+
85
+ @Before
86
+ fun startServer() {
87
+ server = MockWebServer()
88
+ server.dispatcher = object : Dispatcher() {
89
+ override fun dispatch(request: RecordedRequest): MockResponse {
90
+ val path = request.path!!
91
+ received[path] = request.body.readByteArray()
92
+ failing[path]?.let { return MockResponse().setResponseCode(it).setBody("<Error>denied</Error>") }
93
+ // S3 answers UploadPart with an empty body and the part's ETag
94
+ return MockResponse().setHeader("ETag", "\"etag-$path\"")
95
+ }
96
+ }
97
+ server.start()
98
+ }
99
+
100
+ @After
101
+ fun stopServer() {
102
+ server.shutdown()
103
+ }
104
+
105
+ private fun source(): File = tempFolder.newFile("video.mp4").apply { writeBytes(body) }
106
+
107
+ private fun upload(config: RNBGDUploadTaskConfig) {
108
+ Uploader(ApplicationProvider.getApplicationContext()).startUpload(config, listener)
109
+ assertTrue("the upload didn't finish", finished.await(10, TimeUnit.SECONDS))
110
+ }
111
+
112
+ private fun config(file: File, parts: Int, partSize: Long = 0, completed: List<UploadPartResult>? = null) =
113
+ RNBGDUploadTaskConfig(
114
+ id = "upload",
115
+ url = server.url("/p1").toString(),
116
+ source = file.absolutePath,
117
+ method = "PUT",
118
+ partUrls = (1..parts).map { server.url("/p$it").toString() },
119
+ partSize = partSize,
120
+ completedParts = completed
121
+ )
122
+
123
+ @Test
124
+ fun `each part gets its byte range and reports its ETag`() {
125
+ upload(config(source(), parts = 3))
126
+
127
+ assertNull(error)
128
+ // ceil(25000 / 3) = 8334: two full parts and the remainder
129
+ assertArrayEquals(body.copyOfRange(0, 8334), received["/p1"])
130
+ assertArrayEquals(body.copyOfRange(8334, 16668), received["/p2"])
131
+ assertArrayEquals(body.copyOfRange(16668, 25000), received["/p3"])
132
+
133
+ val done = completion!!
134
+ assertEquals(listOf(1, 2, 3), done.parts!!.map { it.partNumber })
135
+ assertEquals(listOf(8334L, 8334L, 8332L), done.parts!!.map { it.bytes })
136
+ // Lowercased header names, as on iOS
137
+ assertEquals("\"etag-/p2\"", done.parts!![1].responseHeaders["etag"])
138
+ assertEquals("\"etag-/p3\"", done.responseHeaders["etag"])
139
+ assertEquals(25_000L, done.bytesUploaded)
140
+ assertEquals(25_000L, done.bytesTotal)
141
+ assertEquals(listOf(25_000L), begins)
142
+ assertEquals(3, partEvents.size)
143
+ }
144
+
145
+ @Test
146
+ fun `parts are sent with the given method and no multipart wrapping`() {
147
+ upload(config(source(), parts = 2))
148
+
149
+ val first = server.takeRequest()
150
+ assertEquals("PUT", first.method)
151
+ assertEquals("application/octet-stream", first.getHeader("Content-Type"))
152
+ assertEquals("12500", first.getHeader("Content-Length"))
153
+ }
154
+
155
+ @Test
156
+ fun `an explicit part size with a smaller last part`() {
157
+ upload(config(source(), parts = 3, partSize = 10_000))
158
+
159
+ assertNull(error)
160
+ assertEquals(listOf(10_000L, 10_000L, 5_000L), completion!!.parts!!.map { it.bytes })
161
+ assertArrayEquals(body.copyOfRange(20_000, 25_000), received["/p3"])
162
+ }
163
+
164
+ @Test
165
+ fun `a part size that doesn't cover the file fails before sending anything`() {
166
+ upload(config(source(), parts = 2, partSize = 10_000))
167
+
168
+ assertTrue(error!!.first.contains("can't be split into 2 parts of 10000 bytes"))
169
+ assertEquals(0, server.requestCount)
170
+ }
171
+
172
+ @Test
173
+ fun `more parts than the file can fill fail`() {
174
+ val file = tempFolder.newFile("tiny").apply { writeBytes(ByteArray(9)) }
175
+ // ceil(9 / 4) = 3 bytes each would leave the last part empty
176
+ upload(config(file, parts = 4))
177
+
178
+ assertTrue(error!!.first.contains("can't be split into 4 parts"))
179
+ assertEquals(0, server.requestCount)
180
+ }
181
+
182
+ @Test
183
+ fun `a rejected part fails the upload with its status and stops there`() {
184
+ failing["/p2"] = 403
185
+
186
+ upload(config(source(), parts = 3))
187
+
188
+ assertEquals(403, error!!.second)
189
+ assertTrue(error!!.first.contains("Part 2 failed: HTTP 403 - <Error>denied</Error>"))
190
+ assertEquals(setOf("/p1", "/p2"), received.keys)
191
+ assertNull(completion)
192
+ }
193
+
194
+ @Test
195
+ fun `a resumed upload skips the parts the server already accepted`() {
196
+ val accepted = UploadPartResult(1, 200, "", mapOf("etag" to "\"saved\""), 12_500)
197
+
198
+ upload(config(source(), parts = 2, completed = listOf(accepted)))
199
+
200
+ assertEquals(setOf("/p2"), received.keys)
201
+ val done = completion!!
202
+ assertEquals(listOf("\"saved\"", "\"etag-/p2\""), done.parts!!.map { it.responseHeaders["etag"] })
203
+ assertEquals(25_000L, done.bytesUploaded)
204
+ }
205
+
206
+ @Test
207
+ fun `a single upload reports its response headers too`() {
208
+ upload(
209
+ RNBGDUploadTaskConfig(
210
+ id = "upload",
211
+ url = server.url("/single").toString(),
212
+ source = source().absolutePath,
213
+ method = "PUT"
214
+ )
215
+ )
216
+
217
+ val done = completion!!
218
+ assertEquals("\"etag-/single\"", done.responseHeaders["etag"])
219
+ assertNull(done.parts)
220
+ assertArrayEquals(body, received["/single"])
221
+ }
222
+ }
@@ -0,0 +1,26 @@
1
+ package com.eko
2
+
3
+ import org.junit.Assert.assertEquals
4
+ import org.junit.Test
5
+ import java.io.StringReader
6
+
7
+ /** The upload response goes to JS as one string, so it is read up to a cap. */
8
+ class UploaderResponseTest {
9
+
10
+ @Test
11
+ fun `stops reading at the cap`() {
12
+ assertEquals("abcd", readCapped(StringReader("abcdefgh"), 4))
13
+ }
14
+
15
+ @Test
16
+ fun `keeps a body under the cap whole, line breaks included`() {
17
+ assertEquals("{\n \"ok\": true\n}\n", readCapped(StringReader("{\n \"ok\": true\n}\n"), 1024))
18
+ }
19
+
20
+ @Test
21
+ fun `reads past the internal buffer size`() {
22
+ val body = "x".repeat(20_000)
23
+ assertEquals(body, readCapped(StringReader(body), 1_000_000))
24
+ assertEquals(10_000, readCapped(StringReader(body), 10_000).length)
25
+ }
26
+ }