forked from itinance/react-native-fs
-
Notifications
You must be signed in to change notification settings - Fork 3
/
RNFSManager.m
504 lines (399 loc) · 17 KB
/
RNFSManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//
// RNFSManager.m
// RNFSManager
//
// Created by Johannes Lumpe on 08/05/15.
// Copyright (c) 2015 Johannes Lumpe. All rights reserved.
//
#import "RNFSManager.h"
#import "RCTBridge.h"
#import "NSArray+Map.h"
#import "Downloader.h"
#import "Uploader.h"
#import "RCTEventDispatcher.h"
@interface RNFSManager()
@property (retain) NSMutableDictionary* downloaders;
@property (retain) NSMutableDictionary* uploaders;
@end
static NSMutableDictionary* sessionCompletionHandlers;
static NSString* errorDomain;
@implementation RNFSManager
@synthesize bridge = _bridge;
RCT_EXPORT_MODULE();
- (dispatch_queue_t)methodQueue
{
return dispatch_queue_create("pe.lum.rnfs", DISPATCH_QUEUE_SERIAL);
}
RCT_EXPORT_METHOD(readDir:(NSString *)dirPath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *contents = [fileManager contentsOfDirectoryAtPath:dirPath error:&error];
contents = [contents rnfs_mapObjectsUsingBlock:^id(NSString *obj, NSUInteger idx) {
NSString *path = [dirPath stringByAppendingPathComponent:obj];
NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:nil];
return @{
@"name": obj,
@"path": path,
@"size": [attributes objectForKey:NSFileSize],
@"type": [attributes objectForKey:NSFileType]
};
}];
if (error) {
return [self reject:reject withError:error];
}
resolve(contents);
}
RCT_EXPORT_METHOD(exists:(NSString *)filepath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(__unused RCTPromiseRejectBlock)reject)
{
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filepath];
resolve([NSNumber numberWithBool:fileExists]);
}
RCT_EXPORT_METHOD(stat:(NSString *)filepath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSError *error = nil;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filepath error:&error];
if (error) {
return [self reject:reject withError:error];
}
attributes = @{
@"ctime": [self dateToTimeIntervalNumber:(NSDate *)[attributes objectForKey:NSFileCreationDate]],
@"mtime": [self dateToTimeIntervalNumber:(NSDate *)[attributes objectForKey:NSFileModificationDate]],
@"size": [attributes objectForKey:NSFileSize],
@"type": [attributes objectForKey:NSFileType],
@"mode": @([[NSString stringWithFormat:@"%ld", (long)[(NSNumber *)[attributes objectForKey:NSFilePosixPermissions] integerValue]] integerValue])
};
resolve(attributes);
}
RCT_EXPORT_METHOD(writeFile:(NSString *)filepath
contents:(NSString *)base64Content
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64Content options:NSDataBase64DecodingIgnoreUnknownCharacters];
BOOL success = [[NSFileManager defaultManager] createFileAtPath:filepath contents:data attributes:nil];
if (!success) {
return reject(@"ENOENT", [NSString stringWithFormat:@"ENOENT: no such file or directory, open '%@'", filepath], nil);
}
return resolve(nil);
}
RCT_EXPORT_METHOD(appendFile:(NSString *)filepath
contents:(NSString *)base64Content
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64Content options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSFileManager *fM = [NSFileManager defaultManager];
if (![fM fileExistsAtPath:filepath])
{
BOOL success = [[NSFileManager defaultManager] createFileAtPath:filepath contents:data attributes:nil];
if (!success) {
return reject(@"ENOENT", [NSString stringWithFormat:@"ENOENT: no such file or directory, open '%@'", filepath], nil);
} else {
return resolve(nil);
}
}
@try {
NSFileHandle *fH = [NSFileHandle fileHandleForUpdatingAtPath:filepath];
[fH seekToEndOfFile];
[fH writeData:data];
return resolve(nil);
} @catch (NSException *e) {
return [self reject:reject withError:e];
}
}
RCT_EXPORT_METHOD(unlink:(NSString*)filepath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSFileManager *manager = [NSFileManager defaultManager];
BOOL exists = [manager fileExistsAtPath:filepath isDirectory:false];
if (!exists) {
return reject(@"ENOENT", [NSString stringWithFormat:@"ENOENT: no such file or directory, open '%@'", filepath], nil);
}
NSError *error = nil;
BOOL success = [manager removeItemAtPath:filepath error:&error];
if (!success) {
return [self reject:reject withError:error];
}
resolve(nil);
}
RCT_EXPORT_METHOD(mkdir:(NSString *)filepath
options:(NSDictionary *)options
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
BOOL success = [manager createDirectoryAtPath:filepath withIntermediateDirectories:YES attributes:nil error:&error];
if (!success) {
return [self reject:reject withError:error];
}
NSURL *url = [NSURL fileURLWithPath:filepath];
if ([[options allKeys] containsObject:@"NSURLIsExcludedFromBackupKey"]) {
NSNumber *value = options[@"NSURLIsExcludedFromBackupKey"];
success = [url setResourceValue: value forKey: NSURLIsExcludedFromBackupKey error: &error];
if (!success) {
return [self reject:reject withError:error];
}
}
resolve(nil);
}
RCT_EXPORT_METHOD(readFile:(NSString *)filepath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filepath];
if (!fileExists) {
return reject(@"ENOENT", [NSString stringWithFormat:@"ENOENT: no such file or directory, open '%@'", filepath], nil);
}
NSError *error = nil;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filepath error:&error];
if (error) {
return [self reject:reject withError:error];
}
if ([attributes objectForKey:NSFileType] == NSFileTypeDirectory) {
return reject(@"EISDIR", @"EISDIR: illegal operation on a directory, read", nil);
}
NSData *content = [[NSFileManager defaultManager] contentsAtPath:filepath];
NSString *base64Content = [content base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
resolve(base64Content);
}
RCT_EXPORT_METHOD(moveFile:(NSString *)filepath
destPath:(NSString *)destPath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
BOOL success = [manager moveItemAtPath:filepath toPath:destPath error:&error];
if (!success) {
return [self reject:reject withError:error];
}
resolve(nil);
}
RCT_EXPORT_METHOD(copyFile:(NSString *)filepath
destPath:(NSString *)destPath
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
BOOL success = [manager copyItemAtPath:filepath toPath:destPath error:&error];
if (!success) {
return [self reject:reject withError:error];
}
resolve(nil);
}
RCT_EXPORT_METHOD(downloadFile:(NSDictionary *)options
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
RNFSDownloadParams* params = [RNFSDownloadParams alloc];
NSNumber* jobId = options[@"jobId"];
params.fromUrl = options[@"fromUrl"];
params.toFile = options[@"toFile"];
NSDictionary* headers = options[@"headers"];
params.headers = headers;
NSNumber* background = options[@"background"];
params.background = [background boolValue];
NSNumber* progressDivider = options[@"progressDivider"];
params.progressDivider = progressDivider;
params.completeCallback = ^(NSNumber* statusCode, NSNumber* bytesWritten) {
NSLog(@"completeCallback. Status: %d. Bytes: %d Job: %d", [statusCode integerValue], bytesWritten, jobId);
NSMutableDictionary* result = [[NSMutableDictionary alloc] initWithDictionary: @{@"jobId": jobId,
@"statusCode": statusCode}];
if (bytesWritten) {
[result setObject:bytesWritten forKey: @"bytesWritten"];
}
return resolve(result);
};
params.errorCallback = ^(NSError* error) {
return [self reject:reject withError:error];
};
params.beginCallback = ^(NSNumber* statusCode, NSNumber* contentLength, NSDictionary* headers) {
[self.bridge.eventDispatcher sendAppEventWithName:[NSString stringWithFormat:@"DownloadBegin-%@", jobId]
body:@{@"jobId": jobId,
@"statusCode": statusCode,
@"contentLength": contentLength,
@"headers": headers}];
};
params.progressCallback = ^(NSNumber* contentLength, NSNumber* bytesWritten) {
[self.bridge.eventDispatcher sendAppEventWithName:[NSString stringWithFormat:@"DownloadProgress-%@", jobId]
body:@{@"jobId": jobId,
@"contentLength": contentLength,
@"bytesWritten": bytesWritten}];
};
if (!self.downloaders) self.downloaders = [[NSMutableDictionary alloc] init];
RNFSDownloader* downloader = [RNFSDownloader alloc];
[downloader downloadFile:params];
[self.downloaders setValue:downloader forKey:[jobId stringValue]];
}
RCT_EXPORT_METHOD(stopDownload:(nonnull NSNumber *)jobId)
{
RNFSDownloader* downloader = [self.downloaders objectForKey:[jobId stringValue]];
if (downloader != nil) {
[downloader stopDownload];
}
}
RCT_EXPORT_METHOD(uploadFiles:(NSDictionary *)options
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
RNFSUploadParams* params = [RNFSUploadParams alloc];
NSNumber* jobId = options[@"jobId"];
params.toUrl = options[@"toUrl"];
params.files = options[@"files"];
NSDictionary* headers = options[@"headers"];
NSDictionary* fields = options[@"fields"];
NSString* method = options[@"method"];
params.headers = headers;
params.fields = fields;
params.method = method;
NSNumber* background = options[@"background"];
params.background = [background boolValue];
params.completeCallback = ^(NSString* body, NSURLResponse *resp) {
NSMutableDictionary* result = [[NSMutableDictionary alloc] initWithDictionary: @{@"jobId": jobId,
@"body": body}];
if ([resp isKindOfClass:[NSHTTPURLResponse class]]) {
[result setValue:((NSHTTPURLResponse *)resp).allHeaderFields forKey:@"headers"];
[result setValue:[NSNumber numberWithUnsignedInteger:((NSHTTPURLResponse *)resp).statusCode] forKey:@"statusCode"];
}
return resolve(result);
};
params.errorCallback = ^(NSError* error) {
return [self reject:reject withError:error];
};
params.beginCallback = ^() {
[self.bridge.eventDispatcher sendAppEventWithName:[NSString stringWithFormat:@"UploadBegin-%@", jobId]
body:@{@"jobId": jobId}];
};
params.progressCallback = ^(NSNumber* totalBytesExpectedToSend, NSNumber* totalBytesSent) {
[self.bridge.eventDispatcher sendAppEventWithName:[NSString stringWithFormat:@"UploadProgress-%@", jobId]
body:@{@"jobId": jobId,
@"totalBytesExpectedToSend": totalBytesExpectedToSend,
@"totalBytesSent": totalBytesSent}];
};
if (!self.uploaders) self.uploaders = [[NSMutableDictionary alloc] init];
RNFSUploader* uploader = [RNFSUploader alloc];
[uploader uploadFiles:params];
[self.uploaders setValue:uploader forKey:[jobId stringValue]];
}
RCT_EXPORT_METHOD(stopUpload:(nonnull NSNumber *)jobId)
{
RNFSUploader* uploader = [self.uploaders objectForKey:[jobId stringValue]];
if (uploader != nil) {
[uploader stopUpload];
}
}
RCT_EXPORT_METHOD(pathForBundle:(NSString *)bundleNamed
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
NSString *path = [[NSBundle mainBundle].bundlePath stringByAppendingFormat:@"/%@.bundle", bundleNamed];
NSBundle *bundle = [NSBundle bundleWithPath:path];
if (!bundle) {
bundle = [NSBundle bundleForClass:NSClassFromString(bundleNamed)];
path = bundle.bundlePath;
}
if (!bundle.isLoaded) {
[bundle load];
}
if (path) {
resolve(path);
} else {
NSError *error = [NSError errorWithDomain:NSPOSIXErrorDomain
code:NSFileNoSuchFileError
userInfo:nil];
[self reject:reject withError:error];
}
}
RCT_EXPORT_METHOD(getFSInfo:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
unsigned long long totalSpace = 0;
unsigned long long totalFreeSpace = 0;
__autoreleasing NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error:&error];
if (dictionary) {
NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
resolve(@{
@"totalSpace": [NSNumber numberWithUnsignedLongLong:totalSpace],
@"freeSpace": [NSNumber numberWithUnsignedLongLong:totalFreeSpace]
});
} else {
[self reject:reject withError:error];
}
}
- (NSNumber *)dateToTimeIntervalNumber:(NSDate *)date
{
return @([date timeIntervalSince1970]);
}
- (void)reject:(RCTPromiseRejectBlock)reject withError:(NSError *)error
{
NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%zd", error.domain.uppercaseString, error.code];
reject(codeWithDomain, error.localizedDescription, error);
}
- (NSString *)getPathForDirectory:(int)directory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
return [paths firstObject];
}
- (NSDictionary *)constantsToExport
{
return @{
@"RNFSMainBundlePath": [[NSBundle mainBundle] bundlePath],
@"RNFSCachesDirectoryPath": [self getPathForDirectory:NSCachesDirectory],
@"RNFSDocumentDirectoryPath": [self getPathForDirectory:NSDocumentDirectory],
@"RNFSExternalDirectoryPath": [NSNull null],
@"RNFSExternalStorageDirectoryPath": [NSNull null],
@"RNFSTemporaryDirectoryPath": NSTemporaryDirectory(),
@"RNFSLibraryDirectoryPath": [self getPathForDirectory:NSLibraryDirectory],
@"RNFSFileTypeRegular": NSFileTypeRegular,
@"RNFSFileTypeDirectory": NSFileTypeDirectory
};
}
+ (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
{
NSString * sessionId = session.configuration.identifier;
NSLog(@"URLSessionDidFinishEventsForBackgroundURLSession start %@", sessionId);
completionHandler sessionCompletionHandler = [RNFSManager getCompletionHandlerForSessionId: sessionId];
if (sessionCompletionHandler) {
[NSThread sleepForTimeInterval: 10.0];
NSLog(@"URLSessionDidFinishEventsForBackgroundURLSession calling completion handler %@", sessionId);
[RNFSManager setCompletionHandler:nil forSessionId: sessionId];
sessionCompletionHandler();
}
}
+ (void) setCompletionHandler:(completionHandler)handler forSessionId:(NSString*) sessionId {
if (! sessionCompletionHandlers) {
sessionCompletionHandlers = [[NSMutableDictionary alloc] init];
}
if (handler == nil) {
[sessionCompletionHandlers removeObjectForKey:sessionId];
} else {
[sessionCompletionHandlers setObject:handler forKey:sessionId];
}
}
+ (completionHandler) getCompletionHandlerForSessionId:(NSString*)sessionId {
if (! sessionCompletionHandlers) {
return nil;
}
return [sessionCompletionHandlers objectForKey:sessionId];
}
+ (void) setErrorDomain:(NSString *)domain {
errorDomain = domain;
}
+ (NSString *) getErrorDomain {
return errorDomain;
}
@end