@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.
Files changed (55) hide show
  1. package/README.md +95 -30
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +18 -2
  3. package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
  4. package/android/src/main/java/com/eko/Downloader.kt +37 -9
  5. package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
  6. package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +36 -1
  7. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +243 -117
  8. package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
  9. package/android/src/main/java/com/eko/ResumableDownloader.kt +109 -16
  10. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
  11. package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +134 -17
  12. package/android/src/main/java/com/eko/UploadEventEmitter.kt +26 -1
  13. package/android/src/main/java/com/eko/Uploader.kt +202 -28
  14. package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
  15. package/android/src/main/java/com/eko/handlers/OnProgress.kt +1 -1
  16. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
  17. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
  18. package/android/src/main/java/com/eko/utils/HeaderUtils.kt +9 -0
  19. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +32 -12
  20. package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
  21. package/android/src/test/java/com/eko/DownloadCompleteReceiverTest.kt +57 -0
  22. package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
  23. package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
  24. package/android/src/test/java/com/eko/ResumableDownloaderRedirectTest.kt +77 -0
  25. package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
  26. package/android/src/test/java/com/eko/UnmeteredNetworkGateTest.kt +248 -0
  27. package/android/src/test/java/com/eko/UploadPartRangesTest.kt +33 -0
  28. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +93 -0
  29. package/android/src/test/java/com/eko/UploaderPartsTest.kt +222 -0
  30. package/android/src/test/java/com/eko/UploaderResponseTest.kt +26 -0
  31. package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
  32. package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
  33. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +133 -0
  34. package/ios/RNBGDTaskConfig.h +2 -0
  35. package/ios/RNBGDTaskConfig.mm +6 -0
  36. package/ios/RNBGDUploadTaskConfig.h +26 -0
  37. package/ios/RNBGDUploadTaskConfig.mm +69 -3
  38. package/ios/RNBackgroundDownloader.mm +1203 -133
  39. package/lib/DownloadTask.d.ts +2 -0
  40. package/lib/DownloadTask.js +17 -1
  41. package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
  42. package/lib/UploadTask.d.ts +7 -1
  43. package/lib/UploadTask.js +38 -4
  44. package/lib/index.d.ts +1 -1
  45. package/lib/index.js +105 -61
  46. package/lib/types.d.ts +33 -2
  47. package/package.json +14 -11
  48. package/plugin/build/index.d.ts +1 -0
  49. package/plugin/build/index.js +18 -10
  50. package/react-native-background-downloader.podspec +8 -0
  51. package/src/DownloadTask.ts +18 -1
  52. package/src/NativeRNBackgroundDownloader.ts +23 -0
  53. package/src/UploadTask.ts +41 -2
  54. package/src/index.ts +131 -66
  55. package/src/types.ts +42 -2
@@ -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
+ }
@@ -0,0 +1,51 @@
1
+ package com.eko.handlers
2
+
3
+ import com.eko.RNBGDTaskConfig
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.Before
9
+ import org.junit.Test
10
+ import org.junit.runner.RunWith
11
+ import org.robolectric.RobolectricTestRunner
12
+ import org.robolectric.annotation.Config
13
+ import java.util.concurrent.TimeUnit
14
+
15
+ /**
16
+ * The HEAD request that reads the size goes to the same URL as the download, so a
17
+ * URL behind auth only answers it when it carries the download's headers.
18
+ */
19
+ @RunWith(RobolectricTestRunner::class)
20
+ @Config(sdk = [34])
21
+ class OnBeginTest {
22
+
23
+ private lateinit var server: MockWebServer
24
+
25
+ @Before
26
+ fun startServer() {
27
+ server = MockWebServer()
28
+ server.start()
29
+ }
30
+
31
+ @After
32
+ fun stopServer() {
33
+ server.shutdown()
34
+ }
35
+
36
+ @Test
37
+ fun `the HEAD request sends the download's headers`() {
38
+ server.enqueue(MockResponse().setHeader("Content-Length", "10"))
39
+ val config = RNBGDTaskConfig(id = "a", url = server.url("/file").toString(), destination = "/tmp/a")
40
+
41
+ // The response is turned into a React map, which needs the native React library;
42
+ // only the request matters here
43
+ runCatching {
44
+ OnBegin(config, { _, _, _ -> }, mapOf("Authorization" to "Bearer token")).call()
45
+ }
46
+
47
+ val request = server.takeRequest(5, TimeUnit.SECONDS)!!
48
+ assertEquals("HEAD", request.method)
49
+ assertEquals("Bearer token", request.getHeader("Authorization"))
50
+ }
51
+ }
@@ -0,0 +1,84 @@
1
+ package com.eko.uidt
2
+
3
+ import android.app.job.JobScheduler
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import androidx.test.core.app.ApplicationProvider
7
+ import com.eko.ResumableDownloader
8
+ import org.junit.After
9
+ import org.junit.Assert.assertEquals
10
+ import org.junit.Assert.assertTrue
11
+ import org.junit.Before
12
+ import org.junit.Test
13
+ import org.junit.runner.RunWith
14
+ import org.robolectric.RobolectricTestRunner
15
+ import org.robolectric.annotation.Config
16
+
17
+ /**
18
+ * Cancel on the notification has to tell JS about any download it stops. A job the
19
+ * system stopped (e.g. waiting for Wi-Fi) isn't running, but is still scheduled and
20
+ * still shows the notification.
21
+ */
22
+ @RunWith(RobolectricTestRunner::class)
23
+ @Config(sdk = [34])
24
+ class CancelDownloadReceiverTest {
25
+
26
+ private val context: Context get() = ApplicationProvider.getApplicationContext()
27
+ private val jobScheduler: JobScheduler
28
+ get() = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
29
+
30
+ private val errors = mutableListOf<Pair<String, Int>>()
31
+
32
+ @Before
33
+ fun setUp() {
34
+ jobScheduler.cancelAll()
35
+ UIDTJobRegistry.activeJobs.clear()
36
+ UIDTJobRegistry.downloadListener = object : ResumableDownloader.DownloadListener {
37
+ override fun onBegin(id: String, expectedBytes: Long, headers: Map<String, String>) = Unit
38
+ override fun onProgress(id: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
39
+ override fun onComplete(id: String, location: String, bytesDownloaded: Long, bytesTotal: Long) = Unit
40
+ override fun onError(id: String, error: String, errorCode: Int) {
41
+ errors.add(id to errorCode)
42
+ }
43
+ }
44
+ }
45
+
46
+ @After
47
+ fun tearDown() {
48
+ UIDTJobRegistry.downloadListener = null
49
+ }
50
+
51
+ private fun cancel(configId: String) {
52
+ CancelDownloadReceiver().onReceive(
53
+ context,
54
+ Intent(CancelDownloadReceiver.ACTION_CANCEL_DOWNLOAD)
55
+ .putExtra(CancelDownloadReceiver.EXTRA_CONFIG_ID, configId)
56
+ )
57
+ }
58
+
59
+ @Test
60
+ fun `cancelling a scheduled job that isn't running reports the cancel and removes the job`() {
61
+ assertTrue(
62
+ UIDTJobManager.scheduleDownload(
63
+ context = context,
64
+ configId = "waiting",
65
+ url = "https://example.com/file",
66
+ destination = "/tmp/waiting",
67
+ headers = emptyMap(),
68
+ isAllowedOverMetered = false
69
+ )
70
+ )
71
+
72
+ cancel("waiting")
73
+
74
+ assertEquals(listOf("waiting" to -1), errors)
75
+ assertTrue(jobScheduler.allPendingJobs.isEmpty())
76
+ }
77
+
78
+ @Test
79
+ fun `cancelling a download that already ended reports nothing`() {
80
+ cancel("finished")
81
+
82
+ assertTrue(errors.isEmpty())
83
+ }
84
+ }
@@ -0,0 +1,133 @@
1
+ package com.eko.utils
2
+
3
+ import okhttp3.mockwebserver.Dispatcher
4
+ import okhttp3.mockwebserver.MockResponse
5
+ import okhttp3.mockwebserver.MockWebServer
6
+ import okhttp3.mockwebserver.RecordedRequest
7
+ import org.junit.After
8
+ import com.facebook.react.bridge.JavaOnlyMap
9
+ import org.junit.Assert.assertEquals
10
+ import org.junit.Assert.assertFalse
11
+ import org.junit.Assert.assertTrue
12
+ import org.junit.Before
13
+ import org.junit.Test
14
+ import org.junit.runner.RunWith
15
+ import org.robolectric.RobolectricTestRunner
16
+ import org.robolectric.annotation.Config
17
+ import java.net.URL
18
+
19
+ /**
20
+ * A Location header may be relative. It has to be resolved against the URL that
21
+ * answered with it, keeping that URL's scheme, host, port and directory.
22
+ */
23
+ @RunWith(RobolectricTestRunner::class)
24
+ @Config(sdk = [34])
25
+ class RedirectResolverTest {
26
+
27
+ private lateinit var server: MockWebServer
28
+ private val redirects = mutableMapOf<String, String>()
29
+
30
+ @Before
31
+ fun startServer() {
32
+ server = MockWebServer()
33
+ server.dispatcher = object : Dispatcher() {
34
+ override fun dispatch(request: RecordedRequest): MockResponse {
35
+ val location = redirects[request.path]
36
+ ?: return MockResponse().setResponseCode(200)
37
+ return MockResponse().setResponseCode(302).setHeader("Location", location)
38
+ }
39
+ }
40
+ server.start()
41
+ }
42
+
43
+ @After
44
+ fun stopServer() {
45
+ server.shutdown()
46
+ }
47
+
48
+ private fun resolve(path: String) = RedirectResolver.resolve(server.url(path).toString(), 5, null)
49
+
50
+ @Test
51
+ fun `a relative location keeps the port and directory`() {
52
+ redirects["/files/start"] = "next/file.zip"
53
+
54
+ assertEquals(server.url("/files/next/file.zip").toString(), resolve("/files/start"))
55
+ }
56
+
57
+ @Test
58
+ fun `an absolute path keeps the port`() {
59
+ redirects["/files/start"] = "/other/file.zip"
60
+
61
+ assertEquals(server.url("/other/file.zip").toString(), resolve("/files/start"))
62
+ }
63
+
64
+ @Test
65
+ fun `a chain of relative redirects resolves each step against the previous one`() {
66
+ redirects["/a/start"] = "../b/step"
67
+ redirects["/b/step"] = "final.zip"
68
+
69
+ assertEquals(server.url("/b/final.zip").toString(), resolve("/a/start"))
70
+ }
71
+
72
+ // A second server is a different origin (another port)
73
+ private fun otherServer(): MockWebServer = MockWebServer().also {
74
+ it.dispatcher = object : Dispatcher() {
75
+ override fun dispatch(request: RecordedRequest) = MockResponse().setResponseCode(200)
76
+ }
77
+ it.start()
78
+ }
79
+
80
+ @Test
81
+ fun `stops before another origin while credentials are attached`() {
82
+ val other = otherServer()
83
+ try {
84
+ redirects["/start"] = other.url("/file.zip").toString()
85
+ val headers = JavaOnlyMap.of("Authorization", "Bearer secret")
86
+
87
+ val resolved = RedirectResolver.resolve(server.url("/start").toString(), 5, headers)
88
+
89
+ assertEquals(server.url("/start").toString(), resolved)
90
+ assertEquals(0, other.requestCount)
91
+ } finally {
92
+ other.shutdown()
93
+ }
94
+ }
95
+
96
+ @Test
97
+ fun `follows another origin when no credentials are attached`() {
98
+ val other = otherServer()
99
+ try {
100
+ redirects["/start"] = other.url("/file.zip").toString()
101
+ val headers = JavaOnlyMap.of("Accept", "*/*")
102
+
103
+ val resolved = RedirectResolver.resolve(server.url("/start").toString(), 5, headers)
104
+
105
+ assertEquals(other.url("/file.zip").toString(), resolved)
106
+ } finally {
107
+ other.shutdown()
108
+ }
109
+ }
110
+
111
+ @Test
112
+ fun `doesn't resolve to a non-http location`() {
113
+ redirects["/start"] = "ftp://example.com/file.zip"
114
+
115
+ // DownloadManager.Request throws on an ftp URL, which crashed the app
116
+ assertEquals(server.url("/start").toString(), resolve("/start"))
117
+ }
118
+
119
+ @Test
120
+ fun `refuses an https to http downgrade even on the same host`() {
121
+ assertFalse(RedirectResolver.isSafeHop(URL("https://a.example/x"), URL("http://a.example/y"), emptyMap()))
122
+ assertTrue(RedirectResolver.isSafeHop(URL("http://a.example/x"), URL("https://a.example/y"), emptyMap()))
123
+ }
124
+
125
+ @Test
126
+ fun `credential headers are matched case-insensitively`() {
127
+ val from = URL("https://a.example/x")
128
+ val to = URL("https://b.example/y")
129
+ assertFalse(RedirectResolver.isSafeHop(from, to, mapOf("cookie" to "s=1")))
130
+ assertFalse(RedirectResolver.isSafeHop(from, to, mapOf("PROXY-AUTHORIZATION" to "x")))
131
+ assertTrue(RedirectResolver.isSafeHop(from, URL("https://a.example:443/y"), mapOf("Authorization" to "x")))
132
+ }
133
+ }
@@ -17,6 +17,8 @@ NS_ASSUME_NONNULL_BEGIN
17
17
  // iOS Data Protection level key for the saved file
18
18
  // (e.g. NSFileProtectionCompleteUntilFirstUserAuthentication). nil = library default.
19
19
  @property (nonatomic, copy, nullable) NSString *dataProtection;
20
+ // Per-download cellular access (isAllowedOverMetered), kept so rebuilt requests honor it after a relaunch
21
+ @property (nonatomic, assign) BOOL allowsCellularAccess;
20
22
 
21
23
  - (instancetype)initWithDictionary:(NSDictionary *)dict;
22
24
 
@@ -23,6 +23,7 @@
23
23
  self.state = NSURLSessionTaskStateRunning;
24
24
  self.errorCode = 0;
25
25
  self.hasResumeData = NO;
26
+ self.allowsCellularAccess = YES;
26
27
  }
27
28
 
28
29
  return self;
@@ -41,6 +42,7 @@
41
42
  [aCoder encodeInteger:self.state forKey:@"state"];
42
43
  [aCoder encodeInteger:self.errorCode forKey:@"errorCode"];
43
44
  [aCoder encodeBool:self.hasResumeData forKey:@"hasResumeData"];
45
+ [aCoder encodeBool:self.allowsCellularAccess forKey:@"allowsCellularAccess"];
44
46
  }
45
47
 
46
48
  - (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder
@@ -61,6 +63,10 @@
61
63
  self.state = [aDecoder decodeIntegerForKey:@"state"];
62
64
  self.errorCode = [aDecoder decodeIntegerForKey:@"errorCode"];
63
65
  self.hasResumeData = [aDecoder decodeBoolForKey:@"hasResumeData"];
66
+ // Configs saved before this field existed had no per-download restriction
67
+ self.allowsCellularAccess = [aDecoder containsValueForKey:@"allowsCellularAccess"]
68
+ ? [aDecoder decodeBoolForKey:@"allowsCellularAccess"]
69
+ : YES;
64
70
  }
65
71
 
66
72
  return self;
@@ -20,8 +20,34 @@ NS_ASSUME_NONNULL_BEGIN
20
20
  // Stores the response body when upload completes
21
21
  @property (nonatomic, strong, nullable) NSMutableData *responseData;
22
22
 
23
+ // Upload source in parts, one URL per part (S3 multipart upload and similar)
24
+ @property (nonatomic, copy, nullable) NSArray<NSString *> *partUrls;
25
+ // Bytes per part; 0 means ceil(file size / number of parts)
26
+ @property (nonatomic, assign) long long partSize;
27
+ // Session task identifier -> 0-based part index, for the part tasks still running
28
+ @property (nonatomic, copy, nullable) NSDictionary<NSNumber *, NSNumber *> *partIndexByTask;
29
+ // 0-based part index -> result (partNumber, responseCode, responseBody, responseHeaders, bytes)
30
+ @property (nonatomic, copy, nullable) NSDictionary<NSNumber *, NSDictionary *> *partResults;
31
+
32
+ // The response of a finished upload, kept until JS has it
33
+ @property (nonatomic, assign) NSInteger responseCode;
34
+ @property (nonatomic, copy, nullable) NSString *responseBody;
35
+ @property (nonatomic, copy, nullable) NSDictionary<NSString *, NSString *> *responseHeaders;
36
+
23
37
  - (instancetype)initWithDictionary:(NSDictionary *)dict;
24
38
 
39
+ /**
40
+ * Byte ranges of the parts as [offset, length] pairs: every part `partSize` bytes
41
+ * (default ceil(fileSize / partCount)) and the last one what's left. Nil when the parts
42
+ * can't cover the file exactly, which includes an empty last part.
43
+ */
44
+ + (nullable NSArray<NSArray<NSNumber *> *> *)partRangesForFileSize:(long long)fileSize
45
+ partCount:(NSUInteger)partCount
46
+ partSize:(long long)partSize;
47
+
48
+ // Results of the accepted parts in part order, as sent to JS
49
+ - (NSArray<NSDictionary *> *)orderedPartResults;
50
+
25
51
  @end
26
52
 
27
53
  NS_ASSUME_NONNULL_END