@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
package/lib/types.d.ts CHANGED
@@ -191,9 +191,18 @@ export type UploadProgressHandlerParams = {
191
191
  bytesTotal: number;
192
192
  };
193
193
  export type UploadProgressHandler = (params: UploadProgressHandlerParams) => void;
194
+ export type UploadPartResult = {
195
+ partNumber: number;
196
+ responseCode: number;
197
+ responseBody: string;
198
+ responseHeaders: Record<string, string>;
199
+ bytes: number;
200
+ };
194
201
  export type UploadDoneHandlerParams = {
195
202
  responseCode: number;
196
203
  responseBody: string;
204
+ responseHeaders: Record<string, string>;
205
+ parts?: UploadPartResult[];
197
206
  bytesUploaded: number;
198
207
  bytesTotal: number;
199
208
  };
@@ -211,19 +220,35 @@ export interface UploadTaskInfoNative {
211
220
  bytesTotal: number;
212
221
  errorCode: number;
213
222
  state: number;
223
+ responseCode?: number | null;
224
+ responseBody?: string | null;
225
+ responseHeaders?: Record<string, string> | null;
226
+ parts?: UploadPartResult[] | null;
214
227
  }
215
228
  export interface UploadTaskInfo {
216
229
  id: string;
217
230
  metadata?: object;
218
231
  }
219
232
  export type UploadParams = {
220
- url: string;
233
+ url?: string;
221
234
  source: string;
222
235
  method?: 'POST' | 'PUT' | 'PATCH';
223
236
  headers?: Headers;
224
237
  fieldName?: string;
225
238
  mimeType?: string;
226
239
  parameters?: Record<string, string>;
240
+ /**
241
+ * Upload `source` in parts, one URL per part (e.g. S3 multipart upload with a
242
+ * presigned UploadPart URL each). Part `i` is sent as the raw body to `partUrls[i]`;
243
+ * can't be combined with `fieldName` or `parameters`.
244
+ */
245
+ partUrls?: string[];
246
+ /**
247
+ * Bytes per part, the last part taking what's left. Defaults to
248
+ * `Math.ceil(fileSize / partUrls.length)`. The upload fails if the parts don't
249
+ * cover the file exactly.
250
+ */
251
+ partSize?: number;
227
252
  isAllowedOverRoaming?: boolean;
228
253
  isAllowedOverMetered?: boolean;
229
254
  };
@@ -235,6 +260,10 @@ export interface UploadTask {
235
260
  bytesUploaded: number;
236
261
  bytesTotal: number;
237
262
  uploadParams?: UploadParams;
263
+ responseCode?: number;
264
+ responseBody?: string;
265
+ responseHeaders?: Record<string, string>;
266
+ parts?: UploadPartResult[];
238
267
  begin: (handler: UploadBeginHandler) => UploadTask;
239
268
  progress: (handler: UploadProgressHandler) => UploadTask;
240
269
  done: (handler: UploadDoneHandler) => UploadTask;
@@ -253,7 +282,7 @@ export interface UploadTask {
253
282
  export type getExistingUploadTasks = () => Promise<UploadTask[]>;
254
283
  export interface UploadOption {
255
284
  id: string;
256
- url: string;
285
+ url?: string;
257
286
  source: string;
258
287
  method?: 'POST' | 'PUT' | 'PATCH';
259
288
  headers?: Headers | undefined;
@@ -261,6 +290,8 @@ export interface UploadOption {
261
290
  fieldName?: string;
262
291
  mimeType?: string;
263
292
  parameters?: Record<string, string>;
293
+ partUrls?: string[];
294
+ partSize?: number;
264
295
  isAllowedOverRoaming?: boolean;
265
296
  isAllowedOverMetered?: boolean;
266
297
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kesha-antonov/react-native-background-downloader",
3
- "version": "4.6.4",
3
+ "version": "4.8.0",
4
4
  "description": "Background file downloads and uploads for React Native and Expo. Large files keep transferring on iOS and Android while your app is in the background or terminated. Pause/resume, progress events, TurboModules, TypeScript.",
5
5
  "keywords": [
6
6
  "react-native",
@@ -71,6 +71,7 @@
71
71
  "src/",
72
72
  "lib/",
73
73
  "ios/",
74
+ "!ios/Tests/",
74
75
  "android/build.gradle",
75
76
  "android/src/",
76
77
  "plugin/build/"
@@ -78,20 +79,21 @@
78
79
  "scripts": {
79
80
  "bump": "npm version patch",
80
81
  "lint": "eslint .",
81
- "typecheck": "tsc src/*.ts --noEmit --strict --skipLibCheck",
82
+ "typecheck": "tsc src/*.ts types/*.d.ts --noEmit --strict --skipLibCheck --module node16 --moduleResolution node16",
82
83
  "build": "rm -rf lib && tsc -p tsconfig.build.json",
83
84
  "prepare": "npm run build && npm run build-plugin",
84
85
  "prepublishOnly": "npm run build-plugin && npm run build && npm run typecheck && jest && npm run lint",
85
86
  "build-plugin": "tsc plugin/src/index.ts --outDir plugin/build --target ES2018 --module commonjs --declaration --esModuleInterop --strict --skipLibCheck",
86
87
  "release": "npm publish",
87
88
  "test": "jest",
88
- "test:android": "cd example/android && ./gradlew :kesha-antonov_react-native-background-downloader:testDebugUnitTest"
89
+ "test:android": "cd example/android && ./gradlew :kesha-antonov_react-native-background-downloader:testDebugUnitTest",
90
+ "test:ios": "cd example/ios && xcodebuild test -workspace RNBDExample.xcworkspace -scheme react-native-background-downloader-Unit-Tests -destination \"platform=iOS Simulator,name=${IOS_SIMULATOR:-iPhone 17}\""
89
91
  },
90
92
  "lint-staged": {
91
93
  "*.js": "eslint --cache"
92
94
  },
93
95
  "jest": {
94
- "preset": "react-native",
96
+ "preset": "@react-native/jest-preset",
95
97
  "setupFiles": [
96
98
  "./__mocks__/RNBackgroundDownloader.js",
97
99
  "./__mocks__/NativeEventEmitter.js"
@@ -112,10 +114,11 @@
112
114
  "@babel/preset-env": "^7.28.5",
113
115
  "@babel/preset-typescript": "^7.28.5",
114
116
  "@babel/runtime": "^7.28.4",
115
- "@expo/config-plugins": "^54.0.2",
116
- "@react-native/babel-preset": "^0.81.5",
117
- "@react-native/eslint-config": "^0.81.5",
118
- "@react-native/metro-config": "^0.81.5",
117
+ "@expo/config-plugins": "^58.0.11",
118
+ "@react-native/babel-preset": "^0.88.1",
119
+ "@react-native/eslint-config": "^0.88.1",
120
+ "@react-native/jest-preset": "^0.88.1",
121
+ "@react-native/metro-config": "^0.88.1",
119
122
  "@typescript-eslint/eslint-plugin": "^8.46.1",
120
123
  "@typescript-eslint/parser": "^8.46.1",
121
124
  "babel-jest": "^29.7.0",
@@ -134,11 +137,11 @@
134
137
  "jest": "^29.7.0",
135
138
  "lint-staged": ">=16",
136
139
  "metro-react-native-babel-preset": "^0.77.0",
137
- "react": "19.1.0",
138
- "react-native": "0.81.5",
140
+ "react": "19.3.0",
141
+ "react-native": "0.88.1",
139
142
  "react-native-fs": "^2.20.0",
140
143
  "react-native-vector-icons": "^10.3.0",
141
- "react-test-renderer": "19.2.0",
144
+ "react-test-renderer": "19.3.0",
142
145
  "typescript": "5.9.3"
143
146
  },
144
147
  "peerDependencies": {
@@ -22,4 +22,5 @@ interface PluginOptions {
22
22
  skipMmkvDependency?: boolean;
23
23
  }
24
24
  declare const withRNBackgroundDownloader: ConfigPlugin<PluginOptions | void>;
25
+ export declare function addSwiftSupport(appDelegateContents: string): string;
25
26
  export default withRNBackgroundDownloader;
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.addSwiftSupport = addSwiftSupport;
36
37
  const config_plugins_1 = require("@expo/config-plugins");
37
38
  const fs = __importStar(require("fs"));
38
39
  const path = __importStar(require("path"));
@@ -43,7 +44,7 @@ const withRNBackgroundDownloader = (config, options) => {
43
44
  const shouldSkipMmkv = skipMmkvDependency || hasReactNativeMmkv;
44
45
  // Handle iOS AppDelegate modifications
45
46
  config = (0, config_plugins_1.withAppDelegate)(config, (config) => {
46
- if (config.modResults.language === 'objc') {
47
+ if (config.modResults.language === 'objc' || config.modResults.language === 'objcpp') {
47
48
  // For Objective-C AppDelegate.m (React Native < 0.77)
48
49
  config.modResults.contents = addObjCSupport(config.modResults.contents);
49
50
  }
@@ -160,26 +161,33 @@ function addObjCSupport(appDelegateContents) {
160
161
  function addSwiftSupport(appDelegateContents) {
161
162
  // For Swift, we need to add the method to the AppDelegate class
162
163
  // The import should be handled by the bridging header
164
+ // Remove the method if an older version of this plugin added it outside the AppDelegate class.
165
+ // Only the exact one-line body it generated is matched, so hand-written methods are never touched
166
+ appDelegateContents = appDelegateContents.replace(/\n[ \t]*func application\(\s*_ application: UIApplication,\s*handleEventsForBackgroundURLSession identifier: String,\s*completionHandler: @escaping \(\) -> Void\s*\)\s*\{\s*RNBackgroundDownloader\.setCompletionHandlerWithIdentifier\(identifier, completionHandler: completionHandler\)\s*\}\n/g, '');
163
167
  // Add the handleEventsForBackgroundURLSession method if not already present
164
168
  if (!appDelegateContents.includes('handleEventsForBackgroundURLSession')) {
169
+ // ExpoAppDelegate already implements the method, so it must be overridden and other sessions passed to it
170
+ const isExpo = /\bExpoAppDelegate\b/.test(appDelegateContents);
171
+ const passOtherSessions = `
172
+ guard identifier.hasSuffix(".backgrounddownloadtask") else {
173
+ return super.application(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
174
+ }`;
165
175
  const methodToAdd = `
166
- func application(
176
+ ${isExpo ? 'public override func' : 'func'} application(
167
177
  _ application: UIApplication,
168
178
  handleEventsForBackgroundURLSession identifier: String,
169
179
  completionHandler: @escaping () -> Void
170
- ) {
180
+ ) {${isExpo ? passOtherSessions : ''}
171
181
  RNBackgroundDownloader.setCompletionHandlerWithIdentifier(identifier, completionHandler: completionHandler)
172
182
  }
173
183
  `;
174
184
  // Find the end of the AppDelegate class but before the closing brace
175
- const classEndRegex = /^}$/gm;
176
- const matches = [...appDelegateContents.matchAll(classEndRegex)];
177
- if (matches.length > 0) {
178
- // Insert before the last closing brace (assuming it's the AppDelegate class)
179
- const lastMatch = matches[matches.length - 1];
180
- const insertPosition = lastMatch.index;
185
+ const classMatch = /^.*\bclass\s+AppDelegate\b.*$/m.exec(appDelegateContents);
186
+ const classEndMatch = classMatch ? /^}$/m.exec(appDelegateContents.slice(classMatch.index)) : null;
187
+ if (classMatch && classEndMatch) {
188
+ const insertPosition = classMatch.index + classEndMatch.index;
181
189
  appDelegateContents = appDelegateContents.slice(0, insertPosition) +
182
- methodToAdd + '\n' +
190
+ methodToAdd +
183
191
  appDelegateContents.slice(insertPosition);
184
192
  }
185
193
  }
@@ -16,6 +16,7 @@ Pod::Spec.new do |s|
16
16
  s.source = { git: 'https://github.com/kesha-antonov/react-native-background-downloader.git', tag: 'main' }
17
17
 
18
18
  s.source_files = 'ios/**/*.{h,m,mm,swift}'
19
+ s.exclude_files = 'ios/Tests/**/*'
19
20
  # React Native Core dependency
20
21
  install_modules_dependencies(s)
21
22
 
@@ -42,6 +43,13 @@ Pod::Spec.new do |s|
42
43
  # resolve to the broken 2.4.1 on its own.
43
44
  s.dependency 'MMKVCore', '!= 2.4.1'
44
45
 
46
+ # Unit tests, built only when a Podfile asks for them with `:testspecs => ['Tests']`
47
+ # (the example app does). They need C++20 for React's headers.
48
+ s.test_spec 'Tests' do |test_spec|
49
+ test_spec.source_files = 'ios/Tests/**/*.{h,m,mm}'
50
+ test_spec.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++20' }
51
+ end
52
+
45
53
  # Enable codegen for new architecture
46
54
  if ENV['RCT_NEW_ARCH_ENABLED'] == '1'
47
55
  s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
@@ -49,6 +49,10 @@ export class DownloadTask {
49
49
  doneHandler?: DoneHandler
50
50
  errorHandler?: ErrorHandler
51
51
 
52
+ // begin fires once per task. Android sends it again for each new transfer (a resume in
53
+ // a new job, a reschedule by the system), which isn't a new beginning for the app.
54
+ private hasBegun = false
55
+
52
56
  constructor (taskParams: TaskInfo | TaskInfoNative, originalTask?: DownloadTaskType) {
53
57
  this.id = taskParams.id
54
58
 
@@ -63,6 +67,9 @@ export class DownloadTask {
63
67
 
64
68
  this.metadata = this.tryParseJson(taskParams.metadata) ?? {}
65
69
 
70
+ // A restored task that already has data has begun; so has one this replaces
71
+ this.hasBegun = (originalTask instanceof DownloadTask && originalTask.hasBegun) || this.bytesDownloaded > 0
72
+
66
73
  if (originalTask) {
67
74
  this.beginHandler = originalTask.beginHandler
68
75
  this.progressHandler = originalTask.progressHandler
@@ -107,13 +114,22 @@ export class DownloadTask {
107
114
 
108
115
  // event listeners
109
116
 
117
+ // Native can still deliver begin or progress that was in flight when the app paused
118
+ // or stopped the task, or when it ended. Those must not run handlers or change state.
119
+ private isInactive (): boolean {
120
+ return this.state === 'PAUSED' || this.state === 'STOPPED' || this.state === 'DONE' || this.state === 'FAILED'
121
+ }
122
+
110
123
  onBegin (params: BeginHandlerParams) {
124
+ if (this.isInactive() || this.hasBegun) return
125
+ this.hasBegun = true
111
126
  this.state = 'DOWNLOADING'
112
127
  this.bytesTotal = params.expectedBytes
113
128
  this.beginHandler?.(params)
114
129
  }
115
130
 
116
131
  onProgress (params: ProgressHandlerParams) {
132
+ if (this.isInactive()) return
117
133
  this.bytesDownloaded = params.bytesDownloaded
118
134
  this.bytesTotal = params.bytesTotal
119
135
  this.progressHandler?.(params)
@@ -128,6 +144,7 @@ export class DownloadTask {
128
144
 
129
145
  onError (params: ErrorHandlerParams) {
130
146
  this.state = 'FAILED'
147
+ this.errorCode = params.errorCode
131
148
  this.errorHandler?.(params)
132
149
  }
133
150
 
@@ -193,7 +210,7 @@ export class DownloadTask {
193
210
  ...this.downloadParams,
194
211
  headers: this.headersToUnsafeObject(this.downloadParams.headers),
195
212
  isAllowedOverRoaming: this.downloadParams.isAllowedOverRoaming ?? false,
196
- isAllowedOverMetered: this.downloadParams.isAllowedOverMetered ?? false,
213
+ isAllowedOverMetered: this.downloadParams.isAllowedOverMetered ?? config.allowsCellularAccess,
197
214
  // iOS-only; ignored on Android. Falls back to the global setConfig default.
198
215
  iosDataProtection: this.downloadParams.iosDataProtection ?? config.iosDataProtection,
199
216
  })
@@ -42,10 +42,25 @@ export type UploadProgressEvent = {
42
42
  bytesTotal: number
43
43
  }
44
44
 
45
+ // One part of an upload split across partUrls
46
+ export type UploadPartResult = {
47
+ // 1-based, as S3's CompleteMultipartUpload numbers parts
48
+ partNumber: number
49
+ responseCode: number
50
+ responseBody: string
51
+ // Lowercased header names, e.g. responseHeaders.etag
52
+ responseHeaders: UnsafeObject
53
+ bytes: number
54
+ }
55
+
45
56
  export type UploadCompleteEvent = {
46
57
  id: string
47
58
  responseCode: number
48
59
  responseBody: string
60
+ // Lowercased header names
61
+ responseHeaders?: UnsafeObject
62
+ // Set for an upload with partUrls, in part order
63
+ parts?: UploadPartResult[]
49
64
  bytesUploaded: number
50
65
  bytesTotal: number
51
66
  }
@@ -124,6 +139,9 @@ export interface Spec extends TurboModule {
124
139
  fieldName?: string
125
140
  mimeType?: string
126
141
  parameters?: UnsafeObject
142
+ // Upload source in parts, one URL per part (url is ignored then)
143
+ partUrls?: string[]
144
+ partSize?: number
127
145
  isAllowedOverRoaming: boolean
128
146
  isAllowedOverMetered: boolean
129
147
  }): void
@@ -139,6 +157,11 @@ export interface Spec extends TurboModule {
139
157
  bytesUploaded: number
140
158
  bytesTotal: number
141
159
  errorCode?: number | null
160
+ // The response of an upload that finished while the app wasn't listening
161
+ responseCode?: number | null
162
+ responseBody?: string | null
163
+ responseHeaders?: UnsafeObject | null
164
+ parts?: UploadPartResult[] | null
142
165
  }>>
143
166
 
144
167
  // Event emitters (new architecture)
package/src/UploadTask.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  Metadata,
16
16
  UnsafeObject,
17
17
  Headers,
18
+ UploadPartResult,
18
19
  } from './types'
19
20
  import { config } from './config'
20
21
  import { log } from './logger'
@@ -43,11 +44,21 @@ export class UploadTask {
43
44
 
44
45
  uploadParams?: UploadParams
45
46
 
47
+ // Set once the upload is done
48
+ responseCode?: number
49
+ responseBody?: string
50
+ responseHeaders?: Record<string, string>
51
+ parts?: UploadPartResult[]
52
+
46
53
  beginHandler?: UploadBeginHandler
47
54
  progressHandler?: UploadProgressHandler
48
55
  doneHandler?: UploadDoneHandler
49
56
  errorHandler?: UploadErrorHandler
50
57
 
58
+ // begin fires once per task. Android sends it again for each new transfer (a resume in
59
+ // a new job, a reschedule by the system), which isn't a new beginning for the app.
60
+ private hasBegun = false
61
+
51
62
  constructor (taskParams: UploadTaskInfo | UploadTaskInfoNative, originalTask?: UploadTaskType) {
52
63
  this.id = taskParams.id
53
64
 
@@ -59,6 +70,16 @@ export class UploadTask {
59
70
 
60
71
  this.metadata = this.tryParseJson(taskParams.metadata) ?? {}
61
72
 
73
+ // A finished upload restored by getExistingUploadTasks carries its response
74
+ const nativeInfo = taskParams as UploadTaskInfoNative
75
+ if (nativeInfo.responseCode != null) this.responseCode = nativeInfo.responseCode
76
+ if (nativeInfo.responseBody != null) this.responseBody = nativeInfo.responseBody
77
+ if (nativeInfo.responseHeaders != null) this.responseHeaders = nativeInfo.responseHeaders
78
+ if (nativeInfo.parts != null) this.parts = nativeInfo.parts
79
+
80
+ // A restored task that already has data has begun; so has one this replaces
81
+ this.hasBegun = (originalTask instanceof UploadTask && originalTask.hasBegun) || this.bytesUploaded > 0
82
+
62
83
  if (originalTask) {
63
84
  this.beginHandler = originalTask.beginHandler
64
85
  this.progressHandler = originalTask.progressHandler
@@ -103,13 +124,22 @@ export class UploadTask {
103
124
 
104
125
  // event listeners
105
126
 
127
+ // Native can still deliver begin or progress that was in flight when the app paused
128
+ // or stopped the upload, or when it ended. Those must not run handlers or change state.
129
+ private isInactive (): boolean {
130
+ return this.state === 'PAUSED' || this.state === 'STOPPED' || this.state === 'DONE' || this.state === 'FAILED'
131
+ }
132
+
106
133
  onBegin (params: UploadBeginHandlerParams) {
134
+ if (this.isInactive() || this.hasBegun) return
135
+ this.hasBegun = true
107
136
  this.state = 'UPLOADING'
108
137
  this.bytesTotal = params.expectedBytes
109
138
  this.beginHandler?.(params)
110
139
  }
111
140
 
112
141
  onProgress (params: UploadProgressHandlerParams) {
142
+ if (this.isInactive()) return
113
143
  this.bytesUploaded = params.bytesUploaded
114
144
  this.bytesTotal = params.bytesTotal
115
145
  this.progressHandler?.(params)
@@ -119,11 +149,16 @@ export class UploadTask {
119
149
  this.state = 'DONE'
120
150
  this.bytesUploaded = params.bytesUploaded
121
151
  this.bytesTotal = params.bytesTotal
152
+ this.responseCode = params.responseCode
153
+ this.responseBody = params.responseBody
154
+ this.responseHeaders = params.responseHeaders
155
+ this.parts = params.parts
122
156
  this.doneHandler?.(params)
123
157
  }
124
158
 
125
159
  onError (params: UploadErrorHandlerParams) {
126
160
  this.state = 'FAILED'
161
+ this.errorCode = params.errorCode
127
162
  this.errorHandler?.(params)
128
163
  }
129
164
 
@@ -177,16 +212,20 @@ export class UploadTask {
177
212
  this.state = 'UPLOADING'
178
213
 
179
214
  // kick-off upload after returning the task
215
+ const { partUrls } = this.uploadParams
180
216
  nativeModule.upload({
181
217
  id: this.id,
182
218
  metadata: JSON.stringify(this.metadata),
183
219
  progressInterval: config.progressInterval,
184
220
  progressMinBytes: config.progressMinBytes,
185
221
  ...this.uploadParams,
186
- method: this.uploadParams.method ?? 'POST',
222
+ // The native spec requires a url; with partUrls native uses those instead
223
+ url: this.uploadParams.url ?? partUrls?.[0] ?? '',
224
+ // S3 UploadPart (and similar part APIs) take PUT
225
+ method: this.uploadParams.method ?? (partUrls ? 'PUT' : 'POST'),
187
226
  headers: this.headersToUnsafeObject(this.uploadParams.headers),
188
227
  isAllowedOverRoaming: this.uploadParams.isAllowedOverRoaming ?? false,
189
- isAllowedOverMetered: this.uploadParams.isAllowedOverMetered ?? false,
228
+ isAllowedOverMetered: this.uploadParams.isAllowedOverMetered ?? config.allowsCellularAccess,
190
229
  })
191
230
  }
192
231