@kesha-antonov/react-native-background-downloader 4.6.4 → 4.7.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 (38) hide show
  1. package/README.md +27 -5
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +13 -2
  3. package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
  4. package/android/src/main/java/com/eko/Downloader.kt +25 -4
  5. package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
  6. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +162 -76
  7. package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
  8. package/android/src/main/java/com/eko/ResumableDownloader.kt +75 -3
  9. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
  10. package/android/src/main/java/com/eko/Uploader.kt +15 -11
  11. package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
  12. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
  13. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
  14. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +5 -13
  15. package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
  16. package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
  17. package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
  18. package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
  19. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +84 -0
  20. package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
  21. package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
  22. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +67 -0
  23. package/ios/RNBGDTaskConfig.h +2 -0
  24. package/ios/RNBGDTaskConfig.mm +6 -0
  25. package/ios/RNBackgroundDownloader.mm +640 -90
  26. package/lib/DownloadTask.d.ts +2 -0
  27. package/lib/DownloadTask.js +17 -1
  28. package/lib/UploadTask.d.ts +2 -0
  29. package/lib/UploadTask.js +17 -1
  30. package/lib/index.d.ts +1 -1
  31. package/lib/index.js +50 -36
  32. package/package.json +14 -11
  33. package/plugin/build/index.d.ts +1 -0
  34. package/plugin/build/index.js +18 -10
  35. package/react-native-background-downloader.podspec +8 -0
  36. package/src/DownloadTask.ts +18 -1
  37. package/src/UploadTask.ts +18 -1
  38. package/src/index.ts +73 -41
@@ -12,11 +12,13 @@ export declare class DownloadTask {
12
12
  progressHandler?: ProgressHandler;
13
13
  doneHandler?: DoneHandler;
14
14
  errorHandler?: ErrorHandler;
15
+ private hasBegun;
15
16
  constructor(taskParams: TaskInfo | TaskInfoNative, originalTask?: DownloadTaskType);
16
17
  begin(handler: BeginHandler): this;
17
18
  progress(handler: ProgressHandler): this;
18
19
  done(handler: DoneHandler): this;
19
20
  error(handler: ErrorHandler): this;
21
+ private isInactive;
20
22
  onBegin(params: BeginHandlerParams): void;
21
23
  onProgress(params: ProgressHandlerParams): void;
22
24
  onDone(params: DoneHandlerParams): void;
@@ -22,6 +22,9 @@ class DownloadTask {
22
22
  this.errorCode = 0;
23
23
  this.bytesDownloaded = 0;
24
24
  this.bytesTotal = 0;
25
+ // begin fires once per task. Android sends it again for each new transfer (a resume in
26
+ // a new job, a reschedule by the system), which isn't a new beginning for the app.
27
+ this.hasBegun = false;
25
28
  this.id = taskParams.id;
26
29
  if (taskParams.bytesDownloaded)
27
30
  this.bytesDownloaded = taskParams.bytesDownloaded;
@@ -30,6 +33,8 @@ class DownloadTask {
30
33
  if (taskParams.destination)
31
34
  this.destination = (_a = taskParams.destination) !== null && _a !== void 0 ? _a : undefined;
32
35
  this.metadata = (_b = this.tryParseJson(taskParams.metadata)) !== null && _b !== void 0 ? _b : {};
36
+ // A restored task that already has data has begun; so has one this replaces
37
+ this.hasBegun = (originalTask instanceof DownloadTask && originalTask.hasBegun) || this.bytesDownloaded > 0;
33
38
  if (originalTask) {
34
39
  this.beginHandler = originalTask.beginHandler;
35
40
  this.progressHandler = originalTask.progressHandler;
@@ -63,14 +68,24 @@ class DownloadTask {
63
68
  return this;
64
69
  }
65
70
  // event listeners
71
+ // Native can still deliver begin or progress that was in flight when the app paused
72
+ // or stopped the task, or when it ended. Those must not run handlers or change state.
73
+ isInactive() {
74
+ return this.state === 'PAUSED' || this.state === 'STOPPED' || this.state === 'DONE' || this.state === 'FAILED';
75
+ }
66
76
  onBegin(params) {
67
77
  var _a;
78
+ if (this.isInactive() || this.hasBegun)
79
+ return;
80
+ this.hasBegun = true;
68
81
  this.state = 'DOWNLOADING';
69
82
  this.bytesTotal = params.expectedBytes;
70
83
  (_a = this.beginHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
71
84
  }
72
85
  onProgress(params) {
73
86
  var _a;
87
+ if (this.isInactive())
88
+ return;
74
89
  this.bytesDownloaded = params.bytesDownloaded;
75
90
  this.bytesTotal = params.bytesTotal;
76
91
  (_a = this.progressHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
@@ -85,6 +100,7 @@ class DownloadTask {
85
100
  onError(params) {
86
101
  var _a;
87
102
  this.state = 'FAILED';
103
+ this.errorCode = params.errorCode;
88
104
  (_a = this.errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
89
105
  }
90
106
  // methods
@@ -141,7 +157,7 @@ class DownloadTask {
141
157
  ...this.downloadParams,
142
158
  headers: this.headersToUnsafeObject(this.downloadParams.headers),
143
159
  isAllowedOverRoaming: (_c = this.downloadParams.isAllowedOverRoaming) !== null && _c !== void 0 ? _c : false,
144
- isAllowedOverMetered: (_d = this.downloadParams.isAllowedOverMetered) !== null && _d !== void 0 ? _d : false,
160
+ isAllowedOverMetered: (_d = this.downloadParams.isAllowedOverMetered) !== null && _d !== void 0 ? _d : config_1.config.allowsCellularAccess,
145
161
  // iOS-only; ignored on Android. Falls back to the global setConfig default.
146
162
  iosDataProtection: (_e = this.downloadParams.iosDataProtection) !== null && _e !== void 0 ? _e : config_1.config.iosDataProtection,
147
163
  });
@@ -11,11 +11,13 @@ export declare class UploadTask {
11
11
  progressHandler?: UploadProgressHandler;
12
12
  doneHandler?: UploadDoneHandler;
13
13
  errorHandler?: UploadErrorHandler;
14
+ private hasBegun;
14
15
  constructor(taskParams: UploadTaskInfo | UploadTaskInfoNative, originalTask?: UploadTaskType);
15
16
  begin(handler: UploadBeginHandler): this;
16
17
  progress(handler: UploadProgressHandler): this;
17
18
  done(handler: UploadDoneHandler): this;
18
19
  error(handler: UploadErrorHandler): this;
20
+ private isInactive;
19
21
  onBegin(params: UploadBeginHandlerParams): void;
20
22
  onProgress(params: UploadProgressHandlerParams): void;
21
23
  onDone(params: UploadDoneHandlerParams): void;
package/lib/UploadTask.js CHANGED
@@ -22,12 +22,17 @@ class UploadTask {
22
22
  this.errorCode = 0;
23
23
  this.bytesUploaded = 0;
24
24
  this.bytesTotal = 0;
25
+ // begin fires once per task. Android sends it again for each new transfer (a resume in
26
+ // a new job, a reschedule by the system), which isn't a new beginning for the app.
27
+ this.hasBegun = false;
25
28
  this.id = taskParams.id;
26
29
  if (taskParams.bytesUploaded)
27
30
  this.bytesUploaded = taskParams.bytesUploaded;
28
31
  if (taskParams.bytesTotal)
29
32
  this.bytesTotal = taskParams.bytesTotal;
30
33
  this.metadata = (_a = this.tryParseJson(taskParams.metadata)) !== null && _a !== void 0 ? _a : {};
34
+ // A restored task that already has data has begun; so has one this replaces
35
+ this.hasBegun = (originalTask instanceof UploadTask && originalTask.hasBegun) || this.bytesUploaded > 0;
31
36
  if (originalTask) {
32
37
  this.beginHandler = originalTask.beginHandler;
33
38
  this.progressHandler = originalTask.progressHandler;
@@ -61,14 +66,24 @@ class UploadTask {
61
66
  return this;
62
67
  }
63
68
  // event listeners
69
+ // Native can still deliver begin or progress that was in flight when the app paused
70
+ // or stopped the upload, or when it ended. Those must not run handlers or change state.
71
+ isInactive() {
72
+ return this.state === 'PAUSED' || this.state === 'STOPPED' || this.state === 'DONE' || this.state === 'FAILED';
73
+ }
64
74
  onBegin(params) {
65
75
  var _a;
76
+ if (this.isInactive() || this.hasBegun)
77
+ return;
78
+ this.hasBegun = true;
66
79
  this.state = 'UPLOADING';
67
80
  this.bytesTotal = params.expectedBytes;
68
81
  (_a = this.beginHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
69
82
  }
70
83
  onProgress(params) {
71
84
  var _a;
85
+ if (this.isInactive())
86
+ return;
72
87
  this.bytesUploaded = params.bytesUploaded;
73
88
  this.bytesTotal = params.bytesTotal;
74
89
  (_a = this.progressHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
@@ -83,6 +98,7 @@ class UploadTask {
83
98
  onError(params) {
84
99
  var _a;
85
100
  this.state = 'FAILED';
101
+ this.errorCode = params.errorCode;
86
102
  (_a = this.errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, params);
87
103
  }
88
104
  // methods
@@ -137,7 +153,7 @@ class UploadTask {
137
153
  method: (_d = this.uploadParams.method) !== null && _d !== void 0 ? _d : 'POST',
138
154
  headers: this.headersToUnsafeObject(this.uploadParams.headers),
139
155
  isAllowedOverRoaming: (_e = this.uploadParams.isAllowedOverRoaming) !== null && _e !== void 0 ? _e : false,
140
- isAllowedOverMetered: (_f = this.uploadParams.isAllowedOverMetered) !== null && _f !== void 0 ? _f : false,
156
+ isAllowedOverMetered: (_f = this.uploadParams.isAllowedOverMetered) !== null && _f !== void 0 ? _f : config_1.config.allowsCellularAccess,
141
157
  });
142
158
  }
143
159
  async stop() {
package/lib/index.d.ts CHANGED
@@ -10,7 +10,7 @@ export declare function cleanup(): void;
10
10
  export declare function setConfig({ headers, progressInterval, progressMinBytes, isLogsEnabled, logCallback, maxParallelDownloads, allowsCellularAccess, showNotificationsEnabled, showCompletionNotification, showCancelAction, notificationsGrouping, iosDataProtection, }: Config): void;
11
11
  export declare const getExistingDownloadTasks: () => Promise<DownloadTask[]>;
12
12
  export declare const completeHandler: (jobId: string) => Promise<void> | undefined;
13
- export declare function createDownloadTask({ isAllowedOverRoaming, isAllowedOverMetered, metadata, ...rest }: TaskInfo & DownloadParams): DownloadTask;
13
+ export declare function createDownloadTask({ isAllowedOverRoaming, isAllowedOverMetered, metadata, groupId, groupName, notificationTitle, ...rest }: TaskInfo & DownloadParams): DownloadTask;
14
14
  export declare const getExistingUploadTasks: () => Promise<UploadTask[]>;
15
15
  export declare function createUploadTask({ isAllowedOverRoaming, isAllowedOverMetered, metadata, ...rest }: UploadTaskInfo & UploadParams): UploadTask;
16
16
  export declare const directories: {
package/lib/index.js CHANGED
@@ -24,10 +24,11 @@ let isInitialized = false;
24
24
  * This prevents issues with module loading before React Native's bridge is ready.
25
25
  */
26
26
  function ensureNativeModuleInitialized() {
27
+ var _a;
27
28
  if (isInitialized && RNBackgroundDownloader != null)
28
29
  return RNBackgroundDownloader;
29
30
  // Try TurboModules first
30
- turboModule = react_native_1.TurboModuleRegistry.get('RNBackgroundDownloader');
31
+ turboModule = (_a = react_native_1.TurboModuleRegistry.get('RNBackgroundDownloader')) !== null && _a !== void 0 ? _a : null;
31
32
  // Check if iOS new architecture event emitters are available
32
33
  // On Android, we always use NativeEventEmitter because Android uses RCTDeviceEventEmitter
33
34
  isIOSNewArchitecture = react_native_1.Platform.OS === 'ios' && turboModule != null && typeof turboModule.onDownloadBegin === 'function';
@@ -80,13 +81,12 @@ function cleanup() {
80
81
  tasks_1.uploadTasksMap.clear();
81
82
  }
82
83
  function initializeEventListeners() {
83
- var _a, _b, _c, _d;
84
84
  if (eventListenersInitialized)
85
85
  return;
86
86
  eventListenersInitialized = true;
87
87
  if (isIOSNewArchitecture && turboModule) {
88
88
  // iOS new architecture: use EventEmitter from TurboModule spec
89
- turboModule.onDownloadBegin((data) => {
89
+ eventSubscriptions.push(turboModule.onDownloadBegin((data) => {
90
90
  const { id, ...rest } = data;
91
91
  (0, logger_1.log)('downloadBegin', id, rest);
92
92
  const task = tasks_1.tasksMap.get(id);
@@ -95,8 +95,8 @@ function initializeEventListeners() {
95
95
  return;
96
96
  }
97
97
  task.onBegin(rest);
98
- });
99
- turboModule.onDownloadProgress((events) => {
98
+ }));
99
+ eventSubscriptions.push(turboModule.onDownloadProgress((events) => {
100
100
  (0, logger_1.log)('downloadProgress', events);
101
101
  for (const event of events) {
102
102
  const { id, ...rest } = event;
@@ -104,8 +104,8 @@ function initializeEventListeners() {
104
104
  if (task)
105
105
  task.onProgress(rest);
106
106
  }
107
- });
108
- turboModule.onDownloadComplete((data) => {
107
+ }));
108
+ eventSubscriptions.push(turboModule.onDownloadComplete((data) => {
109
109
  const { id, ...rest } = data;
110
110
  (0, logger_1.log)('downloadComplete', id, rest);
111
111
  const task = tasks_1.tasksMap.get(id);
@@ -114,8 +114,8 @@ function initializeEventListeners() {
114
114
  else
115
115
  task.onDone(rest);
116
116
  tasks_1.tasksMap.delete(id);
117
- });
118
- turboModule.onDownloadFailed((data) => {
117
+ }));
118
+ eventSubscriptions.push(turboModule.onDownloadFailed((data) => {
119
119
  const { id, ...rest } = data;
120
120
  (0, logger_1.log)('downloadFailed', id, rest);
121
121
  const task = tasks_1.tasksMap.get(id);
@@ -124,10 +124,10 @@ function initializeEventListeners() {
124
124
  else
125
125
  task.onError(rest);
126
126
  tasks_1.tasksMap.delete(id);
127
- });
127
+ }));
128
128
  // Upload events for new architecture (optional - may not exist in all versions)
129
129
  if (typeof turboModule.onUploadBegin === 'function') {
130
- (_a = turboModule.onUploadBegin) === null || _a === void 0 ? void 0 : _a.call(turboModule, (data) => {
130
+ eventSubscriptions.push(turboModule.onUploadBegin((data) => {
131
131
  const { id, ...rest } = data;
132
132
  (0, logger_1.log)('uploadBegin', id, rest);
133
133
  const task = tasks_1.uploadTasksMap.get(id);
@@ -136,8 +136,8 @@ function initializeEventListeners() {
136
136
  return;
137
137
  }
138
138
  task.onBegin(rest);
139
- });
140
- (_b = turboModule.onUploadProgress) === null || _b === void 0 ? void 0 : _b.call(turboModule, (events) => {
139
+ }));
140
+ eventSubscriptions.push(turboModule.onUploadProgress((events) => {
141
141
  (0, logger_1.log)('uploadProgress', events);
142
142
  for (const event of events) {
143
143
  const { id, ...rest } = event;
@@ -145,8 +145,8 @@ function initializeEventListeners() {
145
145
  if (task)
146
146
  task.onProgress(rest);
147
147
  }
148
- });
149
- (_c = turboModule.onUploadComplete) === null || _c === void 0 ? void 0 : _c.call(turboModule, (data) => {
148
+ }));
149
+ eventSubscriptions.push(turboModule.onUploadComplete((data) => {
150
150
  const { id, ...rest } = data;
151
151
  (0, logger_1.log)('uploadComplete', id, rest);
152
152
  const task = tasks_1.uploadTasksMap.get(id);
@@ -155,8 +155,8 @@ function initializeEventListeners() {
155
155
  else
156
156
  task.onDone(rest);
157
157
  tasks_1.uploadTasksMap.delete(id);
158
- });
159
- (_d = turboModule.onUploadFailed) === null || _d === void 0 ? void 0 : _d.call(turboModule, (data) => {
158
+ }));
159
+ eventSubscriptions.push(turboModule.onUploadFailed((data) => {
160
160
  const { id, ...rest } = data;
161
161
  (0, logger_1.log)('uploadFailed', id, rest);
162
162
  const task = tasks_1.uploadTasksMap.get(id);
@@ -165,7 +165,7 @@ function initializeEventListeners() {
165
165
  else
166
166
  task.onError(rest);
167
167
  tasks_1.uploadTasksMap.delete(id);
168
- });
168
+ }));
169
169
  }
170
170
  }
171
171
  else {
@@ -261,19 +261,23 @@ function initializeEventListeners() {
261
261
  }
262
262
  // Event listeners are now initialized lazily when ensureNativeModuleInitialized() is called
263
263
  // This ensures the bridge is ready before any native module access
264
- function setConfig({ headers = {}, progressInterval = config_1.DEFAULT_PROGRESS_INTERVAL, progressMinBytes = config_1.DEFAULT_PROGRESS_MIN_BYTES, isLogsEnabled = false, logCallback, maxParallelDownloads, allowsCellularAccess, showNotificationsEnabled, showCompletionNotification, showCancelAction, notificationsGrouping, iosDataProtection, }) {
264
+ // Only the options passed are changed; the rest keep their current values
265
+ function setConfig({ headers, progressInterval, progressMinBytes, isLogsEnabled, logCallback, maxParallelDownloads, allowsCellularAccess, showNotificationsEnabled, showCompletionNotification, showCancelAction, notificationsGrouping, iosDataProtection, }) {
265
266
  var _a, _b, _c, _d, _e;
266
- config_1.config.headers = headers;
267
+ if (headers !== undefined)
268
+ config_1.config.headers = headers;
267
269
  if (iosDataProtection !== undefined)
268
270
  config_1.config.iosDataProtection = iosDataProtection;
269
- if (progressInterval >= MIN_PROGRESS_INTERVAL)
270
- config_1.config.progressInterval = progressInterval;
271
- else
272
- console.warn(`[RNBackgroundDownloader] progressInterval must be a number >= ${MIN_PROGRESS_INTERVAL}. You passed ${progressInterval}`);
273
- if (progressMinBytes >= 0)
274
- config_1.config.progressMinBytes = progressMinBytes;
275
- else
276
- console.warn(`[RNBackgroundDownloader] progressMinBytes must be a number >= 0. You passed ${progressMinBytes}`);
271
+ if (progressInterval !== undefined)
272
+ if (progressInterval >= MIN_PROGRESS_INTERVAL)
273
+ config_1.config.progressInterval = progressInterval;
274
+ else
275
+ console.warn(`[RNBackgroundDownloader] progressInterval must be a number >= ${MIN_PROGRESS_INTERVAL}. You passed ${progressInterval}`);
276
+ if (progressMinBytes !== undefined)
277
+ if (progressMinBytes >= 0)
278
+ config_1.config.progressMinBytes = progressMinBytes;
279
+ else
280
+ console.warn(`[RNBackgroundDownloader] progressMinBytes must be a number >= 0. You passed ${progressMinBytes}`);
277
281
  if (maxParallelDownloads !== undefined)
278
282
  if (maxParallelDownloads >= 1)
279
283
  config_1.config.maxParallelDownloads = maxParallelDownloads;
@@ -299,12 +303,14 @@ function setConfig({ headers = {}, progressInterval = config_1.DEFAULT_PROGRESS_
299
303
  ...notificationsGrouping.texts,
300
304
  },
301
305
  };
302
- config_1.config.isLogsEnabled = isLogsEnabled;
303
- config_1.config.logCallback = logCallback;
306
+ if (isLogsEnabled !== undefined)
307
+ config_1.config.isLogsEnabled = isLogsEnabled;
308
+ if (logCallback !== undefined)
309
+ config_1.config.logCallback = logCallback;
304
310
  // Notify native side about configuration changes
305
311
  try {
306
312
  const nativeModule = ensureNativeModuleInitialized();
307
- if (nativeModule.setLogsEnabled)
313
+ if (nativeModule.setLogsEnabled && isLogsEnabled !== undefined)
308
314
  nativeModule.setLogsEnabled(isLogsEnabled);
309
315
  // Only call native methods if config was successfully updated
310
316
  if (nativeModule.setMaxParallelDownloads && maxParallelDownloads !== undefined && maxParallelDownloads >= 1)
@@ -362,7 +368,8 @@ const getExistingDownloadTasks = async () => {
362
368
  task.state = 'PAUSED';
363
369
  }
364
370
  else {
365
- task.stop();
371
+ // Not awaited: the task is dropped either way, so a failed stop isn't actionable
372
+ task.stop().catch(() => { });
366
373
  return undefined;
367
374
  }
368
375
  break;
@@ -391,16 +398,20 @@ const completeHandler = (jobId) => {
391
398
  return nativeModule.completeHandler(jobId);
392
399
  };
393
400
  exports.completeHandler = completeHandler;
394
- function createDownloadTask({ isAllowedOverRoaming = true, isAllowedOverMetered = true, metadata, ...rest }) {
401
+ function createDownloadTask({ isAllowedOverRoaming = true,
402
+ // Follows setConfig({ allowsCellularAccess }) unless the task sets its own
403
+ isAllowedOverMetered = config_1.config.allowsCellularAccess, metadata, groupId, groupName, notificationTitle, ...rest }) {
395
404
  // Ensure native module and event listeners are initialized before creating tasks
396
405
  ensureNativeModuleInitialized();
397
406
  if (!rest.id || !rest.url || !rest.destination)
398
407
  throw new Error('[RNBackgroundDownloader] id, url and destination are required');
399
408
  rest.headers = { ...config_1.config.headers, ...rest.headers };
400
409
  rest.destination = rest.destination.replace('file://', '');
410
+ // Native reads the notification fields from metadata only
411
+ const notificationFields = Object.fromEntries(Object.entries({ groupId, groupName, notificationTitle }).filter(([, value]) => value !== undefined));
401
412
  const task = new DownloadTask_1.DownloadTask({
402
413
  id: rest.id,
403
- metadata,
414
+ metadata: Object.keys(notificationFields).length > 0 ? { ...metadata, ...notificationFields } : metadata,
404
415
  });
405
416
  task.setDownloadParams({
406
417
  isAllowedOverRoaming,
@@ -450,7 +461,8 @@ const getExistingUploadTasks = async () => {
450
461
  task.state = 'PAUSED';
451
462
  }
452
463
  else {
453
- task.stop();
464
+ // Not awaited: the task is dropped either way, so a failed stop isn't actionable
465
+ task.stop().catch(() => { });
454
466
  return undefined;
455
467
  }
456
468
  break;
@@ -470,7 +482,9 @@ const getExistingUploadTasks = async () => {
470
482
  return uploadTasks;
471
483
  };
472
484
  exports.getExistingUploadTasks = getExistingUploadTasks;
473
- function createUploadTask({ isAllowedOverRoaming = true, isAllowedOverMetered = true, metadata, ...rest }) {
485
+ function createUploadTask({ isAllowedOverRoaming = true,
486
+ // Follows setConfig({ allowsCellularAccess }) unless the task sets its own
487
+ isAllowedOverMetered = config_1.config.allowsCellularAccess, metadata, ...rest }) {
474
488
  // Ensure native module and event listeners are initialized before creating tasks
475
489
  ensureNativeModuleInitialized();
476
490
  if (!rest.id || !rest.url || !rest.source)
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.7.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
  })