@kesha-antonov/react-native-background-downloader 4.7.0 → 5.0.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 (79) hide show
  1. package/README.md +85 -37
  2. package/android/build.gradle +5 -1
  3. package/android/consumer-rules.pro +14 -0
  4. package/android/src/main/AndroidManifest.xml +18 -1
  5. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +5 -567
  6. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +4 -58
  7. package/android/src/main/java/com/{eko → kesha_antonov}/DownloadConstants.kt +6 -1
  8. package/android/src/main/java/com/{eko → kesha_antonov}/DownloadEventEmitter.kt +1 -1
  9. package/android/src/main/java/com/{eko → kesha_antonov}/DownloadResult.kt +1 -1
  10. package/android/src/main/java/com/{eko → kesha_antonov}/Downloader.kt +14 -7
  11. package/android/src/main/java/com/{eko → kesha_antonov}/ProgressReporter.kt +1 -1
  12. package/android/src/main/java/com/{eko → kesha_antonov}/PromiseExtensions.kt +1 -1
  13. package/android/src/main/java/com/{eko → kesha_antonov}/RNBGDTaskConfig.kt +1 -1
  14. package/android/src/main/java/com/kesha_antonov/RNBGDUploadTaskConfig.kt +57 -0
  15. package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModuleImpl.kt +103 -63
  16. package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderPackage.kt +1 -1
  17. package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloadService.kt +11 -9
  18. package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloader.kt +36 -15
  19. package/android/src/main/java/com/kesha_antonov/UIDTDownloadJobService.kt +590 -0
  20. package/android/src/main/java/com/{eko → kesha_antonov}/UnmeteredNetworkGate.kt +136 -19
  21. package/android/src/main/java/com/{eko → kesha_antonov}/UploadEventEmitter.kt +27 -2
  22. package/android/src/main/java/com/{eko → kesha_antonov}/Uploader.kt +189 -19
  23. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBegin.kt +4 -4
  24. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBeginState.kt +1 -1
  25. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgress.kt +5 -5
  26. package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgressState.kt +1 -1
  27. package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/BeginCallback.kt +1 -1
  28. package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/ProgressCallback.kt +1 -1
  29. package/android/src/main/java/com/kesha_antonov/uidt/CancelDownloadReceiver.kt +68 -0
  30. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/RNBGDFileProvider.kt +1 -1
  31. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobIds.kt +9 -4
  32. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobManager.kt +6 -6
  33. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobState.kt +7 -5
  34. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIds.kt +1 -1
  35. package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationManager.kt +18 -10
  36. package/android/src/main/java/com/{eko → kesha_antonov}/utils/FileUtils.kt +1 -1
  37. package/android/src/main/java/com/{eko → kesha_antonov}/utils/HeaderUtils.kt +11 -2
  38. package/android/src/main/java/com/{eko → kesha_antonov}/utils/NetworkRequestUtils.kt +1 -1
  39. package/android/src/main/java/com/kesha_antonov/utils/NotificationUtils.kt +24 -0
  40. package/android/src/main/java/com/{eko → kesha_antonov}/utils/ProgressUtils.kt +1 -1
  41. package/android/src/main/java/com/{eko → kesha_antonov}/utils/ReadableConverters.kt +1 -1
  42. package/android/src/main/java/com/{eko → kesha_antonov}/utils/RedirectResolver.kt +32 -4
  43. package/android/src/main/java/com/{eko → kesha_antonov}/utils/StorageManager.kt +5 -5
  44. package/android/src/main/java/com/{eko → kesha_antonov}/utils/TempFileUtils.kt +2 -2
  45. package/android/src/newarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
  46. package/android/src/oldarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
  47. package/android/src/test/java/com/kesha_antonov/DownloadCompleteReceiverTest.kt +57 -0
  48. package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderRecoveryTest.kt +2 -2
  49. package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderResumeTest.kt +3 -3
  50. package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderConcurrencyTest.kt +1 -1
  51. package/android/src/test/java/com/kesha_antonov/ResumableDownloaderRedirectTest.kt +77 -0
  52. package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderStallTest.kt +1 -1
  53. package/android/src/test/java/com/kesha_antonov/UnmeteredNetworkGateTest.kt +248 -0
  54. package/android/src/test/java/com/kesha_antonov/UploadPartRangesTest.kt +33 -0
  55. package/android/src/test/java/com/{eko → kesha_antonov}/UploaderMultipartTest.kt +11 -2
  56. package/android/src/test/java/com/kesha_antonov/UploaderPartsTest.kt +222 -0
  57. package/android/src/test/java/com/kesha_antonov/UploaderResponseTest.kt +26 -0
  58. package/android/src/test/java/com/{eko → kesha_antonov}/handlers/OnBeginTest.kt +2 -2
  59. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/CancelDownloadReceiverTest.kt +25 -2
  60. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobIdsTest.kt +13 -2
  61. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobManagerTest.kt +1 -1
  62. package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIdsTest.kt +1 -1
  63. package/android/src/test/java/com/kesha_antonov/utils/RedirectResolverTest.kt +133 -0
  64. package/bin/react-native-background-downloader.js +197 -0
  65. package/ios/RNBGDUploadTaskConfig.h +26 -0
  66. package/ios/RNBGDUploadTaskConfig.mm +69 -3
  67. package/ios/RNBackgroundDownloader.mm +587 -47
  68. package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
  69. package/lib/UploadTask.d.ts +5 -1
  70. package/lib/UploadTask.js +22 -4
  71. package/lib/index.js +57 -27
  72. package/lib/types.d.ts +33 -2
  73. package/package.json +5 -2
  74. package/src/NativeRNBackgroundDownloader.ts +23 -0
  75. package/src/UploadTask.ts +23 -1
  76. package/src/index.ts +60 -27
  77. package/src/types.ts +42 -2
  78. package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +0 -22
  79. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +0 -67
@@ -0,0 +1,133 @@
1
+ package com.kesha_antonov.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
+ }
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ // Command line helper for @kesha-antonov/react-native-background-downloader.
5
+ //
6
+ // npx react-native-background-downloader migrate-package [dir] [--write]
7
+ //
8
+ // Finds references to the library's old Android package (com.eko) in an app
9
+ // and, with --write, changes them to com.kesha_antonov. Only the library's own
10
+ // class and package names are changed; anything else under com.eko is listed
11
+ // for review, since an app can have its own com.eko package.
12
+
13
+ const fs = require('fs')
14
+ const path = require('path')
15
+
16
+ const OLD_PACKAGE = 'com.eko'
17
+ const NEW_PACKAGE = 'com.kesha_antonov'
18
+
19
+ // Classes and subpackages of the library, as they appear after "com.eko."
20
+ const LIBRARY_NAMES = [
21
+ 'RNBackgroundDownloaderPackage',
22
+ 'RNBackgroundDownloaderModule',
23
+ 'RNBackgroundDownloaderModuleImpl',
24
+ 'RNBGDTaskConfig',
25
+ 'RNBGDUploadTaskConfig',
26
+ 'UploadPartResult',
27
+ 'DownloadConstants',
28
+ 'ResumableDownloadService',
29
+ 'UIDTDownloadJobService',
30
+ 'uidt',
31
+ 'utils',
32
+ 'handlers',
33
+ 'interfaces',
34
+ ]
35
+
36
+ const LIBRARY_REFERENCE = new RegExp(
37
+ `\\bcom\\.eko\\.(${LIBRARY_NAMES.join('|')})\\b`,
38
+ 'g'
39
+ )
40
+ const ANY_REFERENCE = /\bcom\.eko\b/
41
+
42
+ const SCANNED_EXTENSIONS = new Set([
43
+ '.java',
44
+ '.kt',
45
+ '.pro',
46
+ '.gradle',
47
+ '.kts',
48
+ '.xml',
49
+ ])
50
+ // Expo apps keep extra ProGuard rules in the app config (expo-build-properties)
51
+ const SCANNED_FILE_NAMES = new Set([
52
+ 'app.json',
53
+ 'app.config.js',
54
+ 'app.config.ts',
55
+ 'app.config.mjs',
56
+ 'app.config.cjs',
57
+ ])
58
+ const SKIPPED_DIRS = new Set([
59
+ 'node_modules',
60
+ '.git',
61
+ 'build',
62
+ '.gradle',
63
+ '.cxx',
64
+ 'Pods',
65
+ 'ios',
66
+ ])
67
+
68
+ /**
69
+ * Rewrite the library's com.eko references in one file's text.
70
+ * Returns the new text, the changed lines and the com.eko lines left as they are.
71
+ */
72
+ function migrateText (text) {
73
+ const changed = []
74
+ const unresolved = []
75
+ const lines = text.split('\n')
76
+ const newLines = lines.map((line, index) => {
77
+ const newLine = line.replace(
78
+ LIBRARY_REFERENCE,
79
+ (_match, name) => `${NEW_PACKAGE}.${name}`
80
+ )
81
+ if (newLine !== line)
82
+ changed.push({ line: index + 1, before: line, after: newLine })
83
+ if (ANY_REFERENCE.test(newLine))
84
+ unresolved.push({ line: index + 1, text: newLine })
85
+ return newLine
86
+ })
87
+ return { text: newLines.join('\n'), changed, unresolved }
88
+ }
89
+
90
+ function shouldScan (fileName) {
91
+ return (
92
+ SCANNED_FILE_NAMES.has(fileName) ||
93
+ SCANNED_EXTENSIONS.has(path.extname(fileName))
94
+ )
95
+ }
96
+
97
+ function listFiles (dir) {
98
+ const files = []
99
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }))
100
+ if (entry.isDirectory()) {
101
+ if (!SKIPPED_DIRS.has(entry.name))
102
+ files.push(...listFiles(path.join(dir, entry.name)))
103
+ } else if (entry.isFile() && shouldScan(entry.name)) {
104
+ files.push(path.join(dir, entry.name))
105
+ }
106
+
107
+ return files
108
+ }
109
+
110
+ /**
111
+ * Find (and with write: true, fix) com.eko references under dir.
112
+ */
113
+ function migratePackage (dir, { write = false } = {}) {
114
+ const results = []
115
+ for (const file of listFiles(dir)) {
116
+ const text = fs.readFileSync(file, 'utf8')
117
+ if (!text.includes(OLD_PACKAGE)) continue
118
+ const result = migrateText(text)
119
+ if (result.changed.length === 0 && result.unresolved.length === 0) continue
120
+ if (write && result.changed.length > 0)
121
+ fs.writeFileSync(file, result.text)
122
+ results.push({
123
+ file: path.relative(dir, file),
124
+ changed: result.changed,
125
+ unresolved: result.unresolved,
126
+ })
127
+ }
128
+ return results
129
+ }
130
+
131
+ function printUsage () {
132
+ console.log(`Usage: react-native-background-downloader migrate-package [dir] [--write]
133
+
134
+ Finds references to the old Android package com.eko in your app (Java, Kotlin,
135
+ Gradle, ProGuard and manifest files, and the Expo app config) and changes them
136
+ to com.kesha_antonov.
137
+
138
+ dir app root to scan, the current directory by default
139
+ --write change the files; without it nothing is written`)
140
+ }
141
+
142
+ function main (args) {
143
+ const [command, ...rest] = args
144
+ if (command !== 'migrate-package') {
145
+ printUsage()
146
+ return command === undefined || command === '--help' || command === '-h'
147
+ ? 0
148
+ : 1
149
+ }
150
+
151
+ const write = rest.includes('--write')
152
+ const dir = path.resolve(rest.find((arg) => !arg.startsWith('--')) || '.')
153
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
154
+ console.error(`Not a directory: ${dir}`)
155
+ return 1
156
+ }
157
+
158
+ const results = migratePackage(dir, { write })
159
+ if (results.length === 0) {
160
+ console.log(`No references to ${OLD_PACKAGE} found in ${dir}.`)
161
+ return 0
162
+ }
163
+
164
+ let changeCount = 0
165
+ let unresolvedCount = 0
166
+ for (const { file, changed, unresolved } of results) {
167
+ console.log(`\n${file}`)
168
+ for (const change of changed) {
169
+ console.log(` ${change.line}: ${change.before.trim()}`)
170
+ console.log(` ${' '.repeat(String(change.line).length)} ${change.after.trim()}`)
171
+ }
172
+ for (const line of unresolved)
173
+ console.log(` ${line.line}: ${line.text.trim()} (check by hand)`)
174
+ changeCount += changed.length
175
+ unresolvedCount += unresolved.length
176
+ }
177
+
178
+ console.log('')
179
+ if (changeCount > 0)
180
+ console.log(
181
+ write
182
+ ? `Changed ${changeCount} line(s).`
183
+ : `${changeCount} line(s) to change. Run again with --write to apply.`
184
+ )
185
+
186
+ if (unresolvedCount > 0)
187
+ console.log(
188
+ `${unresolvedCount} line(s) mention ${OLD_PACKAGE} but not a class of this library; check them by hand.`
189
+ )
190
+
191
+ return 0
192
+ }
193
+
194
+ module.exports = { migrateText, migratePackage, main }
195
+
196
+ if (require.main === module)
197
+ process.exitCode = main(process.argv.slice(2))
@@ -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
@@ -7,6 +7,24 @@
7
7
  return YES;
8
8
  }
9
9
 
10
+ static NSString *_Nullable RNBGDStringOrNil(id value)
11
+ {
12
+ if ([value isKindOfClass:[NSString class]]) return value;
13
+ if (value == nil || value == [NSNull null]) return nil;
14
+ return [value description];
15
+ }
16
+
17
+ static NSDictionary<NSString *, NSString *> *_Nullable RNBGDStringParameters(id value)
18
+ {
19
+ if (![value isKindOfClass:[NSDictionary class]]) return nil;
20
+ NSMutableDictionary<NSString *, NSString *> *parameters = [NSMutableDictionary dictionary];
21
+ [(NSDictionary *)value enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
22
+ NSString *string = RNBGDStringOrNil(obj);
23
+ if ([key isKindOfClass:[NSString class]] && string != nil) parameters[key] = string;
24
+ }];
25
+ return parameters;
26
+ }
27
+
10
28
  - (instancetype)initWithDictionary:(NSDictionary *)dict
11
29
  {
12
30
  self = [super init];
@@ -17,9 +35,14 @@
17
35
  self.source = dict[@"source"];
18
36
  self.method = dict[@"method"] ?: @"POST";
19
37
  self.metadata = dict[@"metadata"] ?: @"{}";
20
- self.fieldName = dict[@"fieldName"];
21
- self.mimeType = dict[@"mimeType"];
22
- self.parameters = dict[@"parameters"];
38
+ // NSNull (a missing option) or a number would be archived as is, and then the
39
+ // whole saved upload map fails to decode with the NSString/NSDictionary allowlist
40
+ self.fieldName = RNBGDStringOrNil(dict[@"fieldName"]);
41
+ self.mimeType = RNBGDStringOrNil(dict[@"mimeType"]);
42
+ self.parameters = RNBGDStringParameters(dict[@"parameters"]);
43
+ id partUrls = dict[@"partUrls"];
44
+ self.partUrls = [partUrls isKindOfClass:[NSArray class]] ? partUrls : nil;
45
+ self.partSize = [dict[@"partSize"] isKindOfClass:[NSNumber class]] ? [dict[@"partSize"] longLongValue] : 0;
23
46
  self.reportedBegin = NO;
24
47
  self.bytesUploaded = 0;
25
48
  self.bytesTotal = 0;
@@ -46,6 +69,13 @@
46
69
  [aCoder encodeInt64:self.bytesTotal forKey:@"bytesTotal"];
47
70
  [aCoder encodeInteger:self.state forKey:@"state"];
48
71
  [aCoder encodeInteger:self.errorCode forKey:@"errorCode"];
72
+ [aCoder encodeObject:self.partUrls forKey:@"partUrls"];
73
+ [aCoder encodeInt64:self.partSize forKey:@"partSize"];
74
+ [aCoder encodeObject:self.partIndexByTask forKey:@"partIndexByTask"];
75
+ [aCoder encodeObject:self.partResults forKey:@"partResults"];
76
+ [aCoder encodeInteger:self.responseCode forKey:@"responseCode"];
77
+ [aCoder encodeObject:self.responseBody forKey:@"responseBody"];
78
+ [aCoder encodeObject:self.responseHeaders forKey:@"responseHeaders"];
49
79
  // Note: responseData is not persisted as it's only needed during active upload
50
80
  }
51
81
 
@@ -73,9 +103,45 @@
73
103
  self.state = [aDecoder decodeIntegerForKey:@"state"];
74
104
  self.errorCode = [aDecoder decodeIntegerForKey:@"errorCode"];
75
105
  self.responseData = nil;
106
+ self.partUrls = [aDecoder decodeObjectOfClasses:[NSSet setWithObjects:[NSArray class], [NSString class], nil] forKey:@"partUrls"];
107
+ self.partSize = [aDecoder decodeInt64ForKey:@"partSize"];
108
+ self.partIndexByTask = [aDecoder decodeObjectOfClasses:[NSSet setWithObjects:[NSDictionary class], [NSNumber class], nil] forKey:@"partIndexByTask"];
109
+ self.partResults = [aDecoder decodeObjectOfClasses:[NSSet setWithObjects:[NSDictionary class], [NSNumber class], [NSString class], nil] forKey:@"partResults"];
110
+ self.responseCode = [aDecoder decodeIntegerForKey:@"responseCode"];
111
+ self.responseBody = [aDecoder decodeObjectOfClass:[NSString class] forKey:@"responseBody"];
112
+ self.responseHeaders = [aDecoder decodeObjectOfClasses:[NSSet setWithObjects:[NSDictionary class], [NSString class], nil] forKey:@"responseHeaders"];
76
113
  }
77
114
 
78
115
  return self;
79
116
  }
80
117
 
118
+ + (NSArray<NSArray<NSNumber *> *> *)partRangesForFileSize:(long long)fileSize
119
+ partCount:(NSUInteger)partCount
120
+ partSize:(long long)partSize
121
+ {
122
+ if (partCount == 0 || fileSize <= 0) return nil;
123
+ long long count = (long long)partCount;
124
+ long long size = partSize > 0 ? partSize : (fileSize + count - 1) / count;
125
+ long long beforeLast = size * (count - 1);
126
+ if (beforeLast >= fileSize || fileSize - beforeLast > size) return nil;
127
+
128
+ NSMutableArray<NSArray<NSNumber *> *> *ranges = [NSMutableArray arrayWithCapacity:partCount];
129
+ for (long long index = 0; index < count; index++) {
130
+ long long offset = size * index;
131
+ long long length = index == count - 1 ? fileSize - offset : size;
132
+ [ranges addObject:@[@(offset), @(length)]];
133
+ }
134
+ return ranges;
135
+ }
136
+
137
+ - (NSArray<NSDictionary *> *)orderedPartResults
138
+ {
139
+ NSArray<NSNumber *> *indexes = [self.partResults.allKeys sortedArrayUsingSelector:@selector(compare:)];
140
+ NSMutableArray<NSDictionary *> *results = [NSMutableArray arrayWithCapacity:indexes.count];
141
+ for (NSNumber *index in indexes) {
142
+ [results addObject:self.partResults[index]];
143
+ }
144
+ return results;
145
+ }
146
+
81
147
  @end