@kesha-antonov/react-native-background-downloader 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +75 -32
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +5 -0
  3. package/android/src/main/java/com/eko/Downloader.kt +12 -5
  4. package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +36 -1
  5. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +94 -54
  6. package/android/src/main/java/com/eko/ResumableDownloader.kt +34 -13
  7. package/android/src/main/java/com/eko/UnmeteredNetworkGate.kt +134 -17
  8. package/android/src/main/java/com/eko/UploadEventEmitter.kt +26 -1
  9. package/android/src/main/java/com/eko/Uploader.kt +187 -17
  10. package/android/src/main/java/com/eko/handlers/OnProgress.kt +1 -1
  11. package/android/src/main/java/com/eko/utils/HeaderUtils.kt +9 -0
  12. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +29 -1
  13. package/android/src/test/java/com/eko/DownloadCompleteReceiverTest.kt +57 -0
  14. package/android/src/test/java/com/eko/ResumableDownloaderRedirectTest.kt +77 -0
  15. package/android/src/test/java/com/eko/UnmeteredNetworkGateTest.kt +248 -0
  16. package/android/src/test/java/com/eko/UploadPartRangesTest.kt +33 -0
  17. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +10 -1
  18. package/android/src/test/java/com/eko/UploaderPartsTest.kt +222 -0
  19. package/android/src/test/java/com/eko/UploaderResponseTest.kt +26 -0
  20. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +66 -0
  21. package/ios/RNBGDUploadTaskConfig.h +26 -0
  22. package/ios/RNBGDUploadTaskConfig.mm +69 -3
  23. package/ios/RNBackgroundDownloader.mm +563 -43
  24. package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
  25. package/lib/UploadTask.d.ts +5 -1
  26. package/lib/UploadTask.js +22 -4
  27. package/lib/index.js +57 -27
  28. package/lib/types.d.ts +33 -2
  29. package/package.json +1 -1
  30. package/src/NativeRNBackgroundDownloader.ts +23 -0
  31. package/src/UploadTask.ts +23 -1
  32. package/src/index.ts +60 -27
  33. package/src/types.ts +42 -2
@@ -12,6 +12,8 @@
12
12
 
13
13
  #define ID_TO_CONFIG_MAP_KEY @"com.eko.bgdownloadidmap"
14
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"
15
17
  #define PROGRESS_INTERVAL_KEY @"progressInterval"
16
18
  #define PROGRESS_MIN_BYTES_KEY @"progressMinBytes"
17
19
  #define MAX_PARALLEL_DOWNLOADS_KEY @"maxParallelDownloads"
@@ -37,6 +39,10 @@ static const NSTimeInterval kStallTimeout = 20.0;
37
39
  static const NSTimeInterval kStallCheckInterval = 5.0;
38
40
  // Times in a row a download cut off by the network continues from its resume data
39
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;
40
46
 
41
47
  // DLog accepts taskId as first parameter to help debugging
42
48
  // Only logs if isLogsEnabled is true (works in both DEBUG and RELEASE builds)
@@ -172,6 +178,15 @@ static void callCompletionHandlerIfDone(void) {
172
178
  NSMutableDictionary<NSString *, NSNumber *> *idToUploadLastBytesMap;
173
179
  NSMutableSet<NSString *> *idsToUploadPauseSet;
174
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;
175
190
  }
176
191
 
177
192
  RCT_EXPORT_MODULE();
@@ -394,6 +409,12 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
394
409
  idToUploadLastBytesMap = [[NSMutableDictionary alloc] init];
395
410
  idsToUploadPauseSet = [[NSMutableSet alloc] init];
396
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];
397
418
 
398
419
  [self registerBridgeListener];
399
420
 
@@ -751,6 +772,9 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
751
772
  [idToNetworkResumeCount removeObjectForKey:taskConfig.id];
752
773
  // Clean up decode error retry tracking to prevent memory leak
753
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];
754
778
  }
755
779
  }
756
780
  }
@@ -1665,7 +1689,11 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1665
1689
 
1666
1690
  NSURL *fileURL = [self resumeDataFileURLForTaskId:taskId];
1667
1691
  NSError *error = nil;
1668
- 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];
1669
1697
 
1670
1698
  if (!success) {
1671
1699
  DLog(taskId, @"[RNBackgroundDownloader] - [saveResumeData] failed to save resume data: %@", error.localizedDescription);
@@ -2140,6 +2168,15 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
2140
2168
  NSString *mimeType = options.mimeType() ? options.mimeType() : nil;
2141
2169
  NSDictionary *parameters = options.parameters() ? (NSDictionary *)options.parameters() : nil;
2142
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;
2143
2180
 
2144
2181
  if (options.progressInterval().has_value()) {
2145
2182
  progressInterval = options.progressInterval().value() / 1000.0;
@@ -2164,6 +2201,8 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
2164
2201
  NSDictionary *parameters = options[@"parameters"];
2165
2202
  NSNumber *isAllowedOverMetered = options[@"isAllowedOverMetered"];
2166
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;
2167
2206
 
2168
2207
  NSNumber *progressIntervalScope = options[@"progressInterval"];
2169
2208
  if (progressIntervalScope) {
@@ -2185,8 +2224,23 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
2185
2224
  return;
2186
2225
  }
2187
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
+
2188
2240
  @try {
2189
2241
  @synchronized (sharedLock) {
2242
+ // A new upload with this id replaces a finished one's kept response
2243
+ [self dropFinishedUpload:identifier];
2190
2244
  [self sendDebugLog:@"upload: calling lazyRegisterSession" taskId:identifier];
2191
2245
  [self lazyRegisterSession];
2192
2246
 
@@ -2292,7 +2346,11 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
2292
2346
 
2293
2347
  // Write body to temp file for background upload
2294
2348
  NSString *tempPath = [self multipartTempPathForUploadId:identifier];
2295
- if (![body writeToFile:tempPath atomically:YES]) {
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]) {
2296
2354
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not write multipart body to temp file");
2297
2355
  [self emitUploadFailed:identifier error:@"Could not write multipart body to temp file" errorCode:NSURLErrorCannotWriteToFile];
2298
2356
  return;
@@ -2332,14 +2390,363 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
2332
2390
  }
2333
2391
  }
2334
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
+
2335
2740
  - (void)pauseUploadTaskInternal:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
2336
2741
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseUploadTask]");
2337
2742
  @try {
2338
2743
  @synchronized (sharedLock) {
2339
- NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
2340
- if (task != nil) {
2744
+ NSArray<NSURLSessionUploadTask *> *tasks = [self uploadTasksForId:identifier];
2745
+ if (tasks.count > 0) {
2341
2746
  [idsToUploadPauseSet addObject:identifier];
2342
- [task suspend];
2747
+ for (NSURLSessionUploadTask *task in tasks) {
2748
+ [task suspend];
2749
+ }
2343
2750
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseUploadTask] suspended upload task: %@", identifier);
2344
2751
  }
2345
2752
  }
@@ -2366,9 +2773,14 @@ RCT_EXPORT_METHOD(pauseUploadTask:(NSString *)id resolver:(RCTPromiseResolveBloc
2366
2773
  [self lazyRegisterSession];
2367
2774
  [idsToUploadPauseSet removeObject:identifier];
2368
2775
 
2369
- NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
2370
- if (task != nil && task.state == NSURLSessionTaskStateSuspended) {
2371
- [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) {
2372
2784
  DLog(identifier, @"[RNBackgroundDownloader] - [resumeUploadTask] resumed upload task: %@", identifier);
2373
2785
  } else {
2374
2786
  DLog(identifier, @"[RNBackgroundDownloader] - [resumeUploadTask] no suspended upload task found for %@", identifier);
@@ -2395,7 +2807,16 @@ RCT_EXPORT_METHOD(resumeUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlo
2395
2807
  @try {
2396
2808
  @synchronized (sharedLock) {
2397
2809
  NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
2398
- 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) {
2399
2820
  [task cancel];
2400
2821
  [self removeUploadTaskFromMap:task];
2401
2822
  } else {
@@ -2411,6 +2832,8 @@ RCT_EXPORT_METHOD(resumeUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlo
2411
2832
  }
2412
2833
  [idsToUploadPauseSet removeObject:identifier];
2413
2834
  [self removeMultipartTempFileForUploadId:identifier];
2835
+ // Also how JS acknowledges a finished upload's response
2836
+ [self dropFinishedUpload:identifier];
2414
2837
  }
2415
2838
  resolve(nil);
2416
2839
  } @catch (NSException *exception) {
@@ -2444,9 +2867,28 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
2444
2867
  NSMutableSet *processedIds = [[NSMutableSet alloc] init];
2445
2868
 
2446
2869
  // Phase 1: Process active upload tasks from session
2870
+ [self->idToUploadPartTasks removeAllObjects];
2447
2871
  for (NSURLSessionUploadTask *task in uploadTasks) {
2448
2872
  RNBGDUploadTaskConfig *taskConfig = [self uploadConfigForTask:task];
2449
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
+
2450
2892
  if (taskConfig) {
2451
2893
  taskConfig.state = task.state;
2452
2894
  taskConfig.bytesUploaded = task.countOfBytesSent;
@@ -2468,6 +2910,29 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
2468
2910
  }
2469
2911
  }
2470
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
+
2471
2936
  // Phase 2: Add persisted upload configs that are not active (for app restart recovery)
2472
2937
  // Uploads cannot truly resume like downloads, but we preserve their metadata
2473
2938
  // so the user can restart them
@@ -2492,6 +2957,30 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
2492
2957
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [getExistingUploadTasks] restored persisted upload task: %@", taskConfig.id);
2493
2958
  }
2494
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
+
2495
2984
  resolve(foundTasks);
2496
2985
  } @catch (NSException *exception) {
2497
2986
  reject(@"ERR_GET_EXISTING_UPLOAD_TASKS", exception.reason, nil);
@@ -2516,6 +3005,13 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2516
3005
  return;
2517
3006
  }
2518
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
+
2519
3015
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didSendBodyData] %lld/%lld", totalBytesSent, totalBytesExpectedToSend);
2520
3016
 
2521
3017
  // Report begin if needed
@@ -2584,10 +3080,20 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2584
3080
  return;
2585
3081
  }
2586
3082
 
2587
- if (taskConfig.responseData == nil) {
2588
- 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];
2589
3096
  }
2590
- [taskConfig.responseData appendData:data];
2591
3097
  }
2592
3098
  }
2593
3099
 
@@ -2621,6 +3127,15 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2621
3127
  }
2622
3128
  }
2623
3129
 
3130
+ NSNumber *taskKey = @(task.taskIdentifier);
3131
+ NSData *responseData = uploadResponseDataByTask[taskKey];
3132
+ [uploadResponseDataByTask removeObjectForKey:taskKey];
3133
+
3134
+ if (taskConfig.partUrls != nil) {
3135
+ [self handlePartCompletion:task config:taskConfig responseData:responseData error:error];
3136
+ return;
3137
+ }
3138
+
2624
3139
  // The upload is over (failed or done); a paused one returned above and keeps its body
2625
3140
  [self removeMultipartTempFileForUploadId:taskConfig.id];
2626
3141
 
@@ -2647,28 +3162,29 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2647
3162
  }
2648
3163
 
2649
3164
  NSString *responseBody = @"";
2650
- if (taskConfig.responseData) {
2651
- responseBody = [[NSString alloc] initWithData:taskConfig.responseData encoding:NSUTF8StringEncoding] ?: @"";
3165
+ if (responseData) {
3166
+ responseBody = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ?: @"";
2652
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];
2653
3179
 
2654
3180
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [handleUploadCompletion] success, responseCode: %ld", (long)responseCode);
2655
- #ifdef RCT_NEW_ARCH_ENABLED
2656
- [self safeEmitEvent:@"onUploadComplete" value:@{
2657
- @"id": taskConfig.id,
2658
- @"responseCode": @(responseCode),
2659
- @"responseBody": responseBody,
2660
- @"bytesUploaded": @(task.countOfBytesSent),
2661
- @"bytesTotal": @(task.countOfBytesExpectedToSend)
2662
- }];
2663
- #else
2664
- [self sendEventWithName:@"uploadComplete" body:@{
2665
- @"id": taskConfig.id,
2666
- @"responseCode": @(responseCode),
2667
- @"responseBody": responseBody,
2668
- @"bytesUploaded": @(task.countOfBytesSent),
2669
- @"bytesTotal": @(task.countOfBytesExpectedToSend)
2670
- }];
2671
- #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];
2672
3188
  }
2673
3189
 
2674
3190
  [self removeUploadTaskFromMap:task];
@@ -2806,18 +3322,20 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2806
3322
 
2807
3323
  #pragma mark - Locked-device deferred move (issue #101)
2808
3324
 
2809
- // Directory (with NSFileProtectionNone) used to hold finished downloads whose move to the
2810
- // 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.
2811
3329
  - (NSURL *)pendingMovesDirectory {
2812
3330
  NSFileManager *fileManager = [NSFileManager defaultManager];
2813
3331
  NSURL *cachesDir = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject];
2814
3332
  NSURL *dir = [cachesDir URLByAppendingPathComponent:@"RNBGDPendingMoves" isDirectory:YES];
3333
+ NSDictionary *attributes = @{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication};
2815
3334
  if (![fileManager fileExistsAtPath:dir.path]) {
2816
- // NSFileProtectionNone so we can write here even while the device is locked.
2817
- [fileManager createDirectoryAtURL:dir
2818
- withIntermediateDirectories:YES
2819
- attributes:@{NSFileProtectionKey: NSFileProtectionNone}
2820
- 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];
2821
3339
  }
2822
3340
  return dir;
2823
3341
  }
@@ -2834,8 +3352,8 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2834
3352
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [stageAndDeferMove] staging failed: %@", stageError.localizedDescription);
2835
3353
  return NO;
2836
3354
  }
2837
- // Make sure the staged file is readable while locked.
2838
- [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];
2839
3357
 
2840
3358
  pendingMoves[taskConfig.id] = @{
2841
3359
  @"id": taskConfig.id,
@@ -2984,7 +3502,7 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2984
3502
  - (NSMutableDictionary<NSNumber *, RNBGDUploadTaskConfig *> *)deserializeUploadConfig:(NSData *)taskMapRaw {
2985
3503
  NSError *error = nil;
2986
3504
  // Creates a list of classes that can be stored.
2987
- 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];
2988
3506
  NSMutableDictionary<NSNumber *, RNBGDUploadTaskConfig *> *taskMap = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:taskMapRaw error:&error];
2989
3507
 
2990
3508
  if (error) {
@@ -3023,11 +3541,13 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
3023
3541
  NSString *dataPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByDeletingLastPathComponent];
3024
3542
  NSString *dataPathWithoutUuid = [self getPathWithoutSuffixUuid:dataPath];
3025
3543
 
3026
- 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) {
3027
3547
  return [path substringFromIndex:[bundlePath length]];
3028
3548
  }
3029
3549
 
3030
- if ([path hasPrefix:dataPathWithoutUuid]) {
3550
+ if ([path hasPrefix:dataPathWithoutUuid] && path.length >= dataPath.length) {
3031
3551
  return [path substringFromIndex:[dataPath length]];
3032
3552
  }
3033
3553