@kesha-antonov/react-native-background-downloader 4.7.0 → 5.0.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.
- package/README.md +85 -37
- package/android/build.gradle +5 -1
- package/android/consumer-rules.pro +14 -0
- package/android/src/main/AndroidManifest.xml +18 -1
- package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +5 -567
- package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +4 -58
- package/android/src/main/java/com/{eko → kesha_antonov}/DownloadConstants.kt +6 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/DownloadEventEmitter.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/DownloadResult.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/Downloader.kt +14 -7
- package/android/src/main/java/com/{eko → kesha_antonov}/ProgressReporter.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/PromiseExtensions.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBGDTaskConfig.kt +1 -1
- package/android/src/main/java/com/kesha_antonov/RNBGDUploadTaskConfig.kt +57 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModuleImpl.kt +103 -63
- package/android/src/main/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderPackage.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloadService.kt +11 -9
- package/android/src/main/java/com/{eko → kesha_antonov}/ResumableDownloader.kt +36 -15
- package/android/src/main/java/com/kesha_antonov/UIDTDownloadJobService.kt +590 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/UnmeteredNetworkGate.kt +136 -19
- package/android/src/main/java/com/{eko → kesha_antonov}/UploadEventEmitter.kt +27 -2
- package/android/src/main/java/com/{eko → kesha_antonov}/Uploader.kt +189 -19
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBegin.kt +4 -4
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnBeginState.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgress.kt +5 -5
- package/android/src/main/java/com/{eko → kesha_antonov}/handlers/OnProgressState.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/BeginCallback.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/interfaces/ProgressCallback.kt +1 -1
- package/android/src/main/java/com/kesha_antonov/uidt/CancelDownloadReceiver.kt +68 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/RNBGDFileProvider.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobIds.kt +9 -4
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobManager.kt +6 -6
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTJobState.kt +7 -5
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIds.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationManager.kt +18 -10
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/FileUtils.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/HeaderUtils.kt +11 -2
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/NetworkRequestUtils.kt +1 -1
- package/android/src/main/java/com/kesha_antonov/utils/NotificationUtils.kt +24 -0
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/ProgressUtils.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/ReadableConverters.kt +1 -1
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/RedirectResolver.kt +32 -4
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/StorageManager.kt +5 -5
- package/android/src/main/java/com/{eko → kesha_antonov}/utils/TempFileUtils.kt +2 -2
- package/android/src/newarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
- package/android/src/oldarch/java/com/{eko → kesha_antonov}/RNBackgroundDownloaderModule.kt +1 -1
- package/android/src/test/java/com/kesha_antonov/DownloadCompleteReceiverTest.kt +57 -0
- package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderRecoveryTest.kt +2 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/DownloaderResumeTest.kt +3 -3
- package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderConcurrencyTest.kt +1 -1
- package/android/src/test/java/com/kesha_antonov/ResumableDownloaderRedirectTest.kt +77 -0
- package/android/src/test/java/com/{eko → kesha_antonov}/ResumableDownloaderStallTest.kt +1 -1
- package/android/src/test/java/com/kesha_antonov/UnmeteredNetworkGateTest.kt +248 -0
- package/android/src/test/java/com/kesha_antonov/UploadPartRangesTest.kt +33 -0
- package/android/src/test/java/com/{eko → kesha_antonov}/UploaderMultipartTest.kt +11 -2
- package/android/src/test/java/com/kesha_antonov/UploaderPartsTest.kt +222 -0
- package/android/src/test/java/com/kesha_antonov/UploaderResponseTest.kt +26 -0
- package/android/src/test/java/com/{eko → kesha_antonov}/handlers/OnBeginTest.kt +2 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/CancelDownloadReceiverTest.kt +25 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobIdsTest.kt +13 -2
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTJobManagerTest.kt +1 -1
- package/android/src/test/java/com/{eko → kesha_antonov}/uidt/UIDTNotificationIdsTest.kt +1 -1
- package/android/src/test/java/com/kesha_antonov/utils/RedirectResolverTest.kt +133 -0
- package/bin/react-native-background-downloader.js +197 -0
- package/ios/RNBGDUploadTaskConfig.h +26 -0
- package/ios/RNBGDUploadTaskConfig.mm +69 -3
- package/ios/RNBackgroundDownloader.mm +587 -47
- package/lib/NativeRNBackgroundDownloader.d.ts +15 -0
- package/lib/UploadTask.d.ts +5 -1
- package/lib/UploadTask.js +22 -4
- package/lib/index.js +57 -27
- package/lib/types.d.ts +33 -2
- package/package.json +5 -2
- package/src/NativeRNBackgroundDownloader.ts +23 -0
- package/src/UploadTask.ts +23 -1
- package/src/index.ts +60 -27
- package/src/types.ts +42 -2
- package/android/src/main/java/com/eko/RNBGDUploadTaskConfig.kt +0 -22
- package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +0 -67
|
@@ -10,15 +10,21 @@
|
|
|
10
10
|
#import <ReactCommon/TurboModule.h>
|
|
11
11
|
#endif
|
|
12
12
|
|
|
13
|
-
#define ID_TO_CONFIG_MAP_KEY @"com.
|
|
14
|
-
#define ID_TO_UPLOAD_CONFIG_MAP_KEY @"com.
|
|
13
|
+
#define ID_TO_CONFIG_MAP_KEY @"com.kesha_antonov.bgdownloadidmap"
|
|
14
|
+
#define ID_TO_UPLOAD_CONFIG_MAP_KEY @"com.kesha_antonov.bguploadidmap"
|
|
15
|
+
// Finished uploads kept until JS has their response, by upload id
|
|
16
|
+
#define FINISHED_UPLOADS_KEY @"com.kesha_antonov.bguploadfinished"
|
|
15
17
|
#define PROGRESS_INTERVAL_KEY @"progressInterval"
|
|
16
18
|
#define PROGRESS_MIN_BYTES_KEY @"progressMinBytes"
|
|
17
19
|
#define MAX_PARALLEL_DOWNLOADS_KEY @"maxParallelDownloads"
|
|
18
20
|
// Persisted map of downloads whose finished file could not be moved to its destination
|
|
19
21
|
// yet because the device was locked (Data Protection). The move is retried when protected
|
|
20
22
|
// data becomes available / on next launch. See issue #101.
|
|
21
|
-
#define PENDING_MOVES_MAP_KEY @"com.
|
|
23
|
+
#define PENDING_MOVES_MAP_KEY @"com.kesha_antonov.bgdpendingmoves"
|
|
24
|
+
// Keys used before the move to com.kesha_antonov; moved to the new keys on launch
|
|
25
|
+
// so downloads and uploads running across the update are not forgotten
|
|
26
|
+
#define LEGACY_KEY_PREFIX @"com.eko."
|
|
27
|
+
#define KEY_PREFIX @"com.kesha_antonov."
|
|
22
28
|
|
|
23
29
|
// Session configuration constants
|
|
24
30
|
static const NSInteger kMaxConnectionsPerHost = 4;
|
|
@@ -37,6 +43,10 @@ static const NSTimeInterval kStallTimeout = 20.0;
|
|
|
37
43
|
static const NSTimeInterval kStallCheckInterval = 5.0;
|
|
38
44
|
// Times in a row a download cut off by the network continues from its resume data
|
|
39
45
|
static const NSInteger kMaxNetworkResumes = 5;
|
|
46
|
+
// Upload response bodies past this are cut off before they reach JS
|
|
47
|
+
static const NSUInteger kMaxUploadResponseBytes = 1024 * 1024;
|
|
48
|
+
// Chunk size when copying an upload part out of the source file
|
|
49
|
+
static const NSUInteger kPartCopyChunkBytes = 4 * 1024 * 1024;
|
|
40
50
|
|
|
41
51
|
// DLog accepts taskId as first parameter to help debugging
|
|
42
52
|
// Only logs if isLogsEnabled is true (works in both DEBUG and RELEASE builds)
|
|
@@ -172,6 +182,15 @@ static void callCompletionHandlerIfDone(void) {
|
|
|
172
182
|
NSMutableDictionary<NSString *, NSNumber *> *idToUploadLastBytesMap;
|
|
173
183
|
NSMutableSet<NSString *> *idsToUploadPauseSet;
|
|
174
184
|
NSDate *lastUploadProgressReportedAt;
|
|
185
|
+
// Response bodies, per session task (the parts of an upload run at the same time)
|
|
186
|
+
NSMutableDictionary<NSNumber *, NSMutableData *> *uploadResponseDataByTask;
|
|
187
|
+
// Bytes each running part task has sent; an upload with parts reports their sum
|
|
188
|
+
NSMutableDictionary<NSNumber *, NSNumber *> *uploadPartBytesSent;
|
|
189
|
+
// The running part tasks of each upload with partUrls
|
|
190
|
+
NSMutableDictionary<NSString *, NSMutableArray<NSURLSessionUploadTask *> *> *idToUploadPartTasks;
|
|
191
|
+
// Finished uploads kept until JS has their response (persisted): an upload can finish
|
|
192
|
+
// while the app isn't running, and an S3 upload needs its parts' ETags to complete
|
|
193
|
+
NSMutableDictionary<NSString *, RNBGDUploadTaskConfig *> *finishedUploads;
|
|
175
194
|
}
|
|
176
195
|
|
|
177
196
|
RCT_EXPORT_MODULE();
|
|
@@ -194,7 +213,7 @@ RCT_EXPORT_MODULE();
|
|
|
194
213
|
|
|
195
214
|
- (dispatch_queue_t)methodQueue
|
|
196
215
|
{
|
|
197
|
-
return dispatch_queue_create("com.
|
|
216
|
+
return dispatch_queue_create("com.kesha_antonov.backgrounddownloader", DISPATCH_QUEUE_SERIAL);
|
|
198
217
|
}
|
|
199
218
|
|
|
200
219
|
#ifndef RCT_NEW_ARCH_ENABLED
|
|
@@ -324,6 +343,7 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
|
|
|
324
343
|
if (self) {
|
|
325
344
|
[MMKV initializeMMKV:nil];
|
|
326
345
|
mmkv = [MMKV mmkvWithID:@"RNBackgroundDownloader"];
|
|
346
|
+
[self migrateLegacyKeys];
|
|
327
347
|
|
|
328
348
|
NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
|
|
329
349
|
NSString *sessionIdentifier = [bundleIdentifier stringByAppendingString:@".backgrounddownloadtask"];
|
|
@@ -394,6 +414,12 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
|
|
|
394
414
|
idToUploadLastBytesMap = [[NSMutableDictionary alloc] init];
|
|
395
415
|
idsToUploadPauseSet = [[NSMutableSet alloc] init];
|
|
396
416
|
lastUploadProgressReportedAt = [[NSDate alloc] init];
|
|
417
|
+
uploadResponseDataByTask = [[NSMutableDictionary alloc] init];
|
|
418
|
+
uploadPartBytesSent = [[NSMutableDictionary alloc] init];
|
|
419
|
+
idToUploadPartTasks = [[NSMutableDictionary alloc] init];
|
|
420
|
+
NSData *finishedUploadsData = [mmkv getDataForKey:FINISHED_UPLOADS_KEY];
|
|
421
|
+
NSMutableDictionary *finishedUploadsDecoded = finishedUploadsData != nil ? [self deserializeUploadConfig:finishedUploadsData] : nil;
|
|
422
|
+
finishedUploads = finishedUploadsDecoded != nil ? finishedUploadsDecoded : [[NSMutableDictionary alloc] init];
|
|
397
423
|
|
|
398
424
|
[self registerBridgeListener];
|
|
399
425
|
|
|
@@ -410,6 +436,21 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
|
|
|
410
436
|
|
|
411
437
|
// The session isn't invalidated here or on reload: that would cancel every transfer. The
|
|
412
438
|
// next module instance takes it over (see -lazyRegisterSession).
|
|
439
|
+
// Move stored state from the com.eko.* keys to the com.kesha_antonov.* ones. A key that
|
|
440
|
+
// already has a value under its new name keeps it; the old key is removed either way.
|
|
441
|
+
- (void)migrateLegacyKeys {
|
|
442
|
+
NSArray<NSString *> *keys = @[ID_TO_CONFIG_MAP_KEY, ID_TO_UPLOAD_CONFIG_MAP_KEY, FINISHED_UPLOADS_KEY, PENDING_MOVES_MAP_KEY];
|
|
443
|
+
for (NSString *key in keys) {
|
|
444
|
+
NSString *legacyKey = [LEGACY_KEY_PREFIX stringByAppendingString:[key substringFromIndex:[KEY_PREFIX length]]];
|
|
445
|
+
if (![mmkv containsKey:legacyKey]) continue;
|
|
446
|
+
if (![mmkv containsKey:key]) {
|
|
447
|
+
NSData *data = [mmkv getDataForKey:legacyKey];
|
|
448
|
+
if (data != nil) [mmkv setData:data forKey:key];
|
|
449
|
+
}
|
|
450
|
+
[mmkv removeValueForKey:legacyKey];
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
413
454
|
- (void)dealloc {
|
|
414
455
|
DLog(nil, @"[RNBackgroundDownloader] - [dealloc]");
|
|
415
456
|
[self unregisterBridgeListener];
|
|
@@ -751,6 +792,9 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
|
|
|
751
792
|
[idToNetworkResumeCount removeObjectForKey:taskConfig.id];
|
|
752
793
|
// Clean up decode error retry tracking to prevent memory leak
|
|
753
794
|
[decodeErrorRetriedIds removeObject:taskConfig.id];
|
|
795
|
+
// The task is over: its resume data (which embeds the request headers,
|
|
796
|
+
// tokens included) must not stay on disk
|
|
797
|
+
[self deleteResumeDataForTaskId:taskConfig.id];
|
|
754
798
|
}
|
|
755
799
|
}
|
|
756
800
|
}
|
|
@@ -1665,7 +1709,11 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
|
|
|
1665
1709
|
|
|
1666
1710
|
NSURL *fileURL = [self resumeDataFileURLForTaskId:taskId];
|
|
1667
1711
|
NSError *error = nil;
|
|
1668
|
-
|
|
1712
|
+
// Resume data embeds the request with its headers: keep it encrypted at rest while still
|
|
1713
|
+
// writable when a network drop saves it on a locked device
|
|
1714
|
+
BOOL success = [resumeData writeToURL:fileURL
|
|
1715
|
+
options:NSDataWritingAtomic | NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
|
|
1716
|
+
error:&error];
|
|
1669
1717
|
|
|
1670
1718
|
if (!success) {
|
|
1671
1719
|
DLog(taskId, @"[RNBackgroundDownloader] - [saveResumeData] failed to save resume data: %@", error.localizedDescription);
|
|
@@ -2140,6 +2188,15 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
|
|
|
2140
2188
|
NSString *mimeType = options.mimeType() ? options.mimeType() : nil;
|
|
2141
2189
|
NSDictionary *parameters = options.parameters() ? (NSDictionary *)options.parameters() : nil;
|
|
2142
2190
|
BOOL allowsCellularAccess = options.isAllowedOverMetered();
|
|
2191
|
+
NSMutableArray<NSString *> *partUrls = nil;
|
|
2192
|
+
if (options.partUrls().has_value()) {
|
|
2193
|
+
auto urls = options.partUrls().value();
|
|
2194
|
+
partUrls = [NSMutableArray arrayWithCapacity:urls.size()];
|
|
2195
|
+
for (size_t i = 0; i < urls.size(); i++) {
|
|
2196
|
+
[partUrls addObject:urls[i]];
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
long long partSize = options.partSize().has_value() ? (long long)options.partSize().value() : 0;
|
|
2143
2200
|
|
|
2144
2201
|
if (options.progressInterval().has_value()) {
|
|
2145
2202
|
progressInterval = options.progressInterval().value() / 1000.0;
|
|
@@ -2164,6 +2221,8 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
|
|
|
2164
2221
|
NSDictionary *parameters = options[@"parameters"];
|
|
2165
2222
|
NSNumber *isAllowedOverMetered = options[@"isAllowedOverMetered"];
|
|
2166
2223
|
BOOL allowsCellularAccess = isAllowedOverMetered == nil || [isAllowedOverMetered boolValue];
|
|
2224
|
+
NSArray<NSString *> *partUrls = [options[@"partUrls"] isKindOfClass:[NSArray class]] ? options[@"partUrls"] : nil;
|
|
2225
|
+
long long partSize = [options[@"partSize"] isKindOfClass:[NSNumber class]] ? [options[@"partSize"] longLongValue] : 0;
|
|
2167
2226
|
|
|
2168
2227
|
NSNumber *progressIntervalScope = options[@"progressInterval"];
|
|
2169
2228
|
if (progressIntervalScope) {
|
|
@@ -2185,8 +2244,23 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
|
|
|
2185
2244
|
return;
|
|
2186
2245
|
}
|
|
2187
2246
|
|
|
2247
|
+
if (partUrls != nil) {
|
|
2248
|
+
[self startPartUpload:identifier
|
|
2249
|
+
source:source
|
|
2250
|
+
partUrls:partUrls
|
|
2251
|
+
partSize:partSize
|
|
2252
|
+
method:method
|
|
2253
|
+
metadata:metadata
|
|
2254
|
+
headers:headers
|
|
2255
|
+
mimeType:mimeType
|
|
2256
|
+
allowsCellularAccess:allowsCellularAccess];
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2188
2260
|
@try {
|
|
2189
2261
|
@synchronized (sharedLock) {
|
|
2262
|
+
// A new upload with this id replaces a finished one's kept response
|
|
2263
|
+
[self dropFinishedUpload:identifier];
|
|
2190
2264
|
[self sendDebugLog:@"upload: calling lazyRegisterSession" taskId:identifier];
|
|
2191
2265
|
[self lazyRegisterSession];
|
|
2192
2266
|
|
|
@@ -2292,7 +2366,11 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
|
|
|
2292
2366
|
|
|
2293
2367
|
// Write body to temp file for background upload
|
|
2294
2368
|
NSString *tempPath = [self multipartTempPathForUploadId:identifier];
|
|
2295
|
-
|
|
2369
|
+
// A full copy of the user's file plus form fields: encrypted at rest, still
|
|
2370
|
+
// readable by the background session while the device is locked
|
|
2371
|
+
if (![body writeToFile:tempPath
|
|
2372
|
+
options:NSDataWritingAtomic | NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
|
|
2373
|
+
error:nil]) {
|
|
2296
2374
|
DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not write multipart body to temp file");
|
|
2297
2375
|
[self emitUploadFailed:identifier error:@"Could not write multipart body to temp file" errorCode:NSURLErrorCannotWriteToFile];
|
|
2298
2376
|
return;
|
|
@@ -2332,14 +2410,363 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
|
|
|
2332
2410
|
}
|
|
2333
2411
|
}
|
|
2334
2412
|
|
|
2413
|
+
#pragma mark - Uploads in parts (partUrls)
|
|
2414
|
+
|
|
2415
|
+
- (void)persistUploadConfigs {
|
|
2416
|
+
[mmkv setData:[self serializeUploadConfig:uploadTaskToConfigMap] forKey:ID_TO_UPLOAD_CONFIG_MAP_KEY];
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
- (void)persistFinishedUploads {
|
|
2420
|
+
[mmkv setData:[self serializeUploadConfig:(NSMutableDictionary *)finishedUploads] forKey:FINISHED_UPLOADS_KEY];
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
// Must hold sharedLock
|
|
2424
|
+
- (void)dropFinishedUpload:(NSString *)identifier {
|
|
2425
|
+
if (identifier != nil && finishedUploads[identifier] != nil) {
|
|
2426
|
+
[finishedUploads removeObjectForKey:identifier];
|
|
2427
|
+
[self persistFinishedUploads];
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
// Response headers with lowercased names, so JS reads responseHeaders.etag on both platforms
|
|
2432
|
+
- (NSDictionary<NSString *, NSString *> *)lowercasedHeadersOfResponse:(NSURLResponse *)response {
|
|
2433
|
+
NSMutableDictionary<NSString *, NSString *> *headers = [NSMutableDictionary dictionary];
|
|
2434
|
+
if (![response isKindOfClass:[NSHTTPURLResponse class]]) {
|
|
2435
|
+
return headers;
|
|
2436
|
+
}
|
|
2437
|
+
[((NSHTTPURLResponse *)response).allHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
|
|
2438
|
+
if ([key isKindOfClass:[NSString class]]) {
|
|
2439
|
+
headers[[(NSString *)key lowercaseString]] = [value isKindOfClass:[NSString class]] ? value : [value description];
|
|
2440
|
+
}
|
|
2441
|
+
}];
|
|
2442
|
+
return headers;
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
- (NSString *)normalizedSourcePath:(NSString *)source {
|
|
2446
|
+
if (![source hasPrefix:@"file://"]) {
|
|
2447
|
+
return source;
|
|
2448
|
+
}
|
|
2449
|
+
NSString *path = [NSURL URLWithString:source].path;
|
|
2450
|
+
if (path == nil) {
|
|
2451
|
+
// URLWithString rejects unencoded paths (e.g. containing spaces)
|
|
2452
|
+
path = [[source substringFromIndex:@"file://".length] stringByRemovingPercentEncoding];
|
|
2453
|
+
}
|
|
2454
|
+
return path ?: source;
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
// A background session uploads only from a file, so each part is copied out of the source
|
|
2458
|
+
- (NSString *)partTempPathForUploadId:(NSString *)identifier index:(NSUInteger)index {
|
|
2459
|
+
NSString *safeId = [identifier stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
|
|
2460
|
+
return [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"RNBGD-upload-%@.part-%lu", safeId, (unsigned long)index]];
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
- (void)removePartTempFilesForUploadId:(NSString *)identifier count:(NSUInteger)count {
|
|
2464
|
+
for (NSUInteger index = 0; index < count; index++) {
|
|
2465
|
+
[[NSFileManager defaultManager] removeItemAtPath:[self partTempPathForUploadId:identifier index:index] error:nil];
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2469
|
+
// Copies [offset, offset + length) of the source in chunks, so a big file isn't read into memory
|
|
2470
|
+
- (BOOL)copyRangeOfFile:(NSString *)source offset:(long long)offset length:(long long)length toPath:(NSString *)path {
|
|
2471
|
+
NSFileManager *fileManager = [NSFileManager defaultManager];
|
|
2472
|
+
[fileManager removeItemAtPath:path error:nil];
|
|
2473
|
+
// Holds a slice of the user's file: encrypted at rest, still readable by the
|
|
2474
|
+
// background session while the device is locked
|
|
2475
|
+
if (![fileManager createFileAtPath:path contents:nil attributes:@{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication}]) {
|
|
2476
|
+
return NO;
|
|
2477
|
+
}
|
|
2478
|
+
NSFileHandle *input = [NSFileHandle fileHandleForReadingAtPath:source];
|
|
2479
|
+
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:path];
|
|
2480
|
+
BOOL copied = input != nil && output != nil && [input seekToOffset:(unsigned long long)offset error:nil];
|
|
2481
|
+
long long remaining = length;
|
|
2482
|
+
while (copied && remaining > 0) {
|
|
2483
|
+
@autoreleasepool {
|
|
2484
|
+
NSData *chunk = [input readDataUpToLength:(NSUInteger)MIN(remaining, (long long)kPartCopyChunkBytes) error:nil];
|
|
2485
|
+
if (chunk.length == 0 || ![output writeData:chunk error:nil]) {
|
|
2486
|
+
copied = NO;
|
|
2487
|
+
} else {
|
|
2488
|
+
remaining -= chunk.length;
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
}
|
|
2492
|
+
[input closeAndReturnError:nil];
|
|
2493
|
+
[output closeAndReturnError:nil];
|
|
2494
|
+
if (!copied) {
|
|
2495
|
+
[fileManager removeItemAtPath:path error:nil];
|
|
2496
|
+
}
|
|
2497
|
+
return copied;
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
- (void)startPartUpload:(NSString *)identifier
|
|
2501
|
+
source:(NSString *)source
|
|
2502
|
+
partUrls:(NSArray<NSString *> *)partUrls
|
|
2503
|
+
partSize:(long long)partSize
|
|
2504
|
+
method:(NSString *)method
|
|
2505
|
+
metadata:(NSString *)metadata
|
|
2506
|
+
headers:(NSDictionary *)headers
|
|
2507
|
+
mimeType:(NSString *)mimeType
|
|
2508
|
+
allowsCellularAccess:(BOOL)allowsCellularAccess {
|
|
2509
|
+
source = [self normalizedSourcePath:source];
|
|
2510
|
+
|
|
2511
|
+
NSError *fileError = nil;
|
|
2512
|
+
NSDictionary *fileAttrs = [[NSFileManager defaultManager] attributesOfItemAtPath:source error:&fileError];
|
|
2513
|
+
if (fileError) {
|
|
2514
|
+
[self emitUploadFailed:identifier error:[NSString stringWithFormat:@"Could not read file: %@", fileError.localizedDescription] errorCode:NSURLErrorFileDoesNotExist];
|
|
2515
|
+
return;
|
|
2516
|
+
}
|
|
2517
|
+
long long fileSize = (long long)[fileAttrs fileSize];
|
|
2518
|
+
|
|
2519
|
+
NSArray<NSArray<NSNumber *> *> *ranges = [RNBGDUploadTaskConfig partRangesForFileSize:fileSize partCount:partUrls.count partSize:partSize];
|
|
2520
|
+
if (ranges == nil) {
|
|
2521
|
+
NSString *sizeNote = partSize > 0 ? [NSString stringWithFormat:@" of %lld bytes", partSize] : @"";
|
|
2522
|
+
[self emitUploadFailed:identifier
|
|
2523
|
+
error:[NSString stringWithFormat:@"The file (%lld bytes) can't be split into %lu parts%@", fileSize, (unsigned long)partUrls.count, sizeNote]
|
|
2524
|
+
errorCode:-1];
|
|
2525
|
+
return;
|
|
2526
|
+
}
|
|
2527
|
+
for (NSString *partUrl in partUrls) {
|
|
2528
|
+
if (![partUrl isKindOfClass:[NSString class]] || [NSURL URLWithString:partUrl] == nil) {
|
|
2529
|
+
[self emitUploadFailed:identifier error:[NSString stringWithFormat:@"invalid url: %@", partUrl] errorCode:NSURLErrorBadURL];
|
|
2530
|
+
return;
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
@synchronized (sharedLock) {
|
|
2535
|
+
// A new upload with this id replaces a finished one's kept response
|
|
2536
|
+
[self dropFinishedUpload:identifier];
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
// Outside the lock: copying a big file takes a while, and session callbacks need it
|
|
2540
|
+
for (NSUInteger index = 0; index < ranges.count; index++) {
|
|
2541
|
+
if (![self copyRangeOfFile:source
|
|
2542
|
+
offset:[ranges[index][0] longLongValue]
|
|
2543
|
+
length:[ranges[index][1] longLongValue]
|
|
2544
|
+
toPath:[self partTempPathForUploadId:identifier index:index]]) {
|
|
2545
|
+
[self removePartTempFilesForUploadId:identifier count:index];
|
|
2546
|
+
[self emitUploadFailed:identifier error:[NSString stringWithFormat:@"Could not copy part %lu of the file", (unsigned long)index + 1] errorCode:NSURLErrorCannotWriteToFile];
|
|
2547
|
+
return;
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
|
|
2551
|
+
@try {
|
|
2552
|
+
@synchronized (sharedLock) {
|
|
2553
|
+
[self lazyRegisterSession];
|
|
2554
|
+
|
|
2555
|
+
RNBGDUploadTaskConfig *taskConfig = [[RNBGDUploadTaskConfig alloc] initWithDictionary:@{
|
|
2556
|
+
@"id": identifier,
|
|
2557
|
+
@"url": partUrls.firstObject,
|
|
2558
|
+
@"source": source,
|
|
2559
|
+
@"method": method,
|
|
2560
|
+
@"metadata": metadata,
|
|
2561
|
+
@"mimeType": mimeType ?: [NSNull null],
|
|
2562
|
+
@"partUrls": partUrls,
|
|
2563
|
+
@"partSize": @(partSize)
|
|
2564
|
+
}];
|
|
2565
|
+
taskConfig.bytesTotal = fileSize;
|
|
2566
|
+
|
|
2567
|
+
NSMutableArray<NSURLSessionUploadTask *> *tasks = [NSMutableArray arrayWithCapacity:partUrls.count];
|
|
2568
|
+
NSMutableDictionary<NSNumber *, NSNumber *> *partIndexByTask = [NSMutableDictionary dictionary];
|
|
2569
|
+
for (NSUInteger index = 0; index < partUrls.count; index++) {
|
|
2570
|
+
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:partUrls[index]]];
|
|
2571
|
+
request.HTTPMethod = method;
|
|
2572
|
+
request.allowsCellularAccess = allowsCellularAccess;
|
|
2573
|
+
for (NSString *headerKey in headers) {
|
|
2574
|
+
[request setValue:[headers valueForKey:headerKey] forHTTPHeaderField:headerKey];
|
|
2575
|
+
}
|
|
2576
|
+
// Raw body, no multipart wrapping
|
|
2577
|
+
[request setValue:mimeType ?: @"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
|
|
2578
|
+
|
|
2579
|
+
NSURL *partFile = [NSURL fileURLWithPath:[self partTempPathForUploadId:identifier index:index]];
|
|
2580
|
+
NSURLSessionUploadTask *task = [self createUploadTaskWithRequest:request fromFile:partFile identifier:identifier];
|
|
2581
|
+
if (task == nil) {
|
|
2582
|
+
for (NSURLSessionUploadTask *created in tasks) {
|
|
2583
|
+
[created cancel];
|
|
2584
|
+
}
|
|
2585
|
+
[self removePartTempFilesForUploadId:identifier count:partUrls.count];
|
|
2586
|
+
[self emitUploadFailed:identifier error:@"failed to create upload task" errorCode:-1];
|
|
2587
|
+
return;
|
|
2588
|
+
}
|
|
2589
|
+
partIndexByTask[@(task.taskIdentifier)] = @(index);
|
|
2590
|
+
[tasks addObject:task];
|
|
2591
|
+
}
|
|
2592
|
+
taskConfig.partIndexByTask = partIndexByTask;
|
|
2593
|
+
|
|
2594
|
+
for (NSURLSessionUploadTask *task in tasks) {
|
|
2595
|
+
uploadTaskToConfigMap[@(task.taskIdentifier)] = taskConfig;
|
|
2596
|
+
}
|
|
2597
|
+
[self persistUploadConfigs];
|
|
2598
|
+
idToUploadPartTasks[identifier] = tasks;
|
|
2599
|
+
idToUploadPercentMap[identifier] = @0.0;
|
|
2600
|
+
idToUploadLastBytesMap[identifier] = @0;
|
|
2601
|
+
|
|
2602
|
+
for (NSURLSessionUploadTask *task in tasks) {
|
|
2603
|
+
[task resume];
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
} @catch (NSException *exception) {
|
|
2607
|
+
DLog(identifier, @"[RNBackgroundDownloader] - [startPartUpload] error: %@", exception.reason);
|
|
2608
|
+
[self removePartTempFilesForUploadId:identifier count:partUrls.count];
|
|
2609
|
+
[self emitUploadFailed:identifier error:exception.reason errorCode:-1];
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2612
|
+
|
|
2613
|
+
// Bytes sent so far across the parts: accepted parts in full, running ones as far as they got.
|
|
2614
|
+
// Must hold sharedLock
|
|
2615
|
+
- (long long)bytesSentForPartUpload:(RNBGDUploadTaskConfig *)taskConfig {
|
|
2616
|
+
long long sent = 0;
|
|
2617
|
+
for (NSDictionary *result in taskConfig.partResults.allValues) {
|
|
2618
|
+
sent += [result[@"bytes"] longLongValue];
|
|
2619
|
+
}
|
|
2620
|
+
for (NSNumber *taskKey in taskConfig.partIndexByTask) {
|
|
2621
|
+
sent += [uploadPartBytesSent[taskKey] longLongValue];
|
|
2622
|
+
}
|
|
2623
|
+
return sent;
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
// Must hold sharedLock
|
|
2627
|
+
- (void)forgetPartUploadTasks:(RNBGDUploadTaskConfig *)taskConfig cancel:(BOOL)cancel {
|
|
2628
|
+
for (NSNumber *taskKey in taskConfig.partIndexByTask) {
|
|
2629
|
+
[uploadTaskToConfigMap removeObjectForKey:taskKey];
|
|
2630
|
+
[uploadPartBytesSent removeObjectForKey:taskKey];
|
|
2631
|
+
[uploadResponseDataByTask removeObjectForKey:taskKey];
|
|
2632
|
+
}
|
|
2633
|
+
if (cancel) {
|
|
2634
|
+
// Their completion finds no config any more and is ignored
|
|
2635
|
+
for (NSURLSessionUploadTask *task in idToUploadPartTasks[taskConfig.id]) {
|
|
2636
|
+
[task cancel];
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
[idToUploadPartTasks removeObjectForKey:taskConfig.id];
|
|
2640
|
+
[idToUploadPercentMap removeObjectForKey:taskConfig.id];
|
|
2641
|
+
[idToUploadLastBytesMap removeObjectForKey:taskConfig.id];
|
|
2642
|
+
[uploadProgressReports removeObjectForKey:taskConfig.id];
|
|
2643
|
+
[idsToUploadPauseSet removeObject:taskConfig.id];
|
|
2644
|
+
[self removePartTempFilesForUploadId:taskConfig.id count:taskConfig.partUrls.count];
|
|
2645
|
+
[self persistUploadConfigs];
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
// Any part that isn't accepted fails the whole upload. Must hold sharedLock
|
|
2649
|
+
- (void)failPartUpload:(RNBGDUploadTaskConfig *)taskConfig error:(NSString *)error errorCode:(NSInteger)errorCode {
|
|
2650
|
+
DLog(taskConfig.id, @"[RNBackgroundDownloader] - [failPartUpload] %@", error);
|
|
2651
|
+
[self forgetPartUploadTasks:taskConfig cancel:YES];
|
|
2652
|
+
[self emitUploadFailed:taskConfig.id error:error errorCode:errorCode];
|
|
2653
|
+
}
|
|
2654
|
+
|
|
2655
|
+
// Must hold sharedLock
|
|
2656
|
+
- (void)handlePartCompletion:(NSURLSessionTask *)task config:(RNBGDUploadTaskConfig *)taskConfig responseData:(NSData *)responseData error:(NSError *)error {
|
|
2657
|
+
NSNumber *taskKey = @(task.taskIdentifier);
|
|
2658
|
+
NSNumber *index = taskConfig.partIndexByTask[taskKey];
|
|
2659
|
+
if (index == nil) {
|
|
2660
|
+
return;
|
|
2661
|
+
}
|
|
2662
|
+
if (error) {
|
|
2663
|
+
[self failPartUpload:taskConfig error:error.localizedDescription errorCode:error.code];
|
|
2664
|
+
return;
|
|
2665
|
+
}
|
|
2666
|
+
|
|
2667
|
+
NSInteger responseCode = [task.response isKindOfClass:[NSHTTPURLResponse class]] ? ((NSHTTPURLResponse *)task.response).statusCode : 0;
|
|
2668
|
+
NSString *responseBody = responseData != nil ? ([[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ?: @"") : @"";
|
|
2669
|
+
NSUInteger partNumber = index.unsignedIntegerValue + 1;
|
|
2670
|
+
if (responseCode < 200 || responseCode >= 300) {
|
|
2671
|
+
[self failPartUpload:taskConfig
|
|
2672
|
+
error:[NSString stringWithFormat:@"Part %lu failed: HTTP %ld - %@", (unsigned long)partNumber, (long)responseCode, responseBody]
|
|
2673
|
+
errorCode:responseCode];
|
|
2674
|
+
return;
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
NSArray<NSArray<NSNumber *> *> *ranges = [RNBGDUploadTaskConfig partRangesForFileSize:taskConfig.bytesTotal
|
|
2678
|
+
partCount:taskConfig.partUrls.count
|
|
2679
|
+
partSize:taskConfig.partSize];
|
|
2680
|
+
NSMutableDictionary<NSNumber *, NSDictionary *> *results = [taskConfig.partResults mutableCopy] ?: [NSMutableDictionary dictionary];
|
|
2681
|
+
results[index] = @{
|
|
2682
|
+
@"partNumber": @(partNumber),
|
|
2683
|
+
@"responseCode": @(responseCode),
|
|
2684
|
+
@"responseBody": responseBody,
|
|
2685
|
+
@"responseHeaders": [self lowercasedHeadersOfResponse:task.response],
|
|
2686
|
+
@"bytes": ranges[index.unsignedIntegerValue][1]
|
|
2687
|
+
};
|
|
2688
|
+
taskConfig.partResults = results;
|
|
2689
|
+
|
|
2690
|
+
NSMutableDictionary<NSNumber *, NSNumber *> *partIndexByTask = [taskConfig.partIndexByTask mutableCopy];
|
|
2691
|
+
[partIndexByTask removeObjectForKey:taskKey];
|
|
2692
|
+
taskConfig.partIndexByTask = partIndexByTask;
|
|
2693
|
+
[uploadTaskToConfigMap removeObjectForKey:taskKey];
|
|
2694
|
+
[uploadPartBytesSent removeObjectForKey:taskKey];
|
|
2695
|
+
[idToUploadPartTasks[taskConfig.id] removeObject:(NSURLSessionUploadTask *)task];
|
|
2696
|
+
// Free the copy as soon as its part is in
|
|
2697
|
+
[[NSFileManager defaultManager] removeItemAtPath:[self partTempPathForUploadId:taskConfig.id index:index.unsignedIntegerValue] error:nil];
|
|
2698
|
+
|
|
2699
|
+
if (results.count < taskConfig.partUrls.count) {
|
|
2700
|
+
[self persistUploadConfigs];
|
|
2701
|
+
return;
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
// Every part is in
|
|
2705
|
+
NSArray<NSDictionary *> *parts = [taskConfig orderedPartResults];
|
|
2706
|
+
NSDictionary *last = parts.lastObject;
|
|
2707
|
+
taskConfig.responseCode = [last[@"responseCode"] integerValue];
|
|
2708
|
+
taskConfig.responseBody = last[@"responseBody"];
|
|
2709
|
+
taskConfig.responseHeaders = last[@"responseHeaders"];
|
|
2710
|
+
taskConfig.bytesUploaded = taskConfig.bytesTotal;
|
|
2711
|
+
taskConfig.state = NSURLSessionTaskStateCompleted;
|
|
2712
|
+
[self forgetPartUploadTasks:taskConfig cancel:NO];
|
|
2713
|
+
finishedUploads[taskConfig.id] = taskConfig;
|
|
2714
|
+
[self persistFinishedUploads];
|
|
2715
|
+
|
|
2716
|
+
[self emitUploadComplete:taskConfig.id
|
|
2717
|
+
responseCode:taskConfig.responseCode
|
|
2718
|
+
responseBody:taskConfig.responseBody
|
|
2719
|
+
responseHeaders:taskConfig.responseHeaders
|
|
2720
|
+
parts:parts
|
|
2721
|
+
bytesUploaded:taskConfig.bytesTotal
|
|
2722
|
+
bytesTotal:taskConfig.bytesTotal];
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
- (void)emitUploadComplete:(NSString *)identifier
|
|
2726
|
+
responseCode:(NSInteger)responseCode
|
|
2727
|
+
responseBody:(NSString *)responseBody
|
|
2728
|
+
responseHeaders:(NSDictionary *)responseHeaders
|
|
2729
|
+
parts:(nullable NSArray<NSDictionary *> *)parts
|
|
2730
|
+
bytesUploaded:(long long)bytesUploaded
|
|
2731
|
+
bytesTotal:(long long)bytesTotal {
|
|
2732
|
+
NSMutableDictionary *body = [@{
|
|
2733
|
+
@"id": identifier,
|
|
2734
|
+
@"responseCode": @(responseCode),
|
|
2735
|
+
@"responseBody": responseBody ?: @"",
|
|
2736
|
+
@"responseHeaders": responseHeaders ?: @{},
|
|
2737
|
+
@"bytesUploaded": @(bytesUploaded),
|
|
2738
|
+
@"bytesTotal": @(bytesTotal)
|
|
2739
|
+
} mutableCopy];
|
|
2740
|
+
if (parts != nil) {
|
|
2741
|
+
body[@"parts"] = parts;
|
|
2742
|
+
}
|
|
2743
|
+
#ifdef RCT_NEW_ARCH_ENABLED
|
|
2744
|
+
[self safeEmitEvent:@"onUploadComplete" value:body];
|
|
2745
|
+
#else
|
|
2746
|
+
[self sendEventWithName:@"uploadComplete" body:body];
|
|
2747
|
+
#endif
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2750
|
+
// The tasks of an upload: one, or one per part. Must hold sharedLock
|
|
2751
|
+
- (NSArray<NSURLSessionUploadTask *> *)uploadTasksForId:(NSString *)identifier {
|
|
2752
|
+
NSArray<NSURLSessionUploadTask *> *parts = idToUploadPartTasks[identifier];
|
|
2753
|
+
if (parts != nil) {
|
|
2754
|
+
return [parts copy];
|
|
2755
|
+
}
|
|
2756
|
+
NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
|
|
2757
|
+
return task != nil ? @[task] : @[];
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2335
2760
|
- (void)pauseUploadTaskInternal:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
|
|
2336
2761
|
DLog(identifier, @"[RNBackgroundDownloader] - [pauseUploadTask]");
|
|
2337
2762
|
@try {
|
|
2338
2763
|
@synchronized (sharedLock) {
|
|
2339
|
-
NSURLSessionUploadTask *
|
|
2340
|
-
if (
|
|
2764
|
+
NSArray<NSURLSessionUploadTask *> *tasks = [self uploadTasksForId:identifier];
|
|
2765
|
+
if (tasks.count > 0) {
|
|
2341
2766
|
[idsToUploadPauseSet addObject:identifier];
|
|
2342
|
-
|
|
2767
|
+
for (NSURLSessionUploadTask *task in tasks) {
|
|
2768
|
+
[task suspend];
|
|
2769
|
+
}
|
|
2343
2770
|
DLog(identifier, @"[RNBackgroundDownloader] - [pauseUploadTask] suspended upload task: %@", identifier);
|
|
2344
2771
|
}
|
|
2345
2772
|
}
|
|
@@ -2366,9 +2793,14 @@ RCT_EXPORT_METHOD(pauseUploadTask:(NSString *)id resolver:(RCTPromiseResolveBloc
|
|
|
2366
2793
|
[self lazyRegisterSession];
|
|
2367
2794
|
[idsToUploadPauseSet removeObject:identifier];
|
|
2368
2795
|
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2796
|
+
BOOL resumed = NO;
|
|
2797
|
+
for (NSURLSessionUploadTask *task in [self uploadTasksForId:identifier]) {
|
|
2798
|
+
if (task.state == NSURLSessionTaskStateSuspended) {
|
|
2799
|
+
[task resume];
|
|
2800
|
+
resumed = YES;
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
if (resumed) {
|
|
2372
2804
|
DLog(identifier, @"[RNBackgroundDownloader] - [resumeUploadTask] resumed upload task: %@", identifier);
|
|
2373
2805
|
} else {
|
|
2374
2806
|
DLog(identifier, @"[RNBackgroundDownloader] - [resumeUploadTask] no suspended upload task found for %@", identifier);
|
|
@@ -2395,7 +2827,16 @@ RCT_EXPORT_METHOD(resumeUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlo
|
|
|
2395
2827
|
@try {
|
|
2396
2828
|
@synchronized (sharedLock) {
|
|
2397
2829
|
NSURLSessionUploadTask *task = idToUploadTaskMap[identifier];
|
|
2398
|
-
|
|
2830
|
+
RNBGDUploadTaskConfig *partConfig = nil;
|
|
2831
|
+
for (RNBGDUploadTaskConfig *config in uploadTaskToConfigMap.allValues) {
|
|
2832
|
+
if (config.partUrls != nil && [config.id isEqualToString:identifier]) {
|
|
2833
|
+
partConfig = config;
|
|
2834
|
+
break;
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
if (partConfig != nil) {
|
|
2838
|
+
[self forgetPartUploadTasks:partConfig cancel:YES];
|
|
2839
|
+
} else if (task != nil) {
|
|
2399
2840
|
[task cancel];
|
|
2400
2841
|
[self removeUploadTaskFromMap:task];
|
|
2401
2842
|
} else {
|
|
@@ -2411,6 +2852,8 @@ RCT_EXPORT_METHOD(resumeUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlo
|
|
|
2411
2852
|
}
|
|
2412
2853
|
[idsToUploadPauseSet removeObject:identifier];
|
|
2413
2854
|
[self removeMultipartTempFileForUploadId:identifier];
|
|
2855
|
+
// Also how JS acknowledges a finished upload's response
|
|
2856
|
+
[self dropFinishedUpload:identifier];
|
|
2414
2857
|
}
|
|
2415
2858
|
resolve(nil);
|
|
2416
2859
|
} @catch (NSException *exception) {
|
|
@@ -2444,9 +2887,28 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
|
|
|
2444
2887
|
NSMutableSet *processedIds = [[NSMutableSet alloc] init];
|
|
2445
2888
|
|
|
2446
2889
|
// Phase 1: Process active upload tasks from session
|
|
2890
|
+
[self->idToUploadPartTasks removeAllObjects];
|
|
2447
2891
|
for (NSURLSessionUploadTask *task in uploadTasks) {
|
|
2448
2892
|
RNBGDUploadTaskConfig *taskConfig = [self uploadConfigForTask:task];
|
|
2449
2893
|
|
|
2894
|
+
if (taskConfig && taskConfig.partUrls != nil) {
|
|
2895
|
+
// One upload, several part tasks: listed once, with the bytes of all parts
|
|
2896
|
+
NSMutableArray *partTasks = self->idToUploadPartTasks[taskConfig.id];
|
|
2897
|
+
if (partTasks == nil) {
|
|
2898
|
+
partTasks = [NSMutableArray array];
|
|
2899
|
+
self->idToUploadPartTasks[taskConfig.id] = partTasks;
|
|
2900
|
+
}
|
|
2901
|
+
[partTasks addObject:task];
|
|
2902
|
+
self->uploadPartBytesSent[@(task.taskIdentifier)] = @(task.countOfBytesSent);
|
|
2903
|
+
if ([processedIds containsObject:taskConfig.id]) {
|
|
2904
|
+
continue;
|
|
2905
|
+
}
|
|
2906
|
+
[processedIds addObject:taskConfig.id];
|
|
2907
|
+
taskConfig.state = task.state;
|
|
2908
|
+
[foundTasks addObject:taskConfig.id];
|
|
2909
|
+
continue;
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2450
2912
|
if (taskConfig) {
|
|
2451
2913
|
taskConfig.state = task.state;
|
|
2452
2914
|
taskConfig.bytesUploaded = task.countOfBytesSent;
|
|
@@ -2468,6 +2930,29 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
|
|
|
2468
2930
|
}
|
|
2469
2931
|
}
|
|
2470
2932
|
|
|
2933
|
+
// Part uploads were held back above until every part task was counted
|
|
2934
|
+
for (NSUInteger i = 0; i < foundTasks.count; i++) {
|
|
2935
|
+
if (![foundTasks[i] isKindOfClass:[NSString class]]) {
|
|
2936
|
+
continue;
|
|
2937
|
+
}
|
|
2938
|
+
RNBGDUploadTaskConfig *taskConfig = nil;
|
|
2939
|
+
for (RNBGDUploadTaskConfig *config in self->uploadTaskToConfigMap.allValues) {
|
|
2940
|
+
if ([config.id isEqualToString:foundTasks[i]]) {
|
|
2941
|
+
taskConfig = config;
|
|
2942
|
+
break;
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
taskConfig.bytesUploaded = [self bytesSentForPartUpload:taskConfig];
|
|
2946
|
+
foundTasks[i] = @{
|
|
2947
|
+
@"id": taskConfig.id,
|
|
2948
|
+
@"metadata": taskConfig.metadata,
|
|
2949
|
+
@"state": @(taskConfig.state),
|
|
2950
|
+
@"bytesUploaded": @(taskConfig.bytesUploaded),
|
|
2951
|
+
@"bytesTotal": @(taskConfig.bytesTotal),
|
|
2952
|
+
@"errorCode": [NSNull null]
|
|
2953
|
+
};
|
|
2954
|
+
}
|
|
2955
|
+
|
|
2471
2956
|
// Phase 2: Add persisted upload configs that are not active (for app restart recovery)
|
|
2472
2957
|
// Uploads cannot truly resume like downloads, but we preserve their metadata
|
|
2473
2958
|
// so the user can restart them
|
|
@@ -2492,6 +2977,30 @@ RCT_EXPORT_METHOD(stopUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlock
|
|
|
2492
2977
|
DLog(taskConfig.id, @"[RNBackgroundDownloader] - [getExistingUploadTasks] restored persisted upload task: %@", taskConfig.id);
|
|
2493
2978
|
}
|
|
2494
2979
|
|
|
2980
|
+
// Phase 3: Uploads that finished while JS wasn't listening, with their response.
|
|
2981
|
+
// JS acknowledges them (stopUploadTask), which drops them
|
|
2982
|
+
for (RNBGDUploadTaskConfig *taskConfig in self->finishedUploads.allValues) {
|
|
2983
|
+
if ([processedIds containsObject:taskConfig.id]) {
|
|
2984
|
+
continue;
|
|
2985
|
+
}
|
|
2986
|
+
NSMutableDictionary *taskInfo = [@{
|
|
2987
|
+
@"id": taskConfig.id,
|
|
2988
|
+
@"metadata": taskConfig.metadata,
|
|
2989
|
+
@"state": @(NSURLSessionTaskStateCompleted),
|
|
2990
|
+
@"bytesUploaded": @(taskConfig.bytesTotal),
|
|
2991
|
+
@"bytesTotal": @(taskConfig.bytesTotal),
|
|
2992
|
+
@"errorCode": [NSNull null],
|
|
2993
|
+
@"responseCode": @(taskConfig.responseCode),
|
|
2994
|
+
@"responseBody": taskConfig.responseBody ?: @"",
|
|
2995
|
+
@"responseHeaders": taskConfig.responseHeaders ?: @{}
|
|
2996
|
+
} mutableCopy];
|
|
2997
|
+
if (taskConfig.partUrls != nil) {
|
|
2998
|
+
taskInfo[@"parts"] = [taskConfig orderedPartResults];
|
|
2999
|
+
}
|
|
3000
|
+
[foundTasks addObject:taskInfo];
|
|
3001
|
+
[processedIds addObject:taskConfig.id];
|
|
3002
|
+
}
|
|
3003
|
+
|
|
2495
3004
|
resolve(foundTasks);
|
|
2496
3005
|
} @catch (NSException *exception) {
|
|
2497
3006
|
reject(@"ERR_GET_EXISTING_UPLOAD_TASKS", exception.reason, nil);
|
|
@@ -2516,6 +3025,13 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2516
3025
|
return;
|
|
2517
3026
|
}
|
|
2518
3027
|
|
|
3028
|
+
// An upload in parts reports the sum of its parts against the file size
|
|
3029
|
+
if (taskConfig.partUrls != nil) {
|
|
3030
|
+
uploadPartBytesSent[@(task.taskIdentifier)] = @(totalBytesSent);
|
|
3031
|
+
totalBytesSent = [self bytesSentForPartUpload:taskConfig];
|
|
3032
|
+
totalBytesExpectedToSend = taskConfig.bytesTotal;
|
|
3033
|
+
}
|
|
3034
|
+
|
|
2519
3035
|
DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didSendBodyData] %lld/%lld", totalBytesSent, totalBytesExpectedToSend);
|
|
2520
3036
|
|
|
2521
3037
|
// Report begin if needed
|
|
@@ -2584,10 +3100,20 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2584
3100
|
return;
|
|
2585
3101
|
}
|
|
2586
3102
|
|
|
2587
|
-
|
|
2588
|
-
|
|
3103
|
+
// Per task: the parts of an upload receive their responses at the same time
|
|
3104
|
+
NSNumber *taskKey = @(dataTask.taskIdentifier);
|
|
3105
|
+
NSMutableData *responseData = uploadResponseDataByTask[taskKey];
|
|
3106
|
+
if (responseData == nil) {
|
|
3107
|
+
responseData = [[NSMutableData alloc] init];
|
|
3108
|
+
uploadResponseDataByTask[taskKey] = responseData;
|
|
3109
|
+
}
|
|
3110
|
+
// The body goes to JS as one string: cap it, so a hostile or broken server
|
|
3111
|
+
// can't run the app (or its background relaunch) out of memory
|
|
3112
|
+
NSUInteger room = kMaxUploadResponseBytes > responseData.length
|
|
3113
|
+
? kMaxUploadResponseBytes - responseData.length : 0;
|
|
3114
|
+
if (room > 0) {
|
|
3115
|
+
[responseData appendData:data.length > room ? [data subdataWithRange:NSMakeRange(0, room)] : data];
|
|
2589
3116
|
}
|
|
2590
|
-
[taskConfig.responseData appendData:data];
|
|
2591
3117
|
}
|
|
2592
3118
|
}
|
|
2593
3119
|
|
|
@@ -2621,6 +3147,15 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2621
3147
|
}
|
|
2622
3148
|
}
|
|
2623
3149
|
|
|
3150
|
+
NSNumber *taskKey = @(task.taskIdentifier);
|
|
3151
|
+
NSData *responseData = uploadResponseDataByTask[taskKey];
|
|
3152
|
+
[uploadResponseDataByTask removeObjectForKey:taskKey];
|
|
3153
|
+
|
|
3154
|
+
if (taskConfig.partUrls != nil) {
|
|
3155
|
+
[self handlePartCompletion:task config:taskConfig responseData:responseData error:error];
|
|
3156
|
+
return;
|
|
3157
|
+
}
|
|
3158
|
+
|
|
2624
3159
|
// The upload is over (failed or done); a paused one returned above and keeps its body
|
|
2625
3160
|
[self removeMultipartTempFileForUploadId:taskConfig.id];
|
|
2626
3161
|
|
|
@@ -2647,28 +3182,29 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2647
3182
|
}
|
|
2648
3183
|
|
|
2649
3184
|
NSString *responseBody = @"";
|
|
2650
|
-
if (
|
|
2651
|
-
responseBody = [[NSString alloc] initWithData:
|
|
3185
|
+
if (responseData) {
|
|
3186
|
+
responseBody = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ?: @"";
|
|
2652
3187
|
}
|
|
3188
|
+
NSDictionary *responseHeaders = [self lowercasedHeadersOfResponse:task.response];
|
|
3189
|
+
|
|
3190
|
+
// Kept until JS has it: the upload may have finished while the app wasn't running
|
|
3191
|
+
taskConfig.responseCode = responseCode;
|
|
3192
|
+
taskConfig.responseBody = responseBody;
|
|
3193
|
+
taskConfig.responseHeaders = responseHeaders;
|
|
3194
|
+
taskConfig.bytesTotal = task.countOfBytesExpectedToSend;
|
|
3195
|
+
taskConfig.bytesUploaded = task.countOfBytesExpectedToSend;
|
|
3196
|
+
taskConfig.state = NSURLSessionTaskStateCompleted;
|
|
3197
|
+
finishedUploads[taskConfig.id] = taskConfig;
|
|
3198
|
+
[self persistFinishedUploads];
|
|
2653
3199
|
|
|
2654
3200
|
DLog(taskConfig.id, @"[RNBackgroundDownloader] - [handleUploadCompletion] success, responseCode: %ld", (long)responseCode);
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
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
|
|
3201
|
+
[self emitUploadComplete:taskConfig.id
|
|
3202
|
+
responseCode:responseCode
|
|
3203
|
+
responseBody:responseBody
|
|
3204
|
+
responseHeaders:responseHeaders
|
|
3205
|
+
parts:nil
|
|
3206
|
+
bytesUploaded:task.countOfBytesSent
|
|
3207
|
+
bytesTotal:task.countOfBytesExpectedToSend];
|
|
2672
3208
|
}
|
|
2673
3209
|
|
|
2674
3210
|
[self removeUploadTaskFromMap:task];
|
|
@@ -2806,18 +3342,20 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2806
3342
|
|
|
2807
3343
|
#pragma mark - Locked-device deferred move (issue #101)
|
|
2808
3344
|
|
|
2809
|
-
// Directory
|
|
2810
|
-
//
|
|
3345
|
+
// Directory used to hold finished downloads whose move to the final destination is deferred
|
|
3346
|
+
// because the device is locked. CompleteUntilFirstUserAuthentication can be written while
|
|
3347
|
+
// locked (background sessions only run after the first unlock), unlike Complete, without
|
|
3348
|
+
// leaving the file unprotected the way None would.
|
|
2811
3349
|
- (NSURL *)pendingMovesDirectory {
|
|
2812
3350
|
NSFileManager *fileManager = [NSFileManager defaultManager];
|
|
2813
3351
|
NSURL *cachesDir = [[fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject];
|
|
2814
3352
|
NSURL *dir = [cachesDir URLByAppendingPathComponent:@"RNBGDPendingMoves" isDirectory:YES];
|
|
3353
|
+
NSDictionary *attributes = @{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication};
|
|
2815
3354
|
if (![fileManager fileExistsAtPath:dir.path]) {
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
error:nil];
|
|
3355
|
+
[fileManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:attributes error:nil];
|
|
3356
|
+
} else {
|
|
3357
|
+
// Older versions created it with NSFileProtectionNone
|
|
3358
|
+
[fileManager setAttributes:attributes ofItemAtPath:dir.path error:nil];
|
|
2821
3359
|
}
|
|
2822
3360
|
return dir;
|
|
2823
3361
|
}
|
|
@@ -2834,8 +3372,8 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2834
3372
|
DLog(taskConfig.id, @"[RNBackgroundDownloader] - [stageAndDeferMove] staging failed: %@", stageError.localizedDescription);
|
|
2835
3373
|
return NO;
|
|
2836
3374
|
}
|
|
2837
|
-
//
|
|
2838
|
-
[fileManager setAttributes:@{NSFileProtectionKey:
|
|
3375
|
+
// Movable while locked, but still encrypted at rest (see pendingMovesDirectory)
|
|
3376
|
+
[fileManager setAttributes:@{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication} ofItemAtPath:stagingURL.path error:nil];
|
|
2839
3377
|
|
|
2840
3378
|
pendingMoves[taskConfig.id] = @{
|
|
2841
3379
|
@"id": taskConfig.id,
|
|
@@ -2984,7 +3522,7 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
2984
3522
|
- (NSMutableDictionary<NSNumber *, RNBGDUploadTaskConfig *> *)deserializeUploadConfig:(NSData *)taskMapRaw {
|
|
2985
3523
|
NSError *error = nil;
|
|
2986
3524
|
// 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];
|
|
3525
|
+
NSSet *classes = [NSSet setWithObjects:[RNBGDUploadTaskConfig class], [NSMutableDictionary class], [NSNumber class], [NSString class], [NSDictionary class], [NSArray class], nil];
|
|
2988
3526
|
NSMutableDictionary<NSNumber *, RNBGDUploadTaskConfig *> *taskMap = [NSKeyedUnarchiver unarchivedObjectOfClasses:classes fromData:taskMapRaw error:&error];
|
|
2989
3527
|
|
|
2990
3528
|
if (error) {
|
|
@@ -3023,11 +3561,13 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
|
|
|
3023
3561
|
NSString *dataPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByDeletingLastPathComponent];
|
|
3024
3562
|
NSString *dataPathWithoutUuid = [self getPathWithoutSuffixUuid:dataPath];
|
|
3025
3563
|
|
|
3026
|
-
|
|
3564
|
+
// A path shorter than the container (e.g. ".../Data/Application" itself) would make
|
|
3565
|
+
// substringFromIndex: throw outside any @try, crashing the app
|
|
3566
|
+
if ([path hasPrefix:bundlePathWithoutUuid] && path.length >= bundlePath.length) {
|
|
3027
3567
|
return [path substringFromIndex:[bundlePath length]];
|
|
3028
3568
|
}
|
|
3029
3569
|
|
|
3030
|
-
if ([path hasPrefix:dataPathWithoutUuid]) {
|
|
3570
|
+
if ([path hasPrefix:dataPathWithoutUuid] && path.length >= dataPath.length) {
|
|
3031
3571
|
return [path substringFromIndex:[dataPath length]];
|
|
3032
3572
|
}
|
|
3033
3573
|
|