@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
@@ -31,10 +31,19 @@ export type UploadProgressEvent = {
31
31
  bytesUploaded: number;
32
32
  bytesTotal: number;
33
33
  };
34
+ export type UploadPartResult = {
35
+ partNumber: number;
36
+ responseCode: number;
37
+ responseBody: string;
38
+ responseHeaders: UnsafeObject;
39
+ bytes: number;
40
+ };
34
41
  export type UploadCompleteEvent = {
35
42
  id: string;
36
43
  responseCode: number;
37
44
  responseBody: string;
45
+ responseHeaders?: UnsafeObject;
46
+ parts?: UploadPartResult[];
38
47
  bytesUploaded: number;
39
48
  bytesTotal: number;
40
49
  };
@@ -102,6 +111,8 @@ export interface Spec extends TurboModule {
102
111
  fieldName?: string;
103
112
  mimeType?: string;
104
113
  parameters?: UnsafeObject;
114
+ partUrls?: string[];
115
+ partSize?: number;
105
116
  isAllowedOverRoaming: boolean;
106
117
  isAllowedOverMetered: boolean;
107
118
  }): void;
@@ -115,6 +126,10 @@ export interface Spec extends TurboModule {
115
126
  bytesUploaded: number;
116
127
  bytesTotal: number;
117
128
  errorCode?: number | null;
129
+ responseCode?: number | null;
130
+ responseBody?: string | null;
131
+ responseHeaders?: UnsafeObject | null;
132
+ parts?: UploadPartResult[] | null;
118
133
  }>>;
119
134
  readonly onDownloadBegin: EventEmitter<DownloadBeginEvent>;
120
135
  readonly onDownloadProgress: EventEmitter<DownloadProgressEvent[]>;
@@ -1,4 +1,4 @@
1
- import { UploadTaskInfo, UploadTask as UploadTaskType, UploadBeginHandler, UploadProgressHandler, UploadDoneHandler, UploadErrorHandler, UploadBeginHandlerParams, UploadProgressHandlerParams, UploadDoneHandlerParams, UploadErrorHandlerParams, UploadTaskInfoNative, UploadParams, UploadTaskState, Metadata } from './types';
1
+ import { UploadTaskInfo, UploadTask as UploadTaskType, UploadBeginHandler, UploadProgressHandler, UploadDoneHandler, UploadErrorHandler, UploadBeginHandlerParams, UploadProgressHandlerParams, UploadDoneHandlerParams, UploadErrorHandlerParams, UploadTaskInfoNative, UploadParams, UploadTaskState, Metadata, UploadPartResult } from './types';
2
2
  export declare class UploadTask {
3
3
  id: string;
4
4
  metadata: Metadata;
@@ -7,6 +7,10 @@ export declare class UploadTask {
7
7
  bytesUploaded: number;
8
8
  bytesTotal: number;
9
9
  uploadParams?: UploadParams;
10
+ responseCode?: number;
11
+ responseBody?: string;
12
+ responseHeaders?: Record<string, string>;
13
+ parts?: UploadPartResult[];
10
14
  beginHandler?: UploadBeginHandler;
11
15
  progressHandler?: UploadProgressHandler;
12
16
  doneHandler?: UploadDoneHandler;
package/lib/UploadTask.js CHANGED
@@ -31,6 +31,16 @@ class UploadTask {
31
31
  if (taskParams.bytesTotal)
32
32
  this.bytesTotal = taskParams.bytesTotal;
33
33
  this.metadata = (_a = this.tryParseJson(taskParams.metadata)) !== null && _a !== void 0 ? _a : {};
34
+ // A finished upload restored by getExistingUploadTasks carries its response
35
+ const nativeInfo = taskParams;
36
+ if (nativeInfo.responseCode != null)
37
+ this.responseCode = nativeInfo.responseCode;
38
+ if (nativeInfo.responseBody != null)
39
+ this.responseBody = nativeInfo.responseBody;
40
+ if (nativeInfo.responseHeaders != null)
41
+ this.responseHeaders = nativeInfo.responseHeaders;
42
+ if (nativeInfo.parts != null)
43
+ this.parts = nativeInfo.parts;
34
44
  // A restored task that already has data has begun; so has one this replaces
35
45
  this.hasBegun = (originalTask instanceof UploadTask && originalTask.hasBegun) || this.bytesUploaded > 0;
36
46
  if (originalTask) {
@@ -93,6 +103,10 @@ class UploadTask {
93
103
  this.state = 'DONE';
94
104
  this.bytesUploaded = params.bytesUploaded;
95
105
  this.bytesTotal = params.bytesTotal;
106
+ this.responseCode = params.responseCode;
107
+ this.responseBody = params.responseBody;
108
+ this.responseHeaders = params.responseHeaders;
109
+ this.parts = params.parts;
96
110
  (_a = this.doneHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
97
111
  }
98
112
  onError(params) {
@@ -125,7 +139,7 @@ class UploadTask {
125
139
  (0, logger_1.log)('UploadTask: resume not supported - native implementation missing');
126
140
  }
127
141
  start() {
128
- var _a, _b, _c, _d, _e, _f;
142
+ var _a, _b, _c, _d, _e, _f, _g, _h;
129
143
  if (this.state !== 'PENDING') {
130
144
  (0, logger_1.log)('UploadTask: start. Upload already started, can\' start again... ', this.id);
131
145
  (_a = this.errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, { error: 'Upload already started', errorCode: -1 });
@@ -144,16 +158,20 @@ class UploadTask {
144
158
  }
145
159
  this.state = 'UPLOADING';
146
160
  // kick-off upload after returning the task
161
+ const { partUrls } = this.uploadParams;
147
162
  nativeModule.upload({
148
163
  id: this.id,
149
164
  metadata: JSON.stringify(this.metadata),
150
165
  progressInterval: config_1.config.progressInterval,
151
166
  progressMinBytes: config_1.config.progressMinBytes,
152
167
  ...this.uploadParams,
153
- method: (_d = this.uploadParams.method) !== null && _d !== void 0 ? _d : 'POST',
168
+ // The native spec requires a url; with partUrls native uses those instead
169
+ url: (_e = (_d = this.uploadParams.url) !== null && _d !== void 0 ? _d : partUrls === null || partUrls === void 0 ? void 0 : partUrls[0]) !== null && _e !== void 0 ? _e : '',
170
+ // S3 UploadPart (and similar part APIs) take PUT
171
+ method: (_f = this.uploadParams.method) !== null && _f !== void 0 ? _f : (partUrls ? 'PUT' : 'POST'),
154
172
  headers: this.headersToUnsafeObject(this.uploadParams.headers),
155
- isAllowedOverRoaming: (_e = this.uploadParams.isAllowedOverRoaming) !== null && _e !== void 0 ? _e : false,
156
- isAllowedOverMetered: (_f = this.uploadParams.isAllowedOverMetered) !== null && _f !== void 0 ? _f : config_1.config.allowsCellularAccess,
173
+ isAllowedOverRoaming: (_g = this.uploadParams.isAllowedOverRoaming) !== null && _g !== void 0 ? _g : false,
174
+ isAllowedOverMetered: (_h = this.uploadParams.isAllowedOverMetered) !== null && _h !== void 0 ? _h : config_1.config.allowsCellularAccess,
157
175
  });
158
176
  }
159
177
  async stop() {
package/lib/index.js CHANGED
@@ -58,6 +58,40 @@ function ensureNativeModuleInitialized() {
58
58
  return RNBackgroundDownloader;
59
59
  }
60
60
  const MIN_PROGRESS_INTERVAL = 250;
61
+ // Apps forward logs to remote services: log response header names and the body
62
+ // size, not values that can carry cookies or tokens
63
+ function loggableBegin({ headers, ...rest }) {
64
+ return { ...rest, headers: Object.keys(headers !== null && headers !== void 0 ? headers : {}) };
65
+ }
66
+ function loggableUploadComplete({ responseBody, responseHeaders, parts, ...rest }) {
67
+ var _a;
68
+ return {
69
+ ...rest,
70
+ responseBodyLength: (_a = responseBody === null || responseBody === void 0 ? void 0 : responseBody.length) !== null && _a !== void 0 ? _a : 0,
71
+ responseHeaders: Object.keys(responseHeaders !== null && responseHeaders !== void 0 ? responseHeaders : {}),
72
+ parts: parts === null || parts === void 0 ? void 0 : parts.length,
73
+ };
74
+ }
75
+ function handleUploadComplete(data) {
76
+ var _a, _b, _c;
77
+ const { id, responseHeaders, ...rest } = data;
78
+ (0, logger_1.log)('uploadComplete', id, loggableUploadComplete(data));
79
+ const task = tasks_1.uploadTasksMap.get(id);
80
+ if (!task) {
81
+ // Nobody received it: after a relaunch, iOS can deliver a finished upload
82
+ // before the app has called getExistingUploadTasks. Native keeps the
83
+ // response, so that call still returns it as DONE.
84
+ (0, logger_1.log)('uploadComplete: task not found in uploadTasksMap', id);
85
+ return;
86
+ }
87
+ // iOS keeps a finished upload's response until JS has it, so an upload that
88
+ // finishes while the app isn't listening still reaches getExistingUploadTasks.
89
+ // This one was delivered: let native drop it. Sent before the handlers run, so it
90
+ // can't race an upload the done handler starts with the same id.
91
+ (_c = (_b = (_a = ensureNativeModuleInitialized()).stopUploadTask) === null || _b === void 0 ? void 0 : _b.call(_a, id)) === null || _c === void 0 ? void 0 : _c.catch(() => { });
92
+ task.onDone({ ...rest, responseHeaders: responseHeaders !== null && responseHeaders !== void 0 ? responseHeaders : {} });
93
+ tasks_1.uploadTasksMap.delete(id);
94
+ }
61
95
  // Set up event listeners based on architecture
62
96
  // For old architecture, we need to defer NativeEventEmitter creation
63
97
  // to avoid issues during module initialization
@@ -88,7 +122,7 @@ function initializeEventListeners() {
88
122
  // iOS new architecture: use EventEmitter from TurboModule spec
89
123
  eventSubscriptions.push(turboModule.onDownloadBegin((data) => {
90
124
  const { id, ...rest } = data;
91
- (0, logger_1.log)('downloadBegin', id, rest);
125
+ (0, logger_1.log)('downloadBegin', id, loggableBegin(rest));
92
126
  const task = tasks_1.tasksMap.get(id);
93
127
  if (!task) {
94
128
  (0, logger_1.log)('downloadBegin: task not found in tasksMap', id);
@@ -146,16 +180,7 @@ function initializeEventListeners() {
146
180
  task.onProgress(rest);
147
181
  }
148
182
  }));
149
- eventSubscriptions.push(turboModule.onUploadComplete((data) => {
150
- const { id, ...rest } = data;
151
- (0, logger_1.log)('uploadComplete', id, rest);
152
- const task = tasks_1.uploadTasksMap.get(id);
153
- if (!task)
154
- (0, logger_1.log)('uploadComplete: task not found in uploadTasksMap', id);
155
- else
156
- task.onDone(rest);
157
- tasks_1.uploadTasksMap.delete(id);
158
- }));
183
+ eventSubscriptions.push(turboModule.onUploadComplete(handleUploadComplete));
159
184
  eventSubscriptions.push(turboModule.onUploadFailed((data) => {
160
185
  const { id, ...rest } = data;
161
186
  (0, logger_1.log)('uploadFailed', id, rest);
@@ -176,7 +201,7 @@ function initializeEventListeners() {
176
201
  const eventEmitter = new react_native_1.NativeEventEmitter(RNBackgroundDownloader);
177
202
  eventSubscriptions.push(eventEmitter.addListener('downloadBegin', (data) => {
178
203
  const { id, ...rest } = data;
179
- (0, logger_1.log)('downloadBegin', id, rest);
204
+ (0, logger_1.log)('downloadBegin', id, loggableBegin(rest));
180
205
  const task = tasks_1.tasksMap.get(id);
181
206
  if (!task) {
182
207
  (0, logger_1.log)('downloadBegin: task not found in tasksMap', id);
@@ -233,16 +258,7 @@ function initializeEventListeners() {
233
258
  task.onProgress(rest);
234
259
  }
235
260
  }));
236
- eventSubscriptions.push(eventEmitter.addListener('uploadComplete', (data) => {
237
- const { id, ...rest } = data;
238
- (0, logger_1.log)('uploadComplete', id, rest);
239
- const task = tasks_1.uploadTasksMap.get(id);
240
- if (!task)
241
- (0, logger_1.log)('uploadComplete: task not found in uploadTasksMap', id);
242
- else
243
- task.onDone(rest);
244
- tasks_1.uploadTasksMap.delete(id);
245
- }));
261
+ eventSubscriptions.push(eventEmitter.addListener('uploadComplete', handleUploadComplete));
246
262
  eventSubscriptions.push(eventEmitter.addListener('uploadFailed', (data) => {
247
263
  const { id, ...rest } = data;
248
264
  (0, logger_1.log)('uploadFailed', id, rest);
@@ -429,7 +445,7 @@ const getExistingUploadTasks = async () => {
429
445
  }
430
446
  const uploads = await nativeModule.getExistingUploadTasks();
431
447
  const uploadTasks = uploads.map(uploadInfo => {
432
- var _a;
448
+ var _a, _b, _c;
433
449
  // Parse metadata from JSON string to object
434
450
  let metadata = {};
435
451
  if (uploadInfo.metadata)
@@ -468,11 +484,16 @@ const getExistingUploadTasks = async () => {
468
484
  break;
469
485
  }
470
486
  case nativeModule.TaskCompleted: {
471
- if (taskInfo.bytesUploaded === taskInfo.bytesTotal)
487
+ if (taskInfo.bytesUploaded === taskInfo.bytesTotal) {
472
488
  task.state = 'DONE';
473
- else
489
+ // Finished while the app wasn't listening: the task carries the response
490
+ // now, so native can drop its copy
491
+ (_c = (_b = nativeModule.stopUploadTask) === null || _b === void 0 ? void 0 : _b.call(nativeModule, task.id)) === null || _c === void 0 ? void 0 : _c.catch(() => { });
492
+ }
493
+ else {
474
494
  // IOS completed the upload but it was not done.
475
495
  return undefined;
496
+ }
476
497
  }
477
498
  }
478
499
  return task;
@@ -487,8 +508,17 @@ function createUploadTask({ isAllowedOverRoaming = true,
487
508
  isAllowedOverMetered = config_1.config.allowsCellularAccess, metadata, ...rest }) {
488
509
  // Ensure native module and event listeners are initialized before creating tasks
489
510
  ensureNativeModuleInitialized();
490
- if (!rest.id || !rest.url || !rest.source)
491
- throw new Error('[RNBackgroundDownloader] id, url and source are required');
511
+ if (rest.partUrls !== undefined) {
512
+ if (!Array.isArray(rest.partUrls) || rest.partUrls.length === 0 ||
513
+ rest.partUrls.some(url => typeof url !== 'string' || url.length === 0))
514
+ throw new Error('[RNBackgroundDownloader] partUrls must be a non-empty array of URLs');
515
+ if (rest.fieldName !== undefined || rest.parameters !== undefined)
516
+ throw new Error('[RNBackgroundDownloader] partUrls sends each part as the raw body; it can\'t be combined with fieldName or parameters');
517
+ if (rest.partSize !== undefined && !(Number.isInteger(rest.partSize) && rest.partSize > 0))
518
+ throw new Error('[RNBackgroundDownloader] partSize must be a positive whole number of bytes');
519
+ }
520
+ if (!rest.id || !(rest.url || rest.partUrls) || !rest.source)
521
+ throw new Error('[RNBackgroundDownloader] id, url (or partUrls) and source are required');
492
522
  rest.headers = { ...config_1.config.headers, ...rest.headers };
493
523
  rest.source = rest.source.replace('file://', '');
494
524
  const task = new UploadTask_1.UploadTask({
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.7.0",
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",
@@ -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,6 +44,12 @@ 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
@@ -63,6 +70,13 @@ export class UploadTask {
63
70
 
64
71
  this.metadata = this.tryParseJson(taskParams.metadata) ?? {}
65
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
+
66
80
  // A restored task that already has data has begun; so has one this replaces
67
81
  this.hasBegun = (originalTask instanceof UploadTask && originalTask.hasBegun) || this.bytesUploaded > 0
68
82
 
@@ -135,6 +149,10 @@ export class UploadTask {
135
149
  this.state = 'DONE'
136
150
  this.bytesUploaded = params.bytesUploaded
137
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
138
156
  this.doneHandler?.(params)
139
157
  }
140
158
 
@@ -194,13 +212,17 @@ export class UploadTask {
194
212
  this.state = 'UPLOADING'
195
213
 
196
214
  // kick-off upload after returning the task
215
+ const { partUrls } = this.uploadParams
197
216
  nativeModule.upload({
198
217
  id: this.id,
199
218
  metadata: JSON.stringify(this.metadata),
200
219
  progressInterval: config.progressInterval,
201
220
  progressMinBytes: config.progressMinBytes,
202
221
  ...this.uploadParams,
203
- 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'),
204
226
  headers: this.headersToUnsafeObject(this.uploadParams.headers),
205
227
  isAllowedOverRoaming: this.uploadParams.isAllowedOverRoaming ?? false,
206
228
  isAllowedOverMetered: this.uploadParams.isAllowedOverMetered ?? config.allowsCellularAccess,
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { NativeModules, Platform, TurboModuleRegistry, NativeEventEmitter } from 'react-native'
2
2
  import { DownloadTask } from './DownloadTask'
3
3
  import { UploadTask } from './UploadTask'
4
- import { Config, DownloadParams, Headers, Metadata, TaskInfo, TaskInfoNative, UploadParams, UploadTaskInfo, UploadTaskInfoNative } from './types'
4
+ import { Config, DownloadParams, Headers, Metadata, TaskInfo, TaskInfoNative, UploadParams, UploadPartResult, UploadTaskInfo, UploadTaskInfoNative } from './types'
5
5
  import { config, DEFAULT_NOTIFICATION_TEXTS } from './config'
6
6
  import { log } from './logger'
7
7
  import { getNotificationTextsForNative } from './notifications'
@@ -126,10 +126,47 @@ interface UploadCompleteEvent {
126
126
  id: string
127
127
  responseCode: number
128
128
  responseBody: string
129
+ responseHeaders?: Record<string, string>
130
+ parts?: UploadPartResult[]
129
131
  bytesUploaded: number
130
132
  bytesTotal: number
131
133
  }
132
134
 
135
+ // Apps forward logs to remote services: log response header names and the body
136
+ // size, not values that can carry cookies or tokens
137
+ function loggableBegin ({ headers, ...rest }: Omit<DownloadBeginEvent, 'id'>) {
138
+ return { ...rest, headers: Object.keys(headers ?? {}) }
139
+ }
140
+
141
+ function loggableUploadComplete ({ responseBody, responseHeaders, parts, ...rest }: Omit<UploadCompleteEvent, 'id'>) {
142
+ return {
143
+ ...rest,
144
+ responseBodyLength: responseBody?.length ?? 0,
145
+ responseHeaders: Object.keys(responseHeaders ?? {}),
146
+ parts: parts?.length,
147
+ }
148
+ }
149
+
150
+ function handleUploadComplete (data: UploadCompleteEvent) {
151
+ const { id, responseHeaders, ...rest } = data
152
+ log('uploadComplete', id, loggableUploadComplete(data))
153
+ const task = uploadTasksMap.get(id)
154
+ if (!task) {
155
+ // Nobody received it: after a relaunch, iOS can deliver a finished upload
156
+ // before the app has called getExistingUploadTasks. Native keeps the
157
+ // response, so that call still returns it as DONE.
158
+ log('uploadComplete: task not found in uploadTasksMap', id)
159
+ return
160
+ }
161
+ // iOS keeps a finished upload's response until JS has it, so an upload that
162
+ // finishes while the app isn't listening still reaches getExistingUploadTasks.
163
+ // This one was delivered: let native drop it. Sent before the handlers run, so it
164
+ // can't race an upload the done handler starts with the same id.
165
+ ensureNativeModuleInitialized().stopUploadTask?.(id)?.catch(() => {})
166
+ task.onDone({ ...rest, responseHeaders: responseHeaders ?? {} })
167
+ uploadTasksMap.delete(id)
168
+ }
169
+
133
170
  interface UploadFailedEvent {
134
171
  id: string
135
172
  error: string
@@ -169,7 +206,7 @@ function initializeEventListeners () {
169
206
  // iOS new architecture: use EventEmitter from TurboModule spec
170
207
  eventSubscriptions.push(turboModule.onDownloadBegin((data: DownloadBeginEvent) => {
171
208
  const { id, ...rest } = data
172
- log('downloadBegin', id, rest)
209
+ log('downloadBegin', id, loggableBegin(rest))
173
210
  const task = tasksMap.get(id)
174
211
  if (!task) {
175
212
  log('downloadBegin: task not found in tasksMap', id)
@@ -233,16 +270,7 @@ function initializeEventListeners () {
233
270
  }
234
271
  }))
235
272
 
236
- eventSubscriptions.push(turboModule.onUploadComplete!((data: UploadCompleteEvent) => {
237
- const { id, ...rest } = data
238
- log('uploadComplete', id, rest)
239
- const task = uploadTasksMap.get(id)
240
- if (!task)
241
- log('uploadComplete: task not found in uploadTasksMap', id)
242
- else
243
- task.onDone(rest)
244
- uploadTasksMap.delete(id)
245
- }))
273
+ eventSubscriptions.push(turboModule.onUploadComplete!(handleUploadComplete))
246
274
 
247
275
  eventSubscriptions.push(turboModule.onUploadFailed!((data: UploadFailedEvent) => {
248
276
  const { id, ...rest } = data
@@ -265,7 +293,7 @@ function initializeEventListeners () {
265
293
  eventSubscriptions.push(
266
294
  eventEmitter.addListener('downloadBegin', (data: DownloadBeginEvent) => {
267
295
  const { id, ...rest } = data
268
- log('downloadBegin', id, rest)
296
+ log('downloadBegin', id, loggableBegin(rest))
269
297
  const task = tasksMap.get(id)
270
298
  if (!task) {
271
299
  log('downloadBegin: task not found in tasksMap', id)
@@ -340,16 +368,7 @@ function initializeEventListeners () {
340
368
  )
341
369
 
342
370
  eventSubscriptions.push(
343
- eventEmitter.addListener('uploadComplete', (data: UploadCompleteEvent) => {
344
- const { id, ...rest } = data
345
- log('uploadComplete', id, rest)
346
- const task = uploadTasksMap.get(id)
347
- if (!task)
348
- log('uploadComplete: task not found in uploadTasksMap', id)
349
- else
350
- task.onDone(rest)
351
- uploadTasksMap.delete(id)
352
- })
371
+ eventEmitter.addListener('uploadComplete', handleUploadComplete)
353
372
  )
354
373
 
355
374
  eventSubscriptions.push(
@@ -640,11 +659,15 @@ export const getExistingUploadTasks = async (): Promise<UploadTask[]> => {
640
659
  break
641
660
  }
642
661
  case nativeModule.TaskCompleted: {
643
- if (taskInfo.bytesUploaded === taskInfo.bytesTotal)
662
+ if (taskInfo.bytesUploaded === taskInfo.bytesTotal) {
644
663
  task.state = 'DONE'
645
- else
664
+ // Finished while the app wasn't listening: the task carries the response
665
+ // now, so native can drop its copy
666
+ nativeModule.stopUploadTask?.(task.id)?.catch(() => {})
667
+ } else {
646
668
  // IOS completed the upload but it was not done.
647
669
  return undefined
670
+ }
648
671
  }
649
672
  }
650
673
 
@@ -667,8 +690,18 @@ export function createUploadTask ({
667
690
  // Ensure native module and event listeners are initialized before creating tasks
668
691
  ensureNativeModuleInitialized()
669
692
 
670
- if (!rest.id || !rest.url || !rest.source)
671
- throw new Error('[RNBackgroundDownloader] id, url and source are required')
693
+ if (rest.partUrls !== undefined) {
694
+ if (!Array.isArray(rest.partUrls) || rest.partUrls.length === 0 ||
695
+ rest.partUrls.some(url => typeof url !== 'string' || url.length === 0))
696
+ throw new Error('[RNBackgroundDownloader] partUrls must be a non-empty array of URLs')
697
+ if (rest.fieldName !== undefined || rest.parameters !== undefined)
698
+ throw new Error('[RNBackgroundDownloader] partUrls sends each part as the raw body; it can\'t be combined with fieldName or parameters')
699
+ if (rest.partSize !== undefined && !(Number.isInteger(rest.partSize) && rest.partSize > 0))
700
+ throw new Error('[RNBackgroundDownloader] partSize must be a positive whole number of bytes')
701
+ }
702
+
703
+ if (!rest.id || !(rest.url || rest.partUrls) || !rest.source)
704
+ throw new Error('[RNBackgroundDownloader] id, url (or partUrls) and source are required')
672
705
 
673
706
  rest.headers = { ...config.headers, ...rest.headers }
674
707