@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
@@ -3,6 +3,7 @@
3
3
  #import "RNBGDUploadTaskConfig.h"
4
4
  #import <MMKV/MMKV.h>
5
5
  #import <React/RCTBridge.h>
6
+ #import <React/RCTUtils.h>
6
7
 
7
8
  #ifdef RCT_NEW_ARCH_ENABLED
8
9
  #import <RNBackgroundDownloaderSpec/RNBackgroundDownloaderSpec.h>
@@ -11,8 +12,11 @@
11
12
 
12
13
  #define ID_TO_CONFIG_MAP_KEY @"com.eko.bgdownloadidmap"
13
14
  #define ID_TO_UPLOAD_CONFIG_MAP_KEY @"com.eko.bguploadidmap"
15
+ // Finished uploads kept until JS has their response, by upload id
16
+ #define FINISHED_UPLOADS_KEY @"com.eko.bguploadfinished"
14
17
  #define PROGRESS_INTERVAL_KEY @"progressInterval"
15
18
  #define PROGRESS_MIN_BYTES_KEY @"progressMinBytes"
19
+ #define MAX_PARALLEL_DOWNLOADS_KEY @"maxParallelDownloads"
16
20
  // Persisted map of downloads whose finished file could not be moved to its destination
17
21
  // yet because the device was locked (Data Protection). The move is retried when protected
18
22
  // data becomes available / on next launch. See issue #101.
@@ -26,7 +30,19 @@ static const NSTimeInterval kResourceTimeoutSeconds = 60 * 60 * 24; // 1 day -
26
30
  // Progress reporting constants
27
31
  static const NSTimeInterval kTaskReconciliationDelay = 0.1; // Delay to allow session tasks to stabilize
28
32
  static const float kProgressReportThreshold = 0.01f; // Report progress every 1% change
29
- static const NSTimeInterval kCompletionHandlerTimeout = 30.0; // Timeout for completion handler (30 seconds)
33
+ // Fallback for the background completion handler; iOS gives a background launch about 30 s
34
+ static const NSTimeInterval kCompletionHandlerTimeout = 25.0;
35
+ static const NSTimeInterval kSessionInvalidationTimeout = 5.0; // Max wait for a replaced session to go away
36
+ // A download that gets no data for this long while the app is in the foreground is
37
+ // restarted from where it stopped: the system can take many minutes to do it itself
38
+ static const NSTimeInterval kStallTimeout = 20.0;
39
+ static const NSTimeInterval kStallCheckInterval = 5.0;
40
+ // Times in a row a download cut off by the network continues from its resume data
41
+ static const NSInteger kMaxNetworkResumes = 5;
42
+ // Upload response bodies past this are cut off before they reach JS
43
+ static const NSUInteger kMaxUploadResponseBytes = 1024 * 1024;
44
+ // Chunk size when copying an upload part out of the source file
45
+ static const NSUInteger kPartCopyChunkBytes = 4 * 1024 * 1024;
30
46
 
31
47
  // DLog accepts taskId as first parameter to help debugging
32
48
  // Only logs if isLogsEnabled is true (works in both DEBUG and RELEASE builds)
@@ -40,7 +56,61 @@ static const NSTimeInterval kCompletionHandlerTimeout = 30.0; // Timeout for com
40
56
  #define DLogStatic( taskId, s, ... ) do { } while(0)
41
57
  #endif
42
58
 
59
+ // The background session's delegate. A JS reload creates a new module instance, but the
60
+ // session must outlive the old one: invalidating it cancels every transfer in it, and its
61
+ // delegate can't be changed. So the delegate is this object, which hands every call to
62
+ // the newest module instance.
63
+ @interface RNBGDSessionDelegate : NSObject
64
+ @property (atomic, strong) RNBackgroundDownloader *target;
65
+ + (instancetype)shared;
66
+ @end
67
+
68
+ @implementation RNBGDSessionDelegate
69
+
70
+ + (instancetype)shared
71
+ {
72
+ static RNBGDSessionDelegate *shared;
73
+ static dispatch_once_t once;
74
+ dispatch_once(&once, ^{
75
+ shared = [RNBGDSessionDelegate new];
76
+ });
77
+ return shared;
78
+ }
79
+
80
+ - (BOOL)respondsToSelector:(SEL)selector
81
+ {
82
+ return [super respondsToSelector:selector] || [RNBackgroundDownloader instancesRespondToSelector:selector];
83
+ }
84
+
85
+ - (id)forwardingTargetForSelector:(SEL)selector
86
+ {
87
+ return self.target;
88
+ }
89
+
90
+ @end
91
+
92
+ // The session every module instance uses, guarded by the RNBGDSessionDelegate class
93
+ static NSURLSession *sharedSession;
94
+
95
+ // The system's completion handler for a background launch, and what it waits for. Only
96
+ // touched on the main queue.
43
97
  static CompletionHandler storedCompletionHandler;
98
+ // Set when the session has delivered every event of the background launch
99
+ static BOOL backgroundEventsFinished = NO;
100
+ // Tasks whose done or failed event was sent during the launch, not yet passed to completeHandler
101
+ static NSMutableSet<NSString *> *idsAwaitingCompleteHandler;
102
+
103
+ // Calls the completion handler once the session has delivered its events and JS has
104
+ // handled every task that ended in them, so the app isn't suspended mid-way. Main queue.
105
+ static void callCompletionHandlerIfDone(void) {
106
+ if (storedCompletionHandler == nil || !backgroundEventsFinished || idsAwaitingCompleteHandler.count > 0) {
107
+ return;
108
+ }
109
+ CompletionHandler handler = storedCompletionHandler;
110
+ storedCompletionHandler = nil;
111
+ backgroundEventsFinished = NO;
112
+ handler();
113
+ }
44
114
 
45
115
  @implementation RNBackgroundDownloader {
46
116
  MMKV *mmkv;
@@ -69,6 +139,20 @@ static CompletionHandler storedCompletionHandler;
69
139
  NSMutableArray<dispatch_block_t> *pendingDownloads;
70
140
  // Controls whether debug logs are sent to JS
71
141
  BOOL isLogsEnabled;
142
+ // A session being invalidated to be replaced with one with a new configuration, and
143
+ // the signal that it's gone (see -lazyRegisterSession)
144
+ NSURLSession *replacedSession;
145
+ dispatch_semaphore_t replacedSessionInvalidated;
146
+ // When each download last received data, for the stall check
147
+ NSMutableDictionary<NSString *, NSDate *> *idToLastDataAt;
148
+ // Downloads being restarted after a stall; their cancel isn't a pause or a failure
149
+ NSMutableSet<NSString *> *idsBeingRestarted;
150
+ // Times each download continued after the network cut it off, since it last got data
151
+ NSMutableDictionary<NSString *, NSNumber *> *idToNetworkResumeCount;
152
+ NSTimeInterval stallTimeout;
153
+ BOOL isAppActive;
154
+ BOOL hasReconciledTasks;
155
+ dispatch_source_t stallTimer;
72
156
 
73
157
  // Downloads that finished but whose file couldn't be moved to its destination because
74
158
  // the device was locked. Keyed by configId -> staging/destination info. Retried on
@@ -80,6 +164,10 @@ static CompletionHandler storedCompletionHandler;
80
164
  // This prevents crashes (std::bad_function_call / SIGABRT) when NSURLSession delegate
81
165
  // callbacks fire before JS has registered event listeners.
82
166
  NSMutableArray<NSDictionary *> *pendingEmitEvents;
167
+ #else
168
+ // Events waiting for the bridge, in the order they were sent (see -sendEventWithName:body:)
169
+ NSMutableArray<NSDictionary *> *pendingBridgeEvents;
170
+ int bridgeRetryCount;
83
171
  #endif
84
172
 
85
173
  // Upload-specific instance variables
@@ -90,6 +178,15 @@ static CompletionHandler storedCompletionHandler;
90
178
  NSMutableDictionary<NSString *, NSNumber *> *idToUploadLastBytesMap;
91
179
  NSMutableSet<NSString *> *idsToUploadPauseSet;
92
180
  NSDate *lastUploadProgressReportedAt;
181
+ // Response bodies, per session task (the parts of an upload run at the same time)
182
+ NSMutableDictionary<NSNumber *, NSMutableData *> *uploadResponseDataByTask;
183
+ // Bytes each running part task has sent; an upload with parts reports their sum
184
+ NSMutableDictionary<NSNumber *, NSNumber *> *uploadPartBytesSent;
185
+ // The running part tasks of each upload with partUrls
186
+ NSMutableDictionary<NSString *, NSMutableArray<NSURLSessionUploadTask *> *> *idToUploadPartTasks;
187
+ // Finished uploads kept until JS has their response (persisted): an upload can finish
188
+ // while the app isn't running, and an S3 upload needs its parts' ETags to complete
189
+ NSMutableDictionary<NSString *, RNBGDUploadTaskConfig *> *finishedUploads;
93
190
  }
94
191
 
95
192
  RCT_EXPORT_MODULE();
@@ -160,25 +257,54 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
160
257
  // Old architecture override to ensure events are sent
161
258
  // Check if bridge is valid and loaded before sending events
162
259
  - (void)sendEventWithName:(NSString *)eventName body:(id)body {
163
- [self sendEventWithName:eventName body:body retryCount:0];
164
- }
165
-
166
- - (void)sendEventWithName:(NSString *)eventName body:(id)body retryCount:(int)retryCount {
167
- // Check if bridge is available and loaded
168
- // This prevents crashes on first app install when events fire before JS is ready
169
- if (self.bridge == nil || !self.bridge.isValid) {
170
- if (retryCount < kMaxEventRetries) {
171
- DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready (attempt %d), queueing event: %@", retryCount + 1, eventName);
172
- // Queue the event to be sent when bridge becomes available
173
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
174
- [self sendEventWithName:eventName body:body retryCount:retryCount + 1];
175
- });
176
- } else {
177
- DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready after %d attempts, dropping event: %@", kMaxEventRetries, eventName);
260
+ [self trackTerminalEvent:eventName body:body];
261
+ @synchronized (pendingBridgeEvents) {
262
+ // While events wait for the bridge, later ones wait behind them, so JS gets them in
263
+ // order (e.g. begin before progress, progress before complete)
264
+ if (pendingBridgeEvents.count > 0 || ![self isBridgeReady]) {
265
+ DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready, queueing event: %@", eventName);
266
+ [pendingBridgeEvents addObject:@{@"name": eventName, @"body": body ?: [NSNull null]}];
267
+ if (pendingBridgeEvents.count == 1) {
268
+ bridgeRetryCount = 0;
269
+ [self scheduleBridgeEventsFlush];
270
+ }
271
+ return;
178
272
  }
179
- return;
273
+ [super sendEventWithName:eventName body:body];
274
+ }
275
+ }
276
+
277
+ // This prevents crashes on first app install when events fire before JS is ready
278
+ - (BOOL)isBridgeReady {
279
+ return self.bridge != nil && self.bridge.isValid;
280
+ }
281
+
282
+ - (void)scheduleBridgeEventsFlush {
283
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
284
+ [self flushBridgeEvents];
285
+ });
286
+ }
287
+
288
+ - (void)flushBridgeEvents {
289
+ @synchronized (pendingBridgeEvents) {
290
+ if (pendingBridgeEvents.count == 0) {
291
+ return;
292
+ }
293
+ if (![self isBridgeReady]) {
294
+ if (++bridgeRetryCount < kMaxEventRetries) {
295
+ [self scheduleBridgeEventsFlush];
296
+ } else {
297
+ DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready after %d attempts, dropping %lu events", kMaxEventRetries, (unsigned long)pendingBridgeEvents.count);
298
+ [pendingBridgeEvents removeAllObjects];
299
+ }
300
+ return;
301
+ }
302
+ for (NSDictionary *event in pendingBridgeEvents) {
303
+ id body = event[@"body"];
304
+ [super sendEventWithName:event[@"name"] body:body == [NSNull null] ? nil : body];
305
+ }
306
+ [pendingBridgeEvents removeAllObjects];
180
307
  }
181
- [super sendEventWithName:eventName body:body];
182
308
  }
183
309
  #endif
184
310
 
@@ -217,7 +343,9 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
217
343
  NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
218
344
  NSString *sessionIdentifier = [bundleIdentifier stringByAppendingString:@".backgrounddownloadtask"];
219
345
  sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier];
220
- sessionConfig.HTTPMaximumConnectionsPerHost = kMaxConnectionsPerHost;
346
+ // Saved by setMaxParallelDownloads, so the session is created with it on launch
347
+ NSInteger savedMaxConnections = (NSInteger)[mmkv getInt64ForKey:MAX_PARALLEL_DOWNLOADS_KEY];
348
+ sessionConfig.HTTPMaximumConnectionsPerHost = savedMaxConnections >= 1 ? savedMaxConnections : kMaxConnectionsPerHost;
221
349
  sessionConfig.timeoutIntervalForRequest = kRequestTimeoutSeconds;
222
350
  sessionConfig.timeoutIntervalForResource = kResourceTimeoutSeconds;
223
351
  sessionConfig.discretionary = NO;
@@ -225,6 +353,10 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
225
353
  // These APIs are available since our minimum iOS version (15.1)
226
354
  sessionConfig.shouldUseExtendedBackgroundIdleMode = YES;
227
355
  sessionConfig.allowsExpensiveNetworkAccess = YES;
356
+ // Cellular is restricted per request (isAllowedOverMetered, which defaults to the
357
+ // global setConfig value in JS). The session must stay open: a request can only
358
+ // reliably narrow its session's access, not widen it.
359
+ sessionConfig.allowsCellularAccess = YES;
228
360
 
229
361
  sharedLock = [NSNumber numberWithInt:1];
230
362
 
@@ -248,6 +380,12 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
248
380
  idToUpdatedHeadersMap = [[NSMutableDictionary alloc] init];
249
381
  isSessionActivated = NO;
250
382
  pendingDownloads = [[NSMutableArray alloc] init];
383
+ idToLastDataAt = [[NSMutableDictionary alloc] init];
384
+ idsBeingRestarted = [[NSMutableSet alloc] init];
385
+ idToNetworkResumeCount = [[NSMutableDictionary alloc] init];
386
+ stallTimeout = kStallTimeout;
387
+ isAppActive = YES;
388
+ [self startStallTimer];
251
389
 
252
390
  // Restore any downloads whose file move was deferred because the device was locked
253
391
  NSData *pendingMovesData = [mmkv getDataForKey:PENDING_MOVES_MAP_KEY];
@@ -256,6 +394,8 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
256
394
 
257
395
  #ifdef RCT_NEW_ARCH_ENABLED
258
396
  pendingEmitEvents = [[NSMutableArray alloc] init];
397
+ #else
398
+ pendingBridgeEvents = [[NSMutableArray alloc] init];
259
399
  #endif
260
400
 
261
401
  // Initialize upload-specific data structures
@@ -269,6 +409,12 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
269
409
  idToUploadLastBytesMap = [[NSMutableDictionary alloc] init];
270
410
  idsToUploadPauseSet = [[NSMutableSet alloc] init];
271
411
  lastUploadProgressReportedAt = [[NSDate alloc] init];
412
+ uploadResponseDataByTask = [[NSMutableDictionary alloc] init];
413
+ uploadPartBytesSent = [[NSMutableDictionary alloc] init];
414
+ idToUploadPartTasks = [[NSMutableDictionary alloc] init];
415
+ NSData *finishedUploadsData = [mmkv getDataForKey:FINISHED_UPLOADS_KEY];
416
+ NSMutableDictionary *finishedUploadsDecoded = finishedUploadsData != nil ? [self deserializeUploadConfig:finishedUploadsData] : nil;
417
+ finishedUploads = finishedUploadsDecoded != nil ? finishedUploadsDecoded : [[NSMutableDictionary alloc] init];
272
418
 
273
419
  [self registerBridgeListener];
274
420
 
@@ -283,23 +429,48 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
283
429
  return self;
284
430
  }
285
431
 
432
+ // The session isn't invalidated here or on reload: that would cancel every transfer. The
433
+ // next module instance takes it over (see -lazyRegisterSession).
286
434
  - (void)dealloc {
287
435
  DLog(nil, @"[RNBackgroundDownloader] - [dealloc]");
288
- [self unregisterSession];
289
436
  [self unregisterBridgeListener];
290
437
  }
291
438
 
292
439
  - (void)handleBridgeHotReload:(NSNotification *) note {
293
440
  DLog(nil, @"[RNBackgroundDownloader] - [handleBridgeHotReload]");
294
- [self unregisterSession];
295
441
  [self unregisterBridgeListener];
296
442
  }
297
443
 
444
+ // The shared session, created if there's none yet. The session's events go to this
445
+ // instance from now on. Must hold sharedLock.
446
+ - (NSURLSession *)attachSession {
447
+ @synchronized ([RNBGDSessionDelegate class]) {
448
+ // Set first: events can arrive as soon as the session exists, and this instance's
449
+ // state is loaded by now
450
+ [RNBGDSessionDelegate shared].target = self;
451
+ if (sharedSession == nil) {
452
+ sharedSession = [NSURLSession sessionWithConfiguration:sessionConfig
453
+ delegate:(id<NSURLSessionDelegate>)[RNBGDSessionDelegate shared]
454
+ delegateQueue:nil];
455
+ }
456
+ return sharedSession;
457
+ }
458
+ }
459
+
298
460
  - (void)lazyRegisterSession {
299
461
  DLog(nil, @"[RNBackgroundDownloader] - [lazyRegisterSession]");
300
462
  [self sendDebugLog:@"lazyRegisterSession called" taskId:nil];
301
463
  @synchronized (sharedLock) {
302
464
  if (urlSession == nil) {
465
+ if (replacedSession != nil) {
466
+ // A background session created while one with its identifier is still being
467
+ // invalidated is unusable, so wait for -URLSession:didBecomeInvalidWithError:.
468
+ // The replaced session is idle, so nothing on its queue needs this lock.
469
+ [self sendDebugLog:@"lazyRegisterSession: waiting for the replaced session to be invalidated" taskId:nil];
470
+ dispatch_semaphore_wait(replacedSessionInvalidated, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kSessionInvalidationTimeout * NSEC_PER_SEC)));
471
+ replacedSession = nil;
472
+ replacedSessionInvalidated = nil;
473
+ }
303
474
  [self sendDebugLog:@"lazyRegisterSession: creating new session" taskId:nil];
304
475
  // +sessionWithConfiguration: can raise NSInvalidArgumentException (the same
305
476
  // failure mode as issues #161/#170). This is the one choke point every entry
@@ -308,7 +479,7 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
308
479
  // thread. Callers already degrade on a nil session (download queues, the
309
480
  // getExisting* methods reject with ERR_SESSION_NIL).
310
481
  @try {
311
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
482
+ urlSession = [self attachSession];
312
483
  // Activate the session by calling getTasksWithCompletionHandler
313
484
  // This forces iOS to fully initialize the background session
314
485
  // On fresh installs, the session may not be ready to process tasks immediately
@@ -347,14 +518,27 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
347
518
  }];
348
519
  }
349
520
 
521
+ // Forgets the shared session, so the next -attachSession creates a new one
522
+ - (void)dropSharedSession:(NSURLSession *)session {
523
+ @synchronized ([RNBGDSessionDelegate class]) {
524
+ if (sharedSession == session) {
525
+ sharedSession = nil;
526
+ }
527
+ }
528
+ }
529
+
530
+ // Invalidates the session, cancelling everything in it. Only for replacing an idle one.
350
531
  - (void)unregisterSession {
351
532
  DLog(nil, @"[RNBackgroundDownloader] - [unregisterSession]");
352
- if (urlSession) {
353
- [urlSession invalidateAndCancel];
354
- urlSession = nil;
533
+ @synchronized (sharedLock) {
534
+ if (urlSession) {
535
+ [self dropSharedSession:urlSession];
536
+ [urlSession invalidateAndCancel];
537
+ urlSession = nil;
538
+ }
539
+ isSessionActivated = NO;
540
+ [pendingDownloads removeAllObjects];
355
541
  }
356
- isSessionActivated = NO;
357
- [pendingDownloads removeAllObjects];
358
542
  }
359
543
 
360
544
  - (void)registerBridgeListener {
@@ -372,6 +556,24 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
372
556
  name:RCTJavaScriptWillStartLoadingNotification
373
557
  object:nil];
374
558
 
559
+ // The stall check runs only while the app is in the foreground
560
+ [[NSNotificationCenter defaultCenter] addObserver:self
561
+ selector:@selector(handleAppActiveChange:)
562
+ name:UIApplicationDidBecomeActiveNotification
563
+ object:nil];
564
+ [[NSNotificationCenter defaultCenter] addObserver:self
565
+ selector:@selector(handleAppActiveChange:)
566
+ name:UIApplicationWillResignActiveNotification
567
+ object:nil];
568
+ dispatch_async(dispatch_get_main_queue(), ^{
569
+ UIApplication *application = RCTSharedApplication();
570
+ if (application != nil) {
571
+ @synchronized (self->sharedLock) {
572
+ self->isAppActive = application.applicationState == UIApplicationStateActive;
573
+ }
574
+ }
575
+ });
576
+
375
577
  // Finish any moves deferred while the device was locked, as soon as
376
578
  // protected data becomes available again (device unlocked). See #101.
377
579
  // Note: the ObjC constant has no "Notification" suffix (unlike most UIApplication ones).
@@ -383,6 +585,136 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
383
585
  }
384
586
  }
385
587
 
588
+ - (void)handleAppActiveChange:(NSNotification *)note {
589
+ @synchronized (sharedLock) {
590
+ isAppActive = [note.name isEqualToString:UIApplicationDidBecomeActiveNotification];
591
+ // Time in the background doesn't count as a stall
592
+ NSDate *now = [NSDate date];
593
+ for (NSString *identifier in [idToLastDataAt allKeys]) {
594
+ idToLastDataAt[identifier] = now;
595
+ }
596
+ }
597
+ }
598
+
599
+ - (void)startStallTimer {
600
+ __weak RNBackgroundDownloader *weakSelf = self;
601
+ stallTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
602
+ dispatch_source_set_timer(stallTimer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kStallCheckInterval * NSEC_PER_SEC)), (uint64_t)(kStallCheckInterval * NSEC_PER_SEC), NSEC_PER_SEC);
603
+ dispatch_source_set_event_handler(stallTimer, ^{
604
+ [weakSelf restartStalledDownloads];
605
+ });
606
+ dispatch_resume(stallTimer);
607
+ }
608
+
609
+ // The system retries a stalled background download on its own, but that can take many
610
+ // minutes. While the app is in the foreground, a download that has gone quiet is cancelled
611
+ // with resume data and continued in a new task, which opens a new connection.
612
+ - (void)restartStalledDownloads {
613
+ @synchronized (sharedLock) {
614
+ if (!isAppActive) {
615
+ return;
616
+ }
617
+ NSDate *now = [NSDate date];
618
+ for (NSString *identifier in [idToTaskMap allKeys]) {
619
+ NSURLSessionDownloadTask *task = idToTaskMap[identifier];
620
+ NSDate *lastDataAt = idToLastDataAt[identifier];
621
+ if (task.state != NSURLSessionTaskStateRunning || lastDataAt == nil
622
+ || [now timeIntervalSinceDate:lastDataAt] < stallTimeout
623
+ || [idsBeingRestarted containsObject:identifier] || [idsToPauseSet containsObject:identifier]
624
+ || ![self canResumeTask:task]) {
625
+ continue;
626
+ }
627
+ DLog(identifier, @"[RNBackgroundDownloader] - [restartStalledDownloads] no data for %.0f s, restarting", [now timeIntervalSinceDate:lastDataAt]);
628
+ [idsBeingRestarted addObject:identifier];
629
+ [task cancelByProducingResumeData:^(NSData *resumeData) {
630
+ @synchronized (self->sharedLock) {
631
+ [self->idsBeingRestarted removeObject:identifier];
632
+ RNBGDTaskConfig *taskConfig = self->taskToConfigMap[@(task.taskIdentifier)];
633
+ // Stopped meanwhile
634
+ if (self->idToTaskMap[identifier] != task || taskConfig == nil) {
635
+ return;
636
+ }
637
+ if ([self->idsToPauseSet containsObject:identifier]) {
638
+ // Paused meanwhile: keep the resume data as -pauseTaskInternal: does
639
+ if (resumeData != nil) {
640
+ self->idToResumeDataMap[identifier] = resumeData;
641
+ [self saveResumeData:resumeData forTaskId:identifier];
642
+ taskConfig.hasResumeData = YES;
643
+ }
644
+ taskConfig.state = NSURLSessionTaskStateCanceling;
645
+ taskConfig.errorCode = NSURLErrorCancelled;
646
+ [self->mmkv setData:[self serialize:self->taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
647
+ return;
648
+ }
649
+ if (![self continueTask:task config:taskConfig resumeData:resumeData]) {
650
+ [self removeTaskFromMap:task];
651
+ [self emitDownloadFailed:identifier error:@"the download stalled and couldn't be continued" errorCode:NSURLErrorTimedOut];
652
+ }
653
+ }
654
+ }];
655
+ }
656
+ }
657
+ }
658
+
659
+ // Resume data needs the server to take ranges and a validator to check the file didn't change
660
+ - (BOOL)canResumeTask:(NSURLSessionTask *)task {
661
+ if (task.countOfBytesReceived <= 0 || ![task.response isKindOfClass:[NSHTTPURLResponse class]]) {
662
+ return NO;
663
+ }
664
+ NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
665
+ NSString *acceptRanges = [response valueForHTTPHeaderField:@"Accept-Ranges"];
666
+ BOOL takesRanges = response.statusCode == 206 || [acceptRanges.lowercaseString containsString:@"bytes"];
667
+ BOOL hasValidator = [response valueForHTTPHeaderField:@"ETag"] != nil || [response valueForHTTPHeaderField:@"Last-Modified"] != nil;
668
+ return takesRanges && hasValidator;
669
+ }
670
+
671
+ // Continues a download from resume data in a new task with the same config. Must hold
672
+ // sharedLock. NO if there's nothing to continue from.
673
+ - (BOOL)continueTask:(NSURLSessionTask *)oldTask config:(RNBGDTaskConfig *)taskConfig resumeData:(NSData *)resumeData {
674
+ if (resumeData == nil) {
675
+ return NO;
676
+ }
677
+ NSURLSessionDownloadTask *newTask = nil;
678
+ @try {
679
+ newTask = [urlSession downloadTaskWithResumeData:resumeData];
680
+ } @catch (NSException *exception) {
681
+ DLog(taskConfig.id, @"[RNBackgroundDownloader] - [continueTask] error: %@", exception.reason);
682
+ }
683
+ if (newTask == nil) {
684
+ return NO;
685
+ }
686
+ [taskToConfigMap removeObjectForKey:@(oldTask.taskIdentifier)];
687
+ taskConfig.state = NSURLSessionTaskStateRunning;
688
+ taskConfig.errorCode = 0;
689
+ taskToConfigMap[@(newTask.taskIdentifier)] = taskConfig;
690
+ [mmkv setData:[self serialize:taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
691
+ idToTaskMap[taskConfig.id] = newTask;
692
+ idToLastDataAt[taskConfig.id] = [NSDate date];
693
+ [newTask resume];
694
+ return YES;
695
+ }
696
+
697
+ - (BOOL)isNetworkFailure:(NSError *)error {
698
+ if (![error.domain isEqualToString:NSURLErrorDomain]) {
699
+ return NO;
700
+ }
701
+ switch (error.code) {
702
+ case NSURLErrorTimedOut:
703
+ case NSURLErrorNetworkConnectionLost:
704
+ case NSURLErrorNotConnectedToInternet:
705
+ case NSURLErrorCannotConnectToHost:
706
+ case NSURLErrorCannotFindHost:
707
+ case NSURLErrorDNSLookupFailed:
708
+ case NSURLErrorInternationalRoamingOff:
709
+ case NSURLErrorCallIsActive:
710
+ case NSURLErrorDataNotAllowed:
711
+ case NSURLErrorBackgroundSessionWasDisconnected:
712
+ return YES;
713
+ default:
714
+ return NO;
715
+ }
716
+ }
717
+
386
718
  - (void)handleProtectedDataAvailable:(NSNotification *) note {
387
719
  DLog(nil, @"[RNBackgroundDownloader] - [handleProtectedDataAvailable]");
388
720
  [self processPendingMoves];
@@ -434,8 +766,15 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
434
766
  [self -> idToTaskMap removeObjectForKey:taskConfig.id];
435
767
  [idToPercentMap removeObjectForKey:taskConfig.id];
436
768
  [idToLastBytesMap removeObjectForKey:taskConfig.id];
769
+ // Progress buffered for a task that's over must not reach JS in a later batch
770
+ [progressReports removeObjectForKey:taskConfig.id];
771
+ [idToLastDataAt removeObjectForKey:taskConfig.id];
772
+ [idToNetworkResumeCount removeObjectForKey:taskConfig.id];
437
773
  // Clean up decode error retry tracking to prevent memory leak
438
774
  [decodeErrorRetriedIds removeObject:taskConfig.id];
775
+ // The task is over: its resume data (which embeds the request headers,
776
+ // tokens included) must not stay on disk
777
+ [self deleteResumeDataForTaskId:taskConfig.id];
439
778
  }
440
779
  }
441
780
  }
@@ -466,14 +805,31 @@ RCT_EXPORT_METHOD(setLogsEnabled:(BOOL)enabled) {
466
805
  // See https://github.com/kesha-antonov/react-native-background-downloader/issues/161
467
806
  @try {
468
807
  @synchronized (sharedLock) {
469
- if (max >= 1) {
470
- sessionConfig.HTTPMaximumConnectionsPerHost = max;
471
- // Recreate session with new config if it's already initialized
472
- if (urlSession != nil) {
473
- [self unregisterSession];
474
- [self lazyRegisterSession];
475
- }
808
+ if (max < 1 || max == sessionConfig.HTTPMaximumConnectionsPerHost) {
809
+ return;
810
+ }
811
+ sessionConfig.HTTPMaximumConnectionsPerHost = max;
812
+ [mmkv setInt64:max forKey:MAX_PARALLEL_DOWNLOADS_KEY];
813
+ if (urlSession == nil) {
814
+ return;
476
815
  }
816
+ // A live session can't change its config, and recreating it cancels every
817
+ // transfer in it. So recreate it only when it has nothing running; otherwise
818
+ // the saved value applies from the next launch.
819
+ NSURLSession *session = urlSession;
820
+ [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
821
+ @synchronized (self->sharedLock) {
822
+ BOOL idle = dataTasks.count == 0 && uploadTasks.count == 0 && downloadTasks.count == 0
823
+ && self->pendingDownloads.count == 0
824
+ && self->idToTaskMap.count == 0 && self->idToUploadTaskMap.count == 0;
825
+ if (self->urlSession == session && idle) {
826
+ // The new session is created once this one is gone
827
+ self->replacedSession = session;
828
+ self->replacedSessionInvalidated = dispatch_semaphore_create(0);
829
+ [self unregisterSession];
830
+ }
831
+ }
832
+ }];
477
833
  }
478
834
  } @catch (NSException *exception) {
479
835
  DLog(nil, @"[RNBackgroundDownloader] - [setMaxParallelDownloads] error: %@", exception.reason);
@@ -490,23 +846,19 @@ RCT_EXPORT_METHOD(setMaxParallelDownloads:(NSInteger)max) {
490
846
  }
491
847
  #endif
492
848
 
849
+ #ifdef RCT_NEW_ARCH_ENABLED
850
+ // Notification grouping is Android-only (JS only calls this on Android), but codegen
851
+ // makes the optional spec method required here
852
+ - (void)setNotificationGroupingConfig:(JS::NativeRNBackgroundDownloader::SpecSetNotificationGroupingConfigConfig &)config {
853
+ }
854
+ #endif
855
+
493
856
  - (void)_setAllowsCellularAccessInternal:(BOOL)allows {
494
- DLog(nil, @"[RNBackgroundDownloader] - [setAllowsCellularAccess:%@]", allows ? @"YES" : @"NO");
495
- // Never let an NSException escape this void method - see the note on
496
- // -_setMaxParallelDownloadsInternal: and issue #161. Recreating the session
497
- // here can throw, and an escaping exception crashes Hermes off the JS thread.
498
- @try {
499
- @synchronized (sharedLock) {
500
- sessionConfig.allowsCellularAccess = allows;
501
- // Recreate session with new config if it's already initialized
502
- if (urlSession != nil) {
503
- [self unregisterSession];
504
- [self lazyRegisterSession];
505
- }
506
- }
507
- } @catch (NSException *exception) {
508
- DLog(nil, @"[RNBackgroundDownloader] - [setAllowsCellularAccess] error: %@", exception.reason);
509
- }
857
+ // The global setting is applied in JS as the default for each task's
858
+ // isAllowedOverMetered, which sets the request's allowsCellularAccess. The session
859
+ // keeps allowing cellular, so there's nothing to change here and no session to
860
+ // recreate. Kept so the native API stays the same.
861
+ DLog(nil, @"[RNBackgroundDownloader] - [setAllowsCellularAccess:%@] applied per task", allows ? @"YES" : @"NO");
510
862
  }
511
863
 
512
864
  #ifdef RCT_NEW_ARCH_ENABLED
@@ -528,6 +880,7 @@ RCT_EXPORT_METHOD(setAllowsCellularAccess:(BOOL)allows) {
528
880
  NSString *metadata = options.metadata() ? options.metadata() : @"";
529
881
  NSDictionary *headers = options.headers() ? (NSDictionary *)options.headers() : nil;
530
882
  NSString *dataProtection = options.iosDataProtection() ? options.iosDataProtection() : nil;
883
+ BOOL allowsCellularAccess = options.isAllowedOverMetered();
531
884
 
532
885
  if (options.progressInterval().has_value()) {
533
886
  progressInterval = options.progressInterval().value() / 1000.0;
@@ -549,6 +902,8 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
549
902
  NSString *metadata = options[@"metadata"] ?: @"";
550
903
  NSDictionary *headers = options[@"headers"];
551
904
  NSString *dataProtection = options[@"iosDataProtection"];
905
+ NSNumber *isAllowedOverMetered = options[@"isAllowedOverMetered"];
906
+ BOOL allowsCellularAccess = isAllowedOverMetered == nil || [isAllowedOverMetered boolValue];
552
907
 
553
908
  NSNumber *progressIntervalScope = options[@"progressInterval"];
554
909
  if (progressIntervalScope) {
@@ -568,15 +923,21 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
568
923
  DLog(identifier, @"[RNBackgroundDownloader] - [download] url %@ destination %@ progressInterval %f", url, destination, progressInterval);
569
924
  if (identifier == nil || url == nil || destination == nil) {
570
925
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] id, url and destination must be set");
926
+ [self emitDownloadFailed:identifier error:@"id, url and destination must be set" errorCode:-1];
571
927
  return;
572
928
  }
573
929
 
574
930
  if (destinationRelative == nil) {
575
931
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] destination is not valid");
932
+ [self emitDownloadFailed:identifier error:@"destination is not valid" errorCode:-1];
576
933
  return;
577
934
  }
578
935
 
579
936
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
937
+ // NOTE: iOS may not allow a request to restrict cellular access further
938
+ // than its session allows.
939
+ // https://developer.apple.com/documentation/foundation/nsmutableurlrequest/allowscellularaccess
940
+ request.allowsCellularAccess = allowsCellularAccess;
580
941
  // Query in the getExistingDownloadTasks function.
581
942
  [request setValue:identifier forHTTPHeaderField:@"configId"];
582
943
  if (headers != nil) {
@@ -616,6 +977,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
616
977
  } @catch (NSException *exception) {
617
978
  DLog(identifier, @"[RNBackgroundDownloader] - [download] error: %@", exception.reason);
618
979
  [self sendDebugLog:[NSString stringWithFormat:@"download: ERROR - %@", exception.reason] taskId:identifier];
980
+ [self emitDownloadFailed:identifier error:exception.reason errorCode:-1];
619
981
  }
620
982
  }
621
983
 
@@ -629,6 +991,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
629
991
  if (task == nil) {
630
992
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] failed to create download task");
631
993
  [self sendDebugLog:@"executeDownloadWithRequest: ERROR - failed to create download task" taskId:identifier];
994
+ [self emitDownloadFailed:identifier error:@"failed to create download task" errorCode:-1];
632
995
  return;
633
996
  }
634
997
 
@@ -642,6 +1005,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
642
1005
  }];
643
1006
  // nil means "use the library default" when saving the file (see -nsFileProtectionFromKey:)
644
1007
  taskConfig.dataProtection = dataProtection;
1008
+ taskConfig.allowsCellularAccess = request.allowsCellularAccess;
645
1009
 
646
1010
  taskToConfigMap[@(task.taskIdentifier)] = taskConfig;
647
1011
  [mmkv setData:[self serialize: taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
@@ -652,7 +1016,6 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
652
1016
 
653
1017
  [task resume];
654
1018
  [self sendDebugLog:@"executeDownloadWithRequest: task.resume() called" taskId:identifier];
655
- lastProgressReportedAt = [[NSDate alloc] init];
656
1019
  }
657
1020
  }
658
1021
 
@@ -673,7 +1036,8 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
673
1036
 
674
1037
  // Recreate the background session directly (do not call unregisterSession,
675
1038
  // which would invalidateAndCancel and drop queued downloads).
676
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
1039
+ [self dropSharedSession:urlSession];
1040
+ urlSession = [self attachSession];
677
1041
  isSessionActivated = YES;
678
1042
 
679
1043
  @try {
@@ -700,7 +1064,8 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
700
1064
 
701
1065
  // Recreate the background session directly (do not call unregisterSession,
702
1066
  // which would invalidateAndCancel and drop queued downloads).
703
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
1067
+ [self dropSharedSession:urlSession];
1068
+ urlSession = [self attachSession];
704
1069
  isSessionActivated = YES;
705
1070
 
706
1071
  @try {
@@ -713,6 +1078,24 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
713
1078
  }
714
1079
  }
715
1080
 
1081
+ // Emits downloadFailed so the JS task errors out instead of hanging when download
1082
+ // setup fails before a task exists (bad params, bad destination, task creation failure).
1083
+ - (void)emitDownloadFailed:(NSString *)identifier error:(NSString *)error errorCode:(NSInteger)errorCode {
1084
+ if (identifier == nil) {
1085
+ return;
1086
+ }
1087
+ NSDictionary *body = @{
1088
+ @"id": identifier,
1089
+ @"error": error ?: @"unknown error",
1090
+ @"errorCode": @(errorCode)
1091
+ };
1092
+ #ifdef RCT_NEW_ARCH_ENABLED
1093
+ [self safeEmitEvent:@"onDownloadFailed" value:body];
1094
+ #else
1095
+ [self sendEventWithName:@"downloadFailed" body:body];
1096
+ #endif
1097
+ }
1098
+
716
1099
  // Emits uploadFailed so the JS task errors out instead of hanging when upload
717
1100
  // setup fails before a task exists (bad params, unreadable file, task creation failure).
718
1101
  - (void)emitUploadFailed:(NSString *)identifier error:(NSString *)error errorCode:(NSInteger)errorCode {
@@ -739,6 +1122,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
739
1122
  if (task != nil) {
740
1123
  // Mark task as pausing IMMEDIATELY before cancellation to prevent race condition
741
1124
  [idsToPauseSet addObject:identifier];
1125
+ [progressReports removeObjectForKey:identifier];
742
1126
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseTask] marking task as pausing: %@", identifier);
743
1127
 
744
1128
  [task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
@@ -784,6 +1168,21 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
784
1168
  }
785
1169
  #endif
786
1170
 
1171
+ // A request that downloads the whole file again: the task's own cellular setting and
1172
+ // the given headers, minus any Range
1173
+ - (NSMutableURLRequest *)freshRequestForConfig:(RNBGDTaskConfig *)taskConfig headers:(NSDictionary *)headers {
1174
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:taskConfig.url]];
1175
+ request.allowsCellularAccess = taskConfig.allowsCellularAccess;
1176
+ for (NSString *headerKey in headers) {
1177
+ if ([headerKey caseInsensitiveCompare:@"Range"] == NSOrderedSame) {
1178
+ continue;
1179
+ }
1180
+ [request setValue:[headers valueForKey:headerKey] forHTTPHeaderField:headerKey];
1181
+ }
1182
+ [request setValue:taskConfig.id forHTTPHeaderField:@"configId"];
1183
+ return request;
1184
+ }
1185
+
787
1186
  - (void)resumeTaskInternal:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
788
1187
  DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask]");
789
1188
  @try {
@@ -816,19 +1215,17 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
816
1215
  // This is needed when auth tokens change while paused
817
1216
  if (updatedHeaders != nil && [updatedHeaders count] > 0) {
818
1217
  RNBGDTaskConfig *taskConfig = [self findConfigById:identifier];
819
- if (taskConfig != nil && taskConfig.bytesDownloaded > 0) {
820
- DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] using updated headers with Range for %@", identifier);
821
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:taskConfig.url]];
822
- [request setValue:identifier forHTTPHeaderField:@"configId"];
823
- for (NSString *headerKey in updatedHeaders) {
824
- [request setValue:[updatedHeaders valueForKey:headerKey] forHTTPHeaderField:headerKey];
825
- }
826
- // Add Range header to resume from where we left off
827
- NSString *rangeValue = [NSString stringWithFormat:@"bytes=%lld-", taskConfig.bytesDownloaded];
828
- [request setValue:rangeValue forHTTPHeaderField:@"Range"];
829
- newTask = [urlSession downloadTaskWithRequest:request];
1218
+ if (taskConfig != nil) {
1219
+ // Resume data carries the old headers and can't be changed, and a fresh
1220
+ // task with a Range header saves only the remaining bytes as the whole
1221
+ // file. So download the file again with the new headers.
1222
+ DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] restarting with updated headers for %@", identifier);
1223
+ newTask = [self createDownloadTaskWithRequest:[self freshRequestForConfig:taskConfig headers:updatedHeaders] identifier:identifier];
1224
+ taskConfig.bytesDownloaded = 0;
1225
+ // Progress thresholds compare with the last report, which was for the old transfer
1226
+ idToPercentMap[identifier] = @0.0;
1227
+ idToLastBytesMap[identifier] = @0;
830
1228
  } else {
831
- // No bytes downloaded, just use resume data (shouldn't normally happen)
832
1229
  newTask = [urlSession downloadTaskWithResumeData:resumeData];
833
1230
  }
834
1231
  // Clear updated headers after use
@@ -868,6 +1265,8 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
868
1265
  // Delete the resume data file after successful resume
869
1266
  [self deleteResumeDataForTaskId:identifier];
870
1267
  [newTask resume];
1268
+ } else {
1269
+ [self emitDownloadFailed:identifier error:@"failed to create download task" errorCode:-1];
871
1270
  }
872
1271
  } else if (task != nil && task.state == NSURLSessionTaskStateSuspended) {
873
1272
  // Task was suspended normally, just resume it
@@ -879,7 +1278,35 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
879
1278
  }
880
1279
  [task resume];
881
1280
  } else {
882
- DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] no task or resume data found for %@", identifier);
1281
+ // Paused without resume data (the server doesn't support resuming), or the
1282
+ // paused task is gone: download the file again instead of staying paused forever
1283
+ RNBGDTaskConfig *taskConfig = [self findConfigById:identifier];
1284
+ if (taskConfig != nil) {
1285
+ DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] no resume data, restarting %@", identifier);
1286
+ NSDictionary *headers = updatedHeaders ?: task.originalRequest.allHTTPHeaderFields;
1287
+ NSURLSessionDownloadTask *newTask = [self createDownloadTaskWithRequest:[self freshRequestForConfig:taskConfig headers:headers] identifier:identifier];
1288
+ [idToUpdatedHeadersMap removeObjectForKey:identifier];
1289
+ if (newTask != nil) {
1290
+ NSNumber *oldKey = [self findTaskKeyById:identifier];
1291
+ if (oldKey != nil) {
1292
+ [taskToConfigMap removeObjectForKey:oldKey];
1293
+ }
1294
+ taskConfig.state = NSURLSessionTaskStateRunning;
1295
+ taskConfig.errorCode = 0;
1296
+ taskConfig.hasResumeData = NO;
1297
+ taskConfig.bytesDownloaded = 0;
1298
+ idToPercentMap[identifier] = @0.0;
1299
+ idToLastBytesMap[identifier] = @0;
1300
+ taskToConfigMap[@(newTask.taskIdentifier)] = taskConfig;
1301
+ [mmkv setData:[self serialize: taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
1302
+ self->idToTaskMap[identifier] = newTask;
1303
+ [newTask resume];
1304
+ } else {
1305
+ [self emitDownloadFailed:identifier error:@"failed to create download task" errorCode:-1];
1306
+ }
1307
+ } else {
1308
+ DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] no task or resume data found for %@", identifier);
1309
+ }
883
1310
  }
884
1311
  }
885
1312
  resolve(nil);
@@ -985,10 +1412,10 @@ RCT_EXPORT_METHOD(updateTaskHeaders:(NSString *)id headers:(NSDictionary *)heade
985
1412
  DLog(nil, @"[RNBackgroundDownloader] - [completeHandlerIOS]");
986
1413
  @try {
987
1414
  [[NSOperationQueue mainQueue] addOperationWithBlock:^{
988
- if (storedCompletionHandler) {
989
- storedCompletionHandler();
990
- storedCompletionHandler = nil;
1415
+ if (jobId != nil) {
1416
+ [idsAwaitingCompleteHandler removeObject:jobId];
991
1417
  }
1418
+ callCompletionHandlerIfDone();
992
1419
  }];
993
1420
 
994
1421
  resolve(nil);
@@ -1022,8 +1449,13 @@ RCT_EXPORT_METHOD(completeHandler:(nonnull NSString *)jobId resolver:(RCTPromise
1022
1449
  NSString *logMsg = [NSString stringWithFormat:@"getExistingDownloadTasks: found %lu download tasks", (unsigned long)downloadTasks.count];
1023
1450
  [self sendDebugLog:logMsg taskId:nil];
1024
1451
 
1025
- // Wait for session tasks to stabilize after app restart
1026
- [NSThread sleepForTimeInterval:kTaskReconciliationDelay];
1452
+ // Wait for session tasks to stabilize after app restart. Only the first time:
1453
+ // this blocks the session's queue, and so every download's events, and apps
1454
+ // call this for every download they start, pause or stop
1455
+ if (!self->hasReconciledTasks) {
1456
+ self->hasReconciledTasks = YES;
1457
+ [NSThread sleepForTimeInterval:kTaskReconciliationDelay];
1458
+ }
1027
1459
 
1028
1460
  NSMutableArray *foundTasks = [[NSMutableArray alloc] init];
1029
1461
  NSMutableSet *processedIds = [[NSMutableSet alloc] init];
@@ -1035,6 +1467,10 @@ RCT_EXPORT_METHOD(completeHandler:(nonnull NSString *)jobId resolver:(RCTPromise
1035
1467
  if (taskConfig) {
1036
1468
  NSURLSessionDownloadTask *mutableTask = task;
1037
1469
  [self restoreTaskIfNeeded:&mutableTask];
1470
+ if (mutableTask != task) {
1471
+ // The replacement gets its own key below; drop the finished task's
1472
+ [self->taskToConfigMap removeObjectForKey:@(task.taskIdentifier)];
1473
+ }
1038
1474
  [self updateTaskMappings:mutableTask config:taskConfig];
1039
1475
  [foundTasks addObject:[self createTaskInfo:mutableTask config:taskConfig]];
1040
1476
  [processedIds addObject:taskConfig.id];
@@ -1102,17 +1538,18 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1102
1538
  - (void)restoreTaskIfNeeded:(NSURLSessionDownloadTask *__strong *)taskPtr {
1103
1539
  NSURLSessionDownloadTask *task = *taskPtr;
1104
1540
 
1105
- BOOL isCompletedOrSuspended = (task.state == NSURLSessionTaskStateCompleted ||
1106
- task.state == NSURLSessionTaskStateSuspended);
1541
+ // A suspended task can still be resumed as is (see -resumeTaskInternal:); only a
1542
+ // finished, incomplete one needs a replacement
1107
1543
  BOOL needsMoreData = task.countOfBytesReceived < task.countOfBytesExpectedToReceive;
1108
1544
 
1109
- if (isCompletedOrSuspended && needsMoreData) {
1545
+ if (task.state == NSURLSessionTaskStateCompleted && needsMoreData) {
1110
1546
  NSData *resumeData = task.error.userInfo[NSURLSessionDownloadTaskResumeData];
1111
1547
 
1112
1548
  if (task.error.code == -999 && resumeData) {
1113
1549
  *taskPtr = [urlSession downloadTaskWithResumeData:resumeData];
1114
- } else {
1115
- *taskPtr = [urlSession downloadTaskWithURL:task.currentRequest.URL];
1550
+ } else if (task.originalRequest != nil) {
1551
+ // The original request keeps the configId header, custom headers and cellular flag
1552
+ *taskPtr = [urlSession downloadTaskWithRequest:task.originalRequest];
1116
1553
  }
1117
1554
  }
1118
1555
  }
@@ -1252,7 +1689,11 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1252
1689
 
1253
1690
  NSURL *fileURL = [self resumeDataFileURLForTaskId:taskId];
1254
1691
  NSError *error = nil;
1255
- BOOL success = [resumeData writeToURL:fileURL options:NSDataWritingAtomic error:&error];
1692
+ // Resume data embeds the request with its headers: keep it encrypted at rest while still
1693
+ // writable when a network drop saves it on a locked device
1694
+ BOOL success = [resumeData writeToURL:fileURL
1695
+ options:NSDataWritingAtomic | NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
1696
+ error:&error];
1256
1697
 
1257
1698
  if (!success) {
1258
1699
  DLog(taskId, @"[RNBackgroundDownloader] - [saveResumeData] failed to save resume data: %@", error.localizedDescription);
@@ -1317,6 +1758,7 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1317
1758
  // when NSURLSession delegate callbacks fire before JS has registered listeners
1318
1759
  // (e.g., background session delivering completions from a prior app session).
1319
1760
  - (void)safeEmitEvent:(NSString *)eventName value:(id)value {
1761
+ [self trackTerminalEvent:eventName body:value];
1320
1762
  @synchronized (pendingEmitEvents) {
1321
1763
  if (_eventEmitterCallback) {
1322
1764
  _eventEmitterCallback(std::string([eventName UTF8String]), value);
@@ -1339,6 +1781,21 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1339
1781
  }
1340
1782
  #endif
1341
1783
 
1784
+ #pragma mark - NSURLSessionDelegate methods
1785
+
1786
+ - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
1787
+ // Set before the session was invalidated, so they're safe to read here. Signal before
1788
+ // taking the lock: -lazyRegisterSession may be holding it while it waits for this.
1789
+ dispatch_semaphore_t invalidated = replacedSessionInvalidated;
1790
+ if (session != replacedSession || invalidated == nil) {
1791
+ return;
1792
+ }
1793
+ DLog(nil, @"[RNBackgroundDownloader] - [didBecomeInvalidWithError] replaced session invalidated");
1794
+ dispatch_semaphore_signal(invalidated);
1795
+ // Create its replacement now, unless something needed the session first
1796
+ [self lazyRegisterSession];
1797
+ }
1798
+
1342
1799
  #pragma mark - NSURLSessionDownloadDelegate methods
1343
1800
  - (void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location {
1344
1801
  @synchronized (sharedLock) {
@@ -1395,17 +1852,19 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1395
1852
  }];
1396
1853
  #endif
1397
1854
  } else {
1855
+ // Where -saveFile: put it, which differs from the stored path after an app update
1856
+ NSString *location = [self currentPathForDestination:taskConfig.destination] ?: taskConfig.destination;
1398
1857
  #ifdef RCT_NEW_ARCH_ENABLED
1399
1858
  [self safeEmitEvent:@"onDownloadComplete" value:@{
1400
1859
  @"id": taskConfig.id,
1401
- @"location": taskConfig.destination,
1860
+ @"location": location,
1402
1861
  @"bytesDownloaded": @(task.countOfBytesReceived),
1403
1862
  @"bytesTotal": @(task.countOfBytesExpectedToReceive)
1404
1863
  }];
1405
1864
  #else
1406
1865
  [self sendEventWithName:@"downloadComplete" body:@{
1407
1866
  @"id": taskConfig.id,
1408
- @"location": taskConfig.destination,
1867
+ @"location": location,
1409
1868
  @"bytesDownloaded": @(task.countOfBytesReceived),
1410
1869
  @"bytesTotal": @(task.countOfBytesExpectedToReceive)
1411
1870
  }];
@@ -1434,6 +1893,9 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1434
1893
 
1435
1894
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didWriteData]");
1436
1895
 
1896
+ idToLastDataAt[taskConfig.id] = [NSDate date];
1897
+ [idToNetworkResumeCount removeObjectForKey:taskConfig.id];
1898
+
1437
1899
  [self reportBeginIfNeeded:taskConfig downloadTask:downloadTask expectedBytes:bytesTotalExpectedToWrite];
1438
1900
  [self updateProgressIfNeeded:taskConfig bytesWritten:bytesTotalWritten bytesTotal:bytesTotalExpectedToWrite];
1439
1901
  [self flushProgressReportsIfNeeded];
@@ -1471,6 +1933,10 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1471
1933
  }
1472
1934
 
1473
1935
  - (void)updateProgressIfNeeded:(RNBGDTaskConfig *)taskConfig bytesWritten:(int64_t)bytesWritten bytesTotal:(int64_t)bytesTotal {
1936
+ // Data already in flight when the app paused the task
1937
+ if ([idsToPauseSet containsObject:taskConfig.id]) {
1938
+ return;
1939
+ }
1474
1940
  NSNumber *prevPercent = idToPercentMap[taskConfig.id] ?: @0.0;
1475
1941
  NSNumber *prevBytes = idToLastBytesMap[taskConfig.id] ?: @0;
1476
1942
  float currentPercent = bytesTotal > 0 ? (float)bytesWritten / (float)bytesTotal : 0.0;
@@ -1532,10 +1998,27 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1532
1998
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didCompleteWithError] error: %@", error);
1533
1999
  [self sendDebugLog:[NSString stringWithFormat:@"didCompleteWithError: error code=%ld, %@", (long)error.code, error.localizedDescription] taskId:taskConfig.id];
1534
2000
 
2001
+ // Cancelled to be restarted after a stall (-restartStalledDownloads:)
2002
+ if ([idsBeingRestarted containsObject:taskConfig.id]) {
2003
+ return;
2004
+ }
2005
+
1535
2006
  // NSURLErrorCancelled (-999) is used for paused or cancelled tasks
1536
2007
  // Extract resume data first before checking isPausedTask
1537
2008
  NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
1538
2009
 
2010
+ // Cut off by the network (timeout, lost connection): continue from the resume data
2011
+ // the system handed over, as it does itself for a stall, instead of failing the task.
2012
+ // Bounded, as a server that always cuts it off would loop
2013
+ if (resumeData != nil && [self isNetworkFailure:error]) {
2014
+ NSInteger resumes = [idToNetworkResumeCount[taskConfig.id] integerValue];
2015
+ if (resumes < kMaxNetworkResumes && [self continueTask:task config:taskConfig resumeData:resumeData]) {
2016
+ idToNetworkResumeCount[taskConfig.id] = @(resumes + 1);
2017
+ DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didCompleteWithError] network failure, continuing (%ld)", (long)resumes + 1);
2018
+ return;
2019
+ }
2020
+ }
2021
+
1539
2022
  // Check if this task was intentionally paused (marked in idsToPauseSet)
1540
2023
  BOOL wasIntentionallyPaused = [idsToPauseSet containsObject:taskConfig.id];
1541
2024
  BOOL hasResumeData = resumeData != nil;
@@ -1544,10 +2027,16 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1544
2027
  if (isPausedTask) {
1545
2028
  taskConfig.errorCode = error.code;
1546
2029
 
1547
- // Store resume data so we can resume the download later
2030
+ // Store resume data so we can resume the download later. Persist it too, as
2031
+ // -pauseTaskInternal: does: a cancel the app didn't ask for (e.g. the system
2032
+ // cancelling the task) would otherwise lose it on the next launch
1548
2033
  if (taskConfig.id && resumeData) {
1549
2034
  idToResumeDataMap[taskConfig.id] = resumeData;
2035
+ [self saveResumeData:resumeData forTaskId:taskConfig.id];
2036
+ taskConfig.hasResumeData = YES;
1550
2037
  }
2038
+ taskConfig.state = NSURLSessionTaskStateCanceling;
2039
+ [mmkv setData:[self serialize:taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
1551
2040
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didCompleteWithError] task was paused, ignoring error for %@", taskConfig.id);
1552
2041
  return;
1553
2042
  }
@@ -1563,6 +2052,8 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1563
2052
 
1564
2053
  // Build a fresh request replicating original headers
1565
2054
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:taskConfig.url]];
2055
+ // Keep the original request's cellular access
2056
+ request.allowsCellularAccess = taskConfig.allowsCellularAccess;
1566
2057
  // Reapply original request headers if available (including our internal identifier header)
1567
2058
  NSDictionary *originalHeaders = task.originalRequest.allHTTPHeaderFields;
1568
2059
  if (originalHeaders != nil) {
@@ -1615,6 +2106,33 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1615
2106
 
1616
2107
  - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
1617
2108
  DLog(nil, @"[RNBackgroundDownloader] - [URLSessionDidFinishEventsForBackgroundURLSession]");
2109
+ // Queued after the ids of the events just sent (-trackTerminalEvent:body:), so they count
2110
+ dispatch_async(dispatch_get_main_queue(), ^{
2111
+ backgroundEventsFinished = YES;
2112
+ callCompletionHandlerIfDone();
2113
+ });
2114
+ }
2115
+
2116
+ // Remembers a task whose done or failed event is sent during a background launch: the
2117
+ // completion handler waits until JS passes it to completeHandler
2118
+ - (void)trackTerminalEvent:(NSString *)eventName body:(id)body {
2119
+ static NSSet<NSString *> *terminalEvents;
2120
+ static dispatch_once_t once;
2121
+ dispatch_once(&once, ^{
2122
+ terminalEvents = [NSSet setWithArray:@[
2123
+ @"downloadComplete", @"downloadFailed", @"uploadComplete", @"uploadFailed",
2124
+ @"onDownloadComplete", @"onDownloadFailed", @"onUploadComplete", @"onUploadFailed",
2125
+ ]];
2126
+ });
2127
+ NSString *identifier = [body isKindOfClass:[NSDictionary class]] ? body[@"id"] : nil;
2128
+ if (identifier == nil || ![terminalEvents containsObject:eventName]) {
2129
+ return;
2130
+ }
2131
+ dispatch_async(dispatch_get_main_queue(), ^{
2132
+ if (storedCompletionHandler != nil) {
2133
+ [idsAwaitingCompleteHandler addObject:identifier];
2134
+ }
2135
+ });
1618
2136
  }
1619
2137
 
1620
2138
  #pragma mark - Upload methods
@@ -1632,6 +2150,7 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1632
2150
  [idToUploadTaskMap removeObjectForKey:taskConfig.id];
1633
2151
  [idToUploadPercentMap removeObjectForKey:taskConfig.id];
1634
2152
  [idToUploadLastBytesMap removeObjectForKey:taskConfig.id];
2153
+ [uploadProgressReports removeObjectForKey:taskConfig.id];
1635
2154
  }
1636
2155
  }
1637
2156
  }
@@ -1648,6 +2167,16 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1648
2167
  NSString *fieldName = options.fieldName() ? options.fieldName() : nil;
1649
2168
  NSString *mimeType = options.mimeType() ? options.mimeType() : nil;
1650
2169
  NSDictionary *parameters = options.parameters() ? (NSDictionary *)options.parameters() : nil;
2170
+ BOOL allowsCellularAccess = options.isAllowedOverMetered();
2171
+ NSMutableArray<NSString *> *partUrls = nil;
2172
+ if (options.partUrls().has_value()) {
2173
+ auto urls = options.partUrls().value();
2174
+ partUrls = [NSMutableArray arrayWithCapacity:urls.size()];
2175
+ for (size_t i = 0; i < urls.size(); i++) {
2176
+ [partUrls addObject:urls[i]];
2177
+ }
2178
+ }
2179
+ long long partSize = options.partSize().has_value() ? (long long)options.partSize().value() : 0;
1651
2180
 
1652
2181
  if (options.progressInterval().has_value()) {
1653
2182
  progressInterval = options.progressInterval().value() / 1000.0;
@@ -1670,6 +2199,10 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1670
2199
  NSString *fieldName = options[@"fieldName"];
1671
2200
  NSString *mimeType = options[@"mimeType"];
1672
2201
  NSDictionary *parameters = options[@"parameters"];
2202
+ NSNumber *isAllowedOverMetered = options[@"isAllowedOverMetered"];
2203
+ BOOL allowsCellularAccess = isAllowedOverMetered == nil || [isAllowedOverMetered boolValue];
2204
+ NSArray<NSString *> *partUrls = [options[@"partUrls"] isKindOfClass:[NSArray class]] ? options[@"partUrls"] : nil;
2205
+ long long partSize = [options[@"partSize"] isKindOfClass:[NSNumber class]] ? [options[@"partSize"] longLongValue] : 0;
1673
2206
 
1674
2207
  NSNumber *progressIntervalScope = options[@"progressInterval"];
1675
2208
  if (progressIntervalScope) {
@@ -1691,8 +2224,23 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1691
2224
  return;
1692
2225
  }
1693
2226
 
2227
+ if (partUrls != nil) {
2228
+ [self startPartUpload:identifier
2229
+ source:source
2230
+ partUrls:partUrls
2231
+ partSize:partSize
2232
+ method:method
2233
+ metadata:metadata
2234
+ headers:headers
2235
+ mimeType:mimeType
2236
+ allowsCellularAccess:allowsCellularAccess];
2237
+ return;
2238
+ }
2239
+
1694
2240
  @try {
1695
2241
  @synchronized (sharedLock) {
2242
+ // A new upload with this id replaces a finished one's kept response
2243
+ [self dropFinishedUpload:identifier];
1696
2244
  [self sendDebugLog:@"upload: calling lazyRegisterSession" taskId:identifier];
1697
2245
  [self lazyRegisterSession];
1698
2246
 
@@ -1729,6 +2277,7 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1729
2277
  // Create request
1730
2278
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestURL];
1731
2279
  request.HTTPMethod = method;
2280
+ request.allowsCellularAccess = allowsCellularAccess;
1732
2281
  [request setValue:identifier forHTTPHeaderField:@"uploadConfigId"];
1733
2282
 
1734
2283
  // Add custom headers
@@ -1796,8 +2345,12 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1796
2345
  [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1797
2346
 
1798
2347
  // Write body to temp file for background upload
1799
- NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
1800
- if (![body writeToFile:tempPath atomically:YES]) {
2348
+ NSString *tempPath = [self multipartTempPathForUploadId:identifier];
2349
+ // A full copy of the user's file plus form fields: encrypted at rest, still
2350
+ // readable by the background session while the device is locked
2351
+ if (![body writeToFile:tempPath
2352
+ options:NSDataWritingAtomic | NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
2353
+ error:nil]) {
1801
2354
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not write multipart body to temp file");
1802
2355
  [self emitUploadFailed:identifier error:@"Could not write multipart body to temp file" errorCode:NSURLErrorCannotWriteToFile];
1803
2356
  return;
@@ -1816,6 +2369,7 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1816
2369
 
1817
2370
  if (uploadTask == nil) {
1818
2371
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] failed to create upload task");
2372
+ [self removeMultipartTempFileForUploadId:identifier];
1819
2373
  [self emitUploadFailed:identifier error:@"failed to create upload task" errorCode:-1];
1820
2374
  return;
1821
2375
  }
@@ -1828,7 +2382,6 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1828
2382
  idToUploadLastBytesMap[identifier] = @0;
1829
2383
 
1830
2384
  [uploadTask resume];
1831
- lastUploadProgressReportedAt = [[NSDate alloc] init];
1832
2385
  }
1833
2386
  } @catch (NSException *exception) {
1834
2387
  DLog(identifier, @"[RNBackgroundDownloader] - [upload] error: %@", exception.reason);
@@ -1837,14 +2390,363 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1837
2390
  }
1838
2391
  }
1839
2392
 
2393
+ #pragma mark - Uploads in parts (partUrls)
2394
+
2395
+ - (void)persistUploadConfigs {
2396
+ [mmkv setData:[self serializeUploadConfig:uploadTaskToConfigMap] forKey:ID_TO_UPLOAD_CONFIG_MAP_KEY];
2397
+ }
2398
+
2399
+ - (void)persistFinishedUploads {
2400
+ [mmkv setData:[self serializeUploadConfig:(NSMutableDictionary *)finishedUploads] forKey:FINISHED_UPLOADS_KEY];
2401
+ }
2402
+
2403
+ // Must hold sharedLock
2404
+ - (void)dropFinishedUpload:(NSString *)identifier {
2405
+ if (identifier != nil && finishedUploads[identifier] != nil) {
2406
+ [finishedUploads removeObjectForKey:identifier];
2407
+ [self persistFinishedUploads];
2408
+ }
2409
+ }
2410
+
2411
+ // Response headers with lowercased names, so JS reads responseHeaders.etag on both platforms
2412
+ - (NSDictionary<NSString *, NSString *> *)lowercasedHeadersOfResponse:(NSURLResponse *)response {
2413
+ NSMutableDictionary<NSString *, NSString *> *headers = [NSMutableDictionary dictionary];
2414
+ if (![response isKindOfClass:[NSHTTPURLResponse class]]) {
2415
+ return headers;
2416
+ }
2417
+ [((NSHTTPURLResponse *)response).allHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
2418
+ if ([key isKindOfClass:[NSString class]]) {
2419
+ headers[[(NSString *)key lowercaseString]] = [value isKindOfClass:[NSString class]] ? value : [value description];
2420
+ }
2421
+ }];
2422
+ return headers;
2423
+ }
2424
+
2425
+ - (NSString *)normalizedSourcePath:(NSString *)source {
2426
+ if (![source hasPrefix:@"file://"]) {
2427
+ return source;
2428
+ }
2429
+ NSString *path = [NSURL URLWithString:source].path;
2430
+ if (path == nil) {
2431
+ // URLWithString rejects unencoded paths (e.g. containing spaces)
2432
+ path = [[source substringFromIndex:@"file://".length] stringByRemovingPercentEncoding];
2433
+ }
2434
+ return path ?: source;
2435
+ }
2436
+
2437
+ // A background session uploads only from a file, so each part is copied out of the source
2438
+ - (NSString *)partTempPathForUploadId:(NSString *)identifier index:(NSUInteger)index {
2439
+ NSString *safeId = [identifier stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
2440
+ return [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"RNBGD-upload-%@.part-%lu", safeId, (unsigned long)index]];
2441
+ }
2442
+
2443
+ - (void)removePartTempFilesForUploadId:(NSString *)identifier count:(NSUInteger)count {
2444
+ for (NSUInteger index = 0; index < count; index++) {
2445
+ [[NSFileManager defaultManager] removeItemAtPath:[self partTempPathForUploadId:identifier index:index] error:nil];
2446
+ }
2447
+ }
2448
+
2449
+ // Copies [offset, offset + length) of the source in chunks, so a big file isn't read into memory
2450
+ - (BOOL)copyRangeOfFile:(NSString *)source offset:(long long)offset length:(long long)length toPath:(NSString *)path {
2451
+ NSFileManager *fileManager = [NSFileManager defaultManager];
2452
+ [fileManager removeItemAtPath:path error:nil];
2453
+ // Holds a slice of the user's file: encrypted at rest, still readable by the
2454
+ // background session while the device is locked
2455
+ if (![fileManager createFileAtPath:path contents:nil attributes:@{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication}]) {
2456
+ return NO;
2457
+ }
2458
+ NSFileHandle *input = [NSFileHandle fileHandleForReadingAtPath:source];
2459
+ NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:path];
2460
+ BOOL copied = input != nil && output != nil && [input seekToOffset:(unsigned long long)offset error:nil];
2461
+ long long remaining = length;
2462
+ while (copied && remaining > 0) {
2463
+ @autoreleasepool {
2464
+ NSData *chunk = [input readDataUpToLength:(NSUInteger)MIN(remaining, (long long)kPartCopyChunkBytes) error:nil];
2465
+ if (chunk.length == 0 || ![output writeData:chunk error:nil]) {
2466
+ copied = NO;
2467
+ } else {
2468
+ remaining -= chunk.length;
2469
+ }
2470
+ }
2471
+ }
2472
+ [input closeAndReturnError:nil];
2473
+ [output closeAndReturnError:nil];
2474
+ if (!copied) {
2475
+ [fileManager removeItemAtPath:path error:nil];
2476
+ }
2477
+ return copied;
2478
+ }
2479
+
2480
+ - (void)startPartUpload:(NSString *)identifier
2481
+ source:(NSString *)source
2482
+ partUrls:(NSArray<NSString *> *)partUrls
2483
+ partSize:(long long)partSize
2484
+ method:(NSString *)method
2485
+ metadata:(NSString *)metadata
2486
+ headers:(NSDictionary *)headers
2487
+ mimeType:(NSString *)mimeType
2488
+ allowsCellularAccess:(BOOL)allowsCellularAccess {
2489
+ source = [self normalizedSourcePath:source];
2490
+
2491
+ NSError *fileError = nil;
2492
+ NSDictionary *fileAttrs = [[NSFileManager defaultManager] attributesOfItemAtPath:source error:&fileError];
2493
+ if (fileError) {
2494
+ [self emitUploadFailed:identifier error:[NSString stringWithFormat:@"Could not read file: %@", fileError.localizedDescription] errorCode:NSURLErrorFileDoesNotExist];
2495
+ return;
2496
+ }
2497
+ long long fileSize = (long long)[fileAttrs fileSize];
2498
+
2499
+ NSArray<NSArray<NSNumber *> *> *ranges = [RNBGDUploadTaskConfig partRangesForFileSize:fileSize partCount:partUrls.count partSize:partSize];
2500
+ if (ranges == nil) {
2501
+ NSString *sizeNote = partSize > 0 ? [NSString stringWithFormat:@" of %lld bytes", partSize] : @"";
2502
+ [self emitUploadFailed:identifier
2503
+ error:[NSString stringWithFormat:@"The file (%lld bytes) can't be split into %lu parts%@", fileSize, (unsigned long)partUrls.count, sizeNote]
2504
+ errorCode:-1];
2505
+ return;
2506
+ }
2507
+ for (NSString *partUrl in partUrls) {
2508
+ if (![partUrl isKindOfClass:[NSString class]] || [NSURL URLWithString:partUrl] == nil) {
2509
+ [self emitUploadFailed:identifier error:[NSString stringWithFormat:@"invalid url: %@", partUrl] errorCode:NSURLErrorBadURL];
2510
+ return;
2511
+ }
2512
+ }
2513
+
2514
+ @synchronized (sharedLock) {
2515
+ // A new upload with this id replaces a finished one's kept response
2516
+ [self dropFinishedUpload:identifier];
2517
+ }
2518
+
2519
+ // Outside the lock: copying a big file takes a while, and session callbacks need it
2520
+ for (NSUInteger index = 0; index < ranges.count; index++) {
2521
+ if (![self copyRangeOfFile:source
2522
+ offset:[ranges[index][0] longLongValue]
2523
+ length:[ranges[index][1] longLongValue]
2524
+ toPath:[self partTempPathForUploadId:identifier index:index]]) {
2525
+ [self removePartTempFilesForUploadId:identifier count:index];
2526
+ [self emitUploadFailed:identifier error:[NSString stringWithFormat:@"Could not copy part %lu of the file", (unsigned long)index + 1] errorCode:NSURLErrorCannotWriteToFile];
2527
+ return;
2528
+ }
2529
+ }
2530
+
2531
+ @try {
2532
+ @synchronized (sharedLock) {
2533
+ [self lazyRegisterSession];
2534
+
2535
+ RNBGDUploadTaskConfig *taskConfig = [[RNBGDUploadTaskConfig alloc] initWithDictionary:@{
2536
+ @"id": identifier,
2537
+ @"url": partUrls.firstObject,
2538
+ @"source": source,
2539
+ @"method": method,
2540
+ @"metadata": metadata,
2541
+ @"mimeType": mimeType ?: [NSNull null],
2542
+ @"partUrls": partUrls,
2543
+ @"partSize": @(partSize)
2544
+ }];
2545
+ taskConfig.bytesTotal = fileSize;
2546
+
2547
+ NSMutableArray<NSURLSessionUploadTask *> *tasks = [NSMutableArray arrayWithCapacity:partUrls.count];
2548
+ NSMutableDictionary<NSNumber *, NSNumber *> *partIndexByTask = [NSMutableDictionary dictionary];
2549
+ for (NSUInteger index = 0; index < partUrls.count; index++) {
2550
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:partUrls[index]]];
2551
+ request.HTTPMethod = method;
2552
+ request.allowsCellularAccess = allowsCellularAccess;
2553
+ for (NSString *headerKey in headers) {
2554
+ [request setValue:[headers valueForKey:headerKey] forHTTPHeaderField:headerKey];
2555
+ }
2556
+ // Raw body, no multipart wrapping
2557
+ [request setValue:mimeType ?: @"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
2558
+
2559
+ NSURL *partFile = [NSURL fileURLWithPath:[self partTempPathForUploadId:identifier index:index]];
2560
+ NSURLSessionUploadTask *task = [self createUploadTaskWithRequest:request fromFile:partFile identifier:identifier];
2561
+ if (task == nil) {
2562
+ for (NSURLSessionUploadTask *created in tasks) {
2563
+ [created cancel];
2564
+ }
2565
+ [self removePartTempFilesForUploadId:identifier count:partUrls.count];
2566
+ [self emitUploadFailed:identifier error:@"failed to create upload task" errorCode:-1];
2567
+ return;
2568
+ }
2569
+ partIndexByTask[@(task.taskIdentifier)] = @(index);
2570
+ [tasks addObject:task];
2571
+ }
2572
+ taskConfig.partIndexByTask = partIndexByTask;
2573
+
2574
+ for (NSURLSessionUploadTask *task in tasks) {
2575
+ uploadTaskToConfigMap[@(task.taskIdentifier)] = taskConfig;
2576
+ }
2577
+ [self persistUploadConfigs];
2578
+ idToUploadPartTasks[identifier] = tasks;
2579
+ idToUploadPercentMap[identifier] = @0.0;
2580
+ idToUploadLastBytesMap[identifier] = @0;
2581
+
2582
+ for (NSURLSessionUploadTask *task in tasks) {
2583
+ [task resume];
2584
+ }
2585
+ }
2586
+ } @catch (NSException *exception) {
2587
+ DLog(identifier, @"[RNBackgroundDownloader] - [startPartUpload] error: %@", exception.reason);
2588
+ [self removePartTempFilesForUploadId:identifier count:partUrls.count];
2589
+ [self emitUploadFailed:identifier error:exception.reason errorCode:-1];
2590
+ }
2591
+ }
2592
+
2593
+ // Bytes sent so far across the parts: accepted parts in full, running ones as far as they got.
2594
+ // Must hold sharedLock
2595
+ - (long long)bytesSentForPartUpload:(RNBGDUploadTaskConfig *)taskConfig {
2596
+ long long sent = 0;
2597
+ for (NSDictionary *result in taskConfig.partResults.allValues) {
2598
+ sent += [result[@"bytes"] longLongValue];
2599
+ }
2600
+ for (NSNumber *taskKey in taskConfig.partIndexByTask) {
2601
+ sent += [uploadPartBytesSent[taskKey] longLongValue];
2602
+ }
2603
+ return sent;
2604
+ }
2605
+
2606
+ // Must hold sharedLock
2607
+ - (void)forgetPartUploadTasks:(RNBGDUploadTaskConfig *)taskConfig cancel:(BOOL)cancel {
2608
+ for (NSNumber *taskKey in taskConfig.partIndexByTask) {
2609
+ [uploadTaskToConfigMap removeObjectForKey:taskKey];
2610
+ [uploadPartBytesSent removeObjectForKey:taskKey];
2611
+ [uploadResponseDataByTask removeObjectForKey:taskKey];
2612
+ }
2613
+ if (cancel) {
2614
+ // Their completion finds no config any more and is ignored
2615
+ for (NSURLSessionUploadTask *task in idToUploadPartTasks[taskConfig.id]) {
2616
+ [task cancel];
2617
+ }
2618
+ }
2619
+ [idToUploadPartTasks removeObjectForKey:taskConfig.id];
2620
+ [idToUploadPercentMap removeObjectForKey:taskConfig.id];
2621
+ [idToUploadLastBytesMap removeObjectForKey:taskConfig.id];
2622
+ [uploadProgressReports removeObjectForKey:taskConfig.id];
2623
+ [idsToUploadPauseSet removeObject:taskConfig.id];
2624
+ [self removePartTempFilesForUploadId:taskConfig.id count:taskConfig.partUrls.count];
2625
+ [self persistUploadConfigs];
2626
+ }
2627
+
2628
+ // Any part that isn't accepted fails the whole upload. Must hold sharedLock
2629
+ - (void)failPartUpload:(RNBGDUploadTaskConfig *)taskConfig error:(NSString *)error errorCode:(NSInteger)errorCode {
2630
+ DLog(taskConfig.id, @"[RNBackgroundDownloader] - [failPartUpload] %@", error);
2631
+ [self forgetPartUploadTasks:taskConfig cancel:YES];
2632
+ [self emitUploadFailed:taskConfig.id error:error errorCode:errorCode];
2633
+ }
2634
+
2635
+ // Must hold sharedLock
2636
+ - (void)handlePartCompletion:(NSURLSessionTask *)task config:(RNBGDUploadTaskConfig *)taskConfig responseData:(NSData *)responseData error:(NSError *)error {
2637
+ NSNumber *taskKey = @(task.taskIdentifier);
2638
+ NSNumber *index = taskConfig.partIndexByTask[taskKey];
2639
+ if (index == nil) {
2640
+ return;
2641
+ }
2642
+ if (error) {
2643
+ [self failPartUpload:taskConfig error:error.localizedDescription errorCode:error.code];
2644
+ return;
2645
+ }
2646
+
2647
+ NSInteger responseCode = [task.response isKindOfClass:[NSHTTPURLResponse class]] ? ((NSHTTPURLResponse *)task.response).statusCode : 0;
2648
+ NSString *responseBody = responseData != nil ? ([[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ?: @"") : @"";
2649
+ NSUInteger partNumber = index.unsignedIntegerValue + 1;
2650
+ if (responseCode < 200 || responseCode >= 300) {
2651
+ [self failPartUpload:taskConfig
2652
+ error:[NSString stringWithFormat:@"Part %lu failed: HTTP %ld - %@", (unsigned long)partNumber, (long)responseCode, responseBody]
2653
+ errorCode:responseCode];
2654
+ return;
2655
+ }
2656
+
2657
+ NSArray<NSArray<NSNumber *> *> *ranges = [RNBGDUploadTaskConfig partRangesForFileSize:taskConfig.bytesTotal
2658
+ partCount:taskConfig.partUrls.count
2659
+ partSize:taskConfig.partSize];
2660
+ NSMutableDictionary<NSNumber *, NSDictionary *> *results = [taskConfig.partResults mutableCopy] ?: [NSMutableDictionary dictionary];
2661
+ results[index] = @{
2662
+ @"partNumber": @(partNumber),
2663
+ @"responseCode": @(responseCode),
2664
+ @"responseBody": responseBody,
2665
+ @"responseHeaders": [self lowercasedHeadersOfResponse:task.response],
2666
+ @"bytes": ranges[index.unsignedIntegerValue][1]
2667
+ };
2668
+ taskConfig.partResults = results;
2669
+
2670
+ NSMutableDictionary<NSNumber *, NSNumber *> *partIndexByTask = [taskConfig.partIndexByTask mutableCopy];
2671
+ [partIndexByTask removeObjectForKey:taskKey];
2672
+ taskConfig.partIndexByTask = partIndexByTask;
2673
+ [uploadTaskToConfigMap removeObjectForKey:taskKey];
2674
+ [uploadPartBytesSent removeObjectForKey:taskKey];
2675
+ [idToUploadPartTasks[taskConfig.id] removeObject:(NSURLSessionUploadTask *)task];
2676
+ // Free the copy as soon as its part is in
2677
+ [[NSFileManager defaultManager] removeItemAtPath:[self partTempPathForUploadId:taskConfig.id index:index.unsignedIntegerValue] error:nil];
2678
+
2679
+ if (results.count < taskConfig.partUrls.count) {
2680
+ [self persistUploadConfigs];
2681
+ return;
2682
+ }
2683
+
2684
+ // Every part is in
2685
+ NSArray<NSDictionary *> *parts = [taskConfig orderedPartResults];
2686
+ NSDictionary *last = parts.lastObject;
2687
+ taskConfig.responseCode = [last[@"responseCode"] integerValue];
2688
+ taskConfig.responseBody = last[@"responseBody"];
2689
+ taskConfig.responseHeaders = last[@"responseHeaders"];
2690
+ taskConfig.bytesUploaded = taskConfig.bytesTotal;
2691
+ taskConfig.state = NSURLSessionTaskStateCompleted;
2692
+ [self forgetPartUploadTasks:taskConfig cancel:NO];
2693
+ finishedUploads[taskConfig.id] = taskConfig;
2694
+ [self persistFinishedUploads];
2695
+
2696
+ [self emitUploadComplete:taskConfig.id
2697
+ responseCode:taskConfig.responseCode
2698
+ responseBody:taskConfig.responseBody
2699
+ responseHeaders:taskConfig.responseHeaders
2700
+ parts:parts
2701
+ bytesUploaded:taskConfig.bytesTotal
2702
+ bytesTotal:taskConfig.bytesTotal];
2703
+ }
2704
+
2705
+ - (void)emitUploadComplete:(NSString *)identifier
2706
+ responseCode:(NSInteger)responseCode
2707
+ responseBody:(NSString *)responseBody
2708
+ responseHeaders:(NSDictionary *)responseHeaders
2709
+ parts:(nullable NSArray<NSDictionary *> *)parts
2710
+ bytesUploaded:(long long)bytesUploaded
2711
+ bytesTotal:(long long)bytesTotal {
2712
+ NSMutableDictionary *body = [@{
2713
+ @"id": identifier,
2714
+ @"responseCode": @(responseCode),
2715
+ @"responseBody": responseBody ?: @"",
2716
+ @"responseHeaders": responseHeaders ?: @{},
2717
+ @"bytesUploaded": @(bytesUploaded),
2718
+ @"bytesTotal": @(bytesTotal)
2719
+ } mutableCopy];
2720
+ if (parts != nil) {
2721
+ body[@"parts"] = parts;
2722
+ }
2723
+ #ifdef RCT_NEW_ARCH_ENABLED
2724
+ [self safeEmitEvent:@"onUploadComplete" value:body];
2725
+ #else
2726
+ [self sendEventWithName:@"uploadComplete" body:body];
2727
+ #endif
2728
+ }
2729
+
2730
+ // The tasks of an upload: one, or one per part. Must hold sharedLock
2731
+ - (NSArray<NSURLSessionUploadTask *> *)uploadTasksForId:(NSString *)identifier {
2732
+ NSArray<NSURLSessionUploadTask *> *parts = idToUploadPartTasks[identifier];
2733
+ if (parts != nil) {
2734
+ return [parts copy];
2735
+ }
2736
+ NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
2737
+ return task != nil ? @[task] : @[];
2738
+ }
2739
+
1840
2740
  - (void)pauseUploadTaskInternal:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
1841
2741
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseUploadTask]");
1842
2742
  @try {
1843
2743
  @synchronized (sharedLock) {
1844
- NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
1845
- if (task != nil) {
2744
+ NSArray<NSURLSessionUploadTask *> *tasks = [self uploadTasksForId:identifier];
2745
+ if (tasks.count > 0) {
1846
2746
  [idsToUploadPauseSet addObject:identifier];
1847
- [task suspend];
2747
+ for (NSURLSessionUploadTask *task in tasks) {
2748
+ [task suspend];
2749
+ }
1848
2750
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseUploadTask] suspended upload task: %@", identifier);
1849
2751
  }
1850
2752
  }
@@ -1871,9 +2773,14 @@ RCT_EXPORT_METHOD(pauseUploadTask:(NSString *)id resolver:(RCTPromiseResolveBloc
1871
2773
  [self lazyRegisterSession];
1872
2774
  [idsToUploadPauseSet removeObject:identifier];
1873
2775
 
1874
- NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
1875
- if (task != nil && task.state == NSURLSessionTaskStateSuspended) {
1876
- [task resume];
2776
+ BOOL resumed = NO;
2777
+ for (NSURLSessionUploadTask *task in [self uploadTasksForId:identifier]) {
2778
+ if (task.state == NSURLSessionTaskStateSuspended) {
2779
+ [task resume];
2780
+ resumed = YES;
2781
+ }
2782
+ }
2783
+ if (resumed) {
1877
2784
  DLog(identifier, @"[RNBackgroundDownloader] - [resumeUploadTask] resumed upload task: %@", identifier);
1878
2785
  } else {
1879
2786
  DLog(identifier, @"[RNBackgroundDownloader] - [resumeUploadTask] no suspended upload task found for %@", identifier);
@@ -1900,11 +2807,33 @@ RCT_EXPORT_METHOD(resumeUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlo
1900
2807
  @try {
1901
2808
  @synchronized (sharedLock) {
1902
2809
  NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
1903
- if (task != nil) {
2810
+ RNBGDUploadTaskConfig *partConfig = nil;
2811
+ for (RNBGDUploadTaskConfig *config in uploadTaskToConfigMap.allValues) {
2812
+ if (config.partUrls != nil && [config.id isEqualToString:identifier]) {
2813
+ partConfig = config;
2814
+ break;
2815
+ }
2816
+ }
2817
+ if (partConfig != nil) {
2818
+ [self forgetPartUploadTasks:partConfig cancel:YES];
2819
+ } else if (task != nil) {
1904
2820
  [task cancel];
1905
2821
  [self removeUploadTaskFromMap:task];
2822
+ } else {
2823
+ // A config restored after a relaunch with no live task: remove it, or it's
2824
+ // listed by getExistingUploadTasks on every launch
2825
+ for (NSNumber *key in [uploadTaskToConfigMap allKeys]) {
2826
+ RNBGDUploadTaskConfig *config = uploadTaskToConfigMap[key];
2827
+ if ([config.id isEqualToString:identifier]) {
2828
+ [uploadTaskToConfigMap removeObjectForKey:key];
2829
+ }
2830
+ }
2831
+ [mmkv setData:[self serializeUploadConfig:uploadTaskToConfigMap] forKey:ID_TO_UPLOAD_CONFIG_MAP_KEY];
1906
2832
  }
1907
2833
  [idsToUploadPauseSet removeObject:identifier];
2834
+ [self removeMultipartTempFileForUploadId:identifier];
2835
+ // Also how JS acknowledges a finished upload's response
2836
+ [self dropFinishedUpload:identifier];
1908
2837
  }
1909
2838
  resolve(nil);
1910
2839
  } @catch (NSException *exception) {
@@ -1938,9 +2867,28 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
1938
2867
  NSMutableSet *processedIds = [[NSMutableSet alloc] init];
1939
2868
 
1940
2869
  // Phase 1: Process active upload tasks from session
2870
+ [self->idToUploadPartTasks removeAllObjects];
1941
2871
  for (NSURLSessionUploadTask *task in uploadTasks) {
1942
2872
  RNBGDUploadTaskConfig *taskConfig = [self uploadConfigForTask:task];
1943
2873
 
2874
+ if (taskConfig && taskConfig.partUrls != nil) {
2875
+ // One upload, several part tasks: listed once, with the bytes of all parts
2876
+ NSMutableArray *partTasks = self->idToUploadPartTasks[taskConfig.id];
2877
+ if (partTasks == nil) {
2878
+ partTasks = [NSMutableArray array];
2879
+ self->idToUploadPartTasks[taskConfig.id] = partTasks;
2880
+ }
2881
+ [partTasks addObject:task];
2882
+ self->uploadPartBytesSent[@(task.taskIdentifier)] = @(task.countOfBytesSent);
2883
+ if ([processedIds containsObject:taskConfig.id]) {
2884
+ continue;
2885
+ }
2886
+ [processedIds addObject:taskConfig.id];
2887
+ taskConfig.state = task.state;
2888
+ [foundTasks addObject:taskConfig.id];
2889
+ continue;
2890
+ }
2891
+
1944
2892
  if (taskConfig) {
1945
2893
  taskConfig.state = task.state;
1946
2894
  taskConfig.bytesUploaded = task.countOfBytesSent;
@@ -1962,6 +2910,29 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
1962
2910
  }
1963
2911
  }
1964
2912
 
2913
+ // Part uploads were held back above until every part task was counted
2914
+ for (NSUInteger i = 0; i < foundTasks.count; i++) {
2915
+ if (![foundTasks[i] isKindOfClass:[NSString class]]) {
2916
+ continue;
2917
+ }
2918
+ RNBGDUploadTaskConfig *taskConfig = nil;
2919
+ for (RNBGDUploadTaskConfig *config in self->uploadTaskToConfigMap.allValues) {
2920
+ if ([config.id isEqualToString:foundTasks[i]]) {
2921
+ taskConfig = config;
2922
+ break;
2923
+ }
2924
+ }
2925
+ taskConfig.bytesUploaded = [self bytesSentForPartUpload:taskConfig];
2926
+ foundTasks[i] = @{
2927
+ @"id": taskConfig.id,
2928
+ @"metadata": taskConfig.metadata,
2929
+ @"state": @(taskConfig.state),
2930
+ @"bytesUploaded": @(taskConfig.bytesUploaded),
2931
+ @"bytesTotal": @(taskConfig.bytesTotal),
2932
+ @"errorCode": [NSNull null]
2933
+ };
2934
+ }
2935
+
1965
2936
  // Phase 2: Add persisted upload configs that are not active (for app restart recovery)
1966
2937
  // Uploads cannot truly resume like downloads, but we preserve their metadata
1967
2938
  // so the user can restart them
@@ -1986,6 +2957,30 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
1986
2957
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [getExistingUploadTasks] restored persisted upload task: %@", taskConfig.id);
1987
2958
  }
1988
2959
 
2960
+ // Phase 3: Uploads that finished while JS wasn't listening, with their response.
2961
+ // JS acknowledges them (stopUploadTask), which drops them
2962
+ for (RNBGDUploadTaskConfig *taskConfig in self->finishedUploads.allValues) {
2963
+ if ([processedIds containsObject:taskConfig.id]) {
2964
+ continue;
2965
+ }
2966
+ NSMutableDictionary *taskInfo = [@{
2967
+ @"id": taskConfig.id,
2968
+ @"metadata": taskConfig.metadata,
2969
+ @"state": @(NSURLSessionTaskStateCompleted),
2970
+ @"bytesUploaded": @(taskConfig.bytesTotal),
2971
+ @"bytesTotal": @(taskConfig.bytesTotal),
2972
+ @"errorCode": [NSNull null],
2973
+ @"responseCode": @(taskConfig.responseCode),
2974
+ @"responseBody": taskConfig.responseBody ?: @"",
2975
+ @"responseHeaders": taskConfig.responseHeaders ?: @{}
2976
+ } mutableCopy];
2977
+ if (taskConfig.partUrls != nil) {
2978
+ taskInfo[@"parts"] = [taskConfig orderedPartResults];
2979
+ }
2980
+ [foundTasks addObject:taskInfo];
2981
+ [processedIds addObject:taskConfig.id];
2982
+ }
2983
+
1989
2984
  resolve(foundTasks);
1990
2985
  } @catch (NSException *exception) {
1991
2986
  reject(@"ERR_GET_EXISTING_UPLOAD_TASKS", exception.reason, nil);
@@ -2010,6 +3005,13 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2010
3005
  return;
2011
3006
  }
2012
3007
 
3008
+ // An upload in parts reports the sum of its parts against the file size
3009
+ if (taskConfig.partUrls != nil) {
3010
+ uploadPartBytesSent[@(task.taskIdentifier)] = @(totalBytesSent);
3011
+ totalBytesSent = [self bytesSentForPartUpload:taskConfig];
3012
+ totalBytesExpectedToSend = taskConfig.bytesTotal;
3013
+ }
3014
+
2013
3015
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didSendBodyData] %lld/%lld", totalBytesSent, totalBytesExpectedToSend);
2014
3016
 
2015
3017
  // Report begin if needed
@@ -2028,7 +3030,10 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2028
3030
  #endif
2029
3031
  }
2030
3032
 
2031
- // Update progress
3033
+ // Update progress, unless the app has paused the upload
3034
+ if ([idsToUploadPauseSet containsObject:taskConfig.id]) {
3035
+ return;
3036
+ }
2032
3037
  NSNumber *prevPercent = idToUploadPercentMap[taskConfig.id] ?: @0.0;
2033
3038
  NSNumber *prevBytes = idToUploadLastBytesMap[taskConfig.id] ?: @0;
2034
3039
  float currentPercent = totalBytesExpectedToSend > 0 ? (float)totalBytesSent / (float)totalBytesExpectedToSend : 0.0;
@@ -2075,14 +3080,38 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2075
3080
  return;
2076
3081
  }
2077
3082
 
2078
- if (taskConfig.responseData == nil) {
2079
- taskConfig.responseData = [[NSMutableData alloc] init];
3083
+ // Per task: the parts of an upload receive their responses at the same time
3084
+ NSNumber *taskKey = @(dataTask.taskIdentifier);
3085
+ NSMutableData *responseData = uploadResponseDataByTask[taskKey];
3086
+ if (responseData == nil) {
3087
+ responseData = [[NSMutableData alloc] init];
3088
+ uploadResponseDataByTask[taskKey] = responseData;
3089
+ }
3090
+ // The body goes to JS as one string: cap it, so a hostile or broken server
3091
+ // can't run the app (or its background relaunch) out of memory
3092
+ NSUInteger room = kMaxUploadResponseBytes > responseData.length
3093
+ ? kMaxUploadResponseBytes - responseData.length : 0;
3094
+ if (room > 0) {
3095
+ [responseData appendData:data.length > room ? [data subdataWithRange:NSMakeRange(0, room)] : data];
2080
3096
  }
2081
- [taskConfig.responseData appendData:data];
2082
3097
  }
2083
3098
  }
2084
3099
 
2085
3100
  // Handle upload completion (override the existing method to also handle uploads)
3101
+ // Multipart bodies are written to a temp file named after the upload, so it can be
3102
+ // removed once the upload is over without persisting its path
3103
+ - (NSString *)multipartTempPathForUploadId:(NSString *)identifier {
3104
+ NSString *safeId = [identifier stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
3105
+ return [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"RNBGD-upload-%@.multipart", safeId]];
3106
+ }
3107
+
3108
+ - (void)removeMultipartTempFileForUploadId:(NSString *)identifier {
3109
+ if (identifier == nil) {
3110
+ return;
3111
+ }
3112
+ [[NSFileManager defaultManager] removeItemAtPath:[self multipartTempPathForUploadId:identifier] error:nil];
3113
+ }
3114
+
2086
3115
  - (void)handleUploadCompletion:(NSURLSessionTask *)task error:(NSError *)error {
2087
3116
  @synchronized (sharedLock) {
2088
3117
  RNBGDUploadTaskConfig *taskConfig = [self uploadConfigForTask:task];
@@ -2096,7 +3125,21 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2096
3125
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - upload was paused, ignoring error");
2097
3126
  return;
2098
3127
  }
3128
+ }
3129
+
3130
+ NSNumber *taskKey = @(task.taskIdentifier);
3131
+ NSData *responseData = uploadResponseDataByTask[taskKey];
3132
+ [uploadResponseDataByTask removeObjectForKey:taskKey];
2099
3133
 
3134
+ if (taskConfig.partUrls != nil) {
3135
+ [self handlePartCompletion:task config:taskConfig responseData:responseData error:error];
3136
+ return;
3137
+ }
3138
+
3139
+ // The upload is over (failed or done); a paused one returned above and keeps its body
3140
+ [self removeMultipartTempFileForUploadId:taskConfig.id];
3141
+
3142
+ if (error) {
2100
3143
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [handleUploadCompletion] error: %@", error);
2101
3144
  #ifdef RCT_NEW_ARCH_ENABLED
2102
3145
  [self safeEmitEvent:@"onUploadFailed" value:@{
@@ -2119,28 +3162,29 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2119
3162
  }
2120
3163
 
2121
3164
  NSString *responseBody = @"";
2122
- if (taskConfig.responseData) {
2123
- responseBody = [[NSString alloc] initWithData:taskConfig.responseData encoding:NSUTF8StringEncoding] ?: @"";
3165
+ if (responseData) {
3166
+ responseBody = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ?: @"";
2124
3167
  }
3168
+ NSDictionary *responseHeaders = [self lowercasedHeadersOfResponse:task.response];
3169
+
3170
+ // Kept until JS has it: the upload may have finished while the app wasn't running
3171
+ taskConfig.responseCode = responseCode;
3172
+ taskConfig.responseBody = responseBody;
3173
+ taskConfig.responseHeaders = responseHeaders;
3174
+ taskConfig.bytesTotal = task.countOfBytesExpectedToSend;
3175
+ taskConfig.bytesUploaded = task.countOfBytesExpectedToSend;
3176
+ taskConfig.state = NSURLSessionTaskStateCompleted;
3177
+ finishedUploads[taskConfig.id] = taskConfig;
3178
+ [self persistFinishedUploads];
2125
3179
 
2126
3180
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [handleUploadCompletion] success, responseCode: %ld", (long)responseCode);
2127
- #ifdef RCT_NEW_ARCH_ENABLED
2128
- [self safeEmitEvent:@"onUploadComplete" value:@{
2129
- @"id": taskConfig.id,
2130
- @"responseCode": @(responseCode),
2131
- @"responseBody": responseBody,
2132
- @"bytesUploaded": @(task.countOfBytesSent),
2133
- @"bytesTotal": @(task.countOfBytesExpectedToSend)
2134
- }];
2135
- #else
2136
- [self sendEventWithName:@"uploadComplete" body:@{
2137
- @"id": taskConfig.id,
2138
- @"responseCode": @(responseCode),
2139
- @"responseBody": responseBody,
2140
- @"bytesUploaded": @(task.countOfBytesSent),
2141
- @"bytesTotal": @(task.countOfBytesExpectedToSend)
2142
- }];
2143
- #endif
3181
+ [self emitUploadComplete:taskConfig.id
3182
+ responseCode:responseCode
3183
+ responseBody:responseBody
3184
+ responseHeaders:responseHeaders
3185
+ parts:nil
3186
+ bytesUploaded:task.countOfBytesSent
3187
+ bytesTotal:task.countOfBytesExpectedToSend];
2144
3188
  }
2145
3189
 
2146
3190
  [self removeUploadTaskFromMap:task];
@@ -2153,18 +3197,31 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2153
3197
  NSString *sessionIdentifier =
2154
3198
  [bundleIdentifier stringByAppendingString:@".backgrounddownloadtask"];
2155
3199
  if ([sessionIdentifier isEqualToString:identifier]) {
3200
+ // Called on the main queue by the AppDelegate. A handler left from an earlier launch
3201
+ // must still be called, not dropped
3202
+ if (storedCompletionHandler) {
3203
+ CompletionHandler previous = storedCompletionHandler;
3204
+ storedCompletionHandler = nil;
3205
+ previous();
3206
+ }
2156
3207
  storedCompletionHandler = completionHandler;
3208
+ backgroundEventsFinished = NO;
3209
+ if (idsAwaitingCompleteHandler == nil) {
3210
+ idsAwaitingCompleteHandler = [NSMutableSet new];
3211
+ }
3212
+ [idsAwaitingCompleteHandler removeAllObjects];
2157
3213
 
2158
- // Set a timeout to prevent memory leak if JS never calls completeHandler
2159
- // iOS requires the completion handler to be called within 30 seconds
2160
- // Copy the handler to a local variable to avoid retain cycle with static variable
3214
+ // Call it anyway before the background time runs out, e.g. if JS never calls
3215
+ // completeHandler for a task. Copy the handler to avoid a retain cycle with the static
2161
3216
  __block CompletionHandler handlerToCall = completionHandler;
2162
3217
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kCompletionHandlerTimeout * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
2163
3218
  // Check if this is still the same handler (not already called or replaced)
2164
3219
  if (storedCompletionHandler && storedCompletionHandler == handlerToCall) {
2165
3220
  DLogStatic(nil, @"[RNBackgroundDownloader] - [setCompletionHandlerWithIdentifier] timeout - calling completion handler automatically");
2166
- storedCompletionHandler();
2167
3221
  storedCompletionHandler = nil;
3222
+ backgroundEventsFinished = NO;
3223
+ [idsAwaitingCompleteHandler removeAllObjects];
3224
+ handlerToCall();
2168
3225
  }
2169
3226
  handlerToCall = nil; // Release the block reference
2170
3227
  });
@@ -2200,6 +3257,17 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2200
3257
  return NSFileProtectionCompleteUntilFirstUserAuthentication;
2201
3258
  }
2202
3259
 
3260
+ // The destination in the app's current container: its absolute path changes when the app
3261
+ // is updated, its path relative to the container doesn't. nil if it isn't in the container.
3262
+ - (NSString *)currentPathForDestination:(NSString *)destination {
3263
+ NSString *rootPath = [self getRootPathFromPath:destination];
3264
+ NSString *fileRelativePath = [self getRelativeFilePathFromPath:destination];
3265
+ if (rootPath == nil || fileRelativePath == nil) {
3266
+ return nil;
3267
+ }
3268
+ return [rootPath stringByAppendingPathComponent:fileRelativePath];
3269
+ }
3270
+
2203
3271
  - (BOOL)saveFile: (nonnull RNBGDTaskConfig *) taskConfig downloadURL:(nonnull NSURL *)location bytesDownloaded:(int64_t)bytesDownloaded bytesTotal:(int64_t)bytesTotal error:(NSError **)saveError deferred:(BOOL *)deferred {
2204
3272
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [saveFile]");
2205
3273
  if (deferred) *deferred = NO;
@@ -2207,11 +3275,10 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2207
3275
  // The absolute path may change when the application is restarted.
2208
3276
  // But the relative path remains the same.
2209
3277
  // Relative paths are used to recreate the Absolute path.
2210
- NSString *rootPath = [self getRootPathFromPath:taskConfig.destination];
2211
- NSString *fileRelativePath = [self getRelativeFilePathFromPath:taskConfig.destination];
3278
+ NSString *fileAbsolutePath = [self currentPathForDestination:taskConfig.destination];
2212
3279
 
2213
3280
  // Check for nil paths to prevent crash
2214
- if (rootPath == nil || fileRelativePath == nil) {
3281
+ if (fileAbsolutePath == nil) {
2215
3282
  if (saveError) {
2216
3283
  *saveError = [NSError errorWithDomain:NSURLErrorDomain
2217
3284
  code:NSURLErrorFileDoesNotExist
@@ -2220,7 +3287,6 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2220
3287
  return NO;
2221
3288
  }
2222
3289
 
2223
- NSString *fileAbsolutePath = [rootPath stringByAppendingPathComponent:fileRelativePath];
2224
3290
  NSURL *destinationURL = [NSURL fileURLWithPath:fileAbsolutePath];
2225
3291
 
2226
3292
  NSFileManager *fileManager = [NSFileManager defaultManager];
@@ -2256,18 +3322,20 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2256
3322
 
2257
3323
  #pragma mark - Locked-device deferred move (issue #101)
2258
3324
 
2259
- // Directory (with NSFileProtectionNone) used to hold finished downloads whose move to the
2260
- // final destination is deferred because the device is locked.
3325
+ // Directory used to hold finished downloads whose move to the final destination is deferred
3326
+ // because the device is locked. CompleteUntilFirstUserAuthentication can be written while
3327
+ // locked (background sessions only run after the first unlock), unlike Complete, without
3328
+ // leaving the file unprotected the way None would.
2261
3329
  - (NSURL *)pendingMovesDirectory {
2262
3330
  NSFileManager *fileManager = [NSFileManager defaultManager];
2263
3331
  NSURL *cachesDir = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject];
2264
3332
  NSURL *dir = [cachesDir URLByAppendingPathComponent:@"RNBGDPendingMoves" isDirectory:YES];
3333
+ NSDictionary *attributes = @{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication};
2265
3334
  if (![fileManager fileExistsAtPath:dir.path]) {
2266
- // NSFileProtectionNone so we can write here even while the device is locked.
2267
- [fileManager createDirectoryAtURL:dir
2268
- withIntermediateDirectories:YES
2269
- attributes:@{NSFileProtectionKey: NSFileProtectionNone}
2270
- error:nil];
3335
+ [fileManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:attributes error:nil];
3336
+ } else {
3337
+ // Older versions created it with NSFileProtectionNone
3338
+ [fileManager setAttributes:attributes ofItemAtPath:dir.path error:nil];
2271
3339
  }
2272
3340
  return dir;
2273
3341
  }
@@ -2284,8 +3352,8 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2284
3352
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [stageAndDeferMove] staging failed: %@", stageError.localizedDescription);
2285
3353
  return NO;
2286
3354
  }
2287
- // Make sure the staged file is readable while locked.
2288
- [fileManager setAttributes:@{NSFileProtectionKey: NSFileProtectionNone} ofItemAtPath:stagingURL.path error:nil];
3355
+ // Movable while locked, but still encrypted at rest (see pendingMovesDirectory)
3356
+ [fileManager setAttributes:@{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication} ofItemAtPath:stagingURL.path error:nil];
2289
3357
 
2290
3358
  pendingMoves[taskConfig.id] = @{
2291
3359
  @"id": taskConfig.id,
@@ -2434,7 +3502,7 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2434
3502
  - (NSMutableDictionary<NSNumber *, RNBGDUploadTaskConfig *> *)deserializeUploadConfig:(NSData *)taskMapRaw {
2435
3503
  NSError *error = nil;
2436
3504
  // Creates a list of classes that can be stored.
2437
- NSSet *classes = [NSSet setWithObjects:[RNBGDUploadTaskConfig class], [NSMutableDictionary class], [NSNumber class], [NSString class], [NSDictionary class], nil];
3505
+ NSSet *classes = [NSSet setWithObjects:[RNBGDUploadTaskConfig class], [NSMutableDictionary class], [NSNumber class], [NSString class], [NSDictionary class], [NSArray class], nil];
2438
3506
  NSMutableDictionary<NSNumber *, RNBGDUploadTaskConfig *> *taskMap = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:taskMapRaw error:&error];
2439
3507
 
2440
3508
  if (error) {
@@ -2473,11 +3541,13 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2473
3541
  NSString *dataPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByDeletingLastPathComponent];
2474
3542
  NSString *dataPathWithoutUuid = [self getPathWithoutSuffixUuid:dataPath];
2475
3543
 
2476
- if ([path hasPrefix:bundlePathWithoutUuid]) {
3544
+ // A path shorter than the container (e.g. ".../Data/Application" itself) would make
3545
+ // substringFromIndex: throw outside any @try, crashing the app
3546
+ if ([path hasPrefix:bundlePathWithoutUuid] && path.length >= bundlePath.length) {
2477
3547
  return [path substringFromIndex:[bundlePath length]];
2478
3548
  }
2479
3549
 
2480
- if ([path hasPrefix:dataPathWithoutUuid]) {
3550
+ if ([path hasPrefix:dataPathWithoutUuid] && path.length >= dataPath.length) {
2481
3551
  return [path substringFromIndex:[dataPath length]];
2482
3552
  }
2483
3553