From 4977508b364cbc372658a2698d454cf0c537d3c6 Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 22:25:04 +0200 Subject: [PATCH 1/7] iOS and JS --- FS.common.js | 90 ++++++++--------------------------------- RNFSManager.m | 109 +++++++++++++++++++++++++++----------------------- package.json | 1 - 3 files changed, 75 insertions(+), 125 deletions(-) diff --git a/FS.common.js b/FS.common.js index b68804d2..77de0dfb 100644 --- a/FS.common.js +++ b/FS.common.js @@ -2,40 +2,12 @@ // This file supports both iOS and Android -// Stop bluebird going nuts because it can't find "self" -if (typeof self === 'undefined') { - global.self = global; -} - var RNFSManager = require('react-native').NativeModules.RNFSManager; var NativeAppEventEmitter = require('react-native').NativeAppEventEmitter; // iOS var DeviceEventEmitter = require('react-native').DeviceEventEmitter; // Android -var Promise = require('bluebird'); var base64 = require('base-64'); var utf8 = require('utf8'); -var _readDir = Promise.promisify(RNFSManager.readDir); -var _exists = Promise.promisify(RNFSManager.exists); -var _stat = Promise.promisify(RNFSManager.stat); -var _readFile = Promise.promisify(RNFSManager.readFile); -var _writeFile = Promise.promisify(RNFSManager.writeFile); -var _moveFile = Promise.promisify(RNFSManager.moveFile); -var _unlink = Promise.promisify(RNFSManager.unlink); -var _mkdir = Promise.promisify(RNFSManager.mkdir); -var _downloadFile = Promise.promisify(RNFSManager.downloadFile); -var _pathForBundle = Promise.promisify(RNFSManager.pathForBundle); -var _getFSInfo = Promise.promisify(RNFSManager.getFSInfo); - -var convertError = (err) => { - if (err.isOperational && err.cause) { - err = err.cause; - } - - var error = new Error(err.description || err.message); - error.code = err.code; - throw error; -}; - var NSFileTypeRegular = RNFSManager.NSFileTypeRegular; var NSFileTypeDirectory = RNFSManager.NSFileTypeDirectory; @@ -49,7 +21,7 @@ var getJobId = () => { var RNFS = { readDir(dirpath) { - return _readDir(dirpath) + return RNFSManager.readDir(dirpath) .then(files => { return files.map(file => ({ name: file.name, @@ -58,20 +30,17 @@ var RNFS = { isFile: () => file.type === NSFileTypeRegular, isDirectory: () => file.type === NSFileTypeDirectory, })); - }) - .catch(convertError); + }); }, // Node style version (lowercase d). Returns just the names readdir(dirpath) { - return RNFS.readDir(dirpath) - .then(files => { - return files.map(file => file.name); - }); + return RNFSManager.readDir(dirpath) + .then(files => files.map(file => file.name)); }, stat(filepath) { - return _stat(filepath) + return RNFSManager.stat(filepath) .then((result) => { return { 'ctime': new Date(result.ctime*1000), @@ -85,15 +54,10 @@ var RNFS = { .catch(convertError); }, - exists(filepath) { - return _exists(filepath) - .catch(convertError); - }, - readFile(filepath, encoding) { if (!encoding) encoding = 'utf8'; - return _readFile(filepath) + return RNFSManager.readFile(filepath) .then((b64) => { var contents; @@ -108,8 +72,7 @@ var RNFS = { } return contents; - }) - .catch(convertError); + }); }, writeFile(filepath, contents, encoding, options) { @@ -127,33 +90,12 @@ var RNFS = { throw new Error('Invalid encoding type "' + encoding + '"'); } - return _writeFile(filepath, b64, options) - .catch(convertError); - }, - - moveFile(filepath, destPath) { - return _moveFile(filepath, destPath) - .catch(convertError); - }, - - pathForBundle(bundleName) { - return _pathForBundle(bundleName); - }, - - getFSInfo() { - return _getFSInfo() - .catch(convertError); - }, - - unlink(filepath) { - return _unlink(filepath) - .catch(convertError); + return RNFSManager.writeFile(filepath, b64, options); }, mkdir(filepath, excludeFromBackup) { excludeFromBackup = !!excludeFromBackup; - return _mkdir(filepath, excludeFromBackup) - .catch(convertError); + return RNFSManager.mkdir(filepath, excludeFromBackup); }, downloadFile(fromUrl, toFile, begin, progress) { @@ -179,18 +121,20 @@ var RNFS = { subscriptionAndroid = DeviceEventEmitter.addListener('DownloadProgress-' + jobId, progress); } - return _downloadFile(fromUrl, toFile, jobId) + return RNFSManager.downloadFile(fromUrl, toFile, jobId) .then(res => { if (subscriptionIos) subscriptionIos.remove(); if (subscriptionAndroid) subscriptionAndroid.remove(); return res; - }) - .catch(convertError); + }); }, - stopDownload(jobId) { - RNFSManager.stopDownload(jobId); - }, + stopDownload: RNFSManager.stopDownload, + moveFile: RNFSManager.moveFile, + pathForBundle: RNFSManager.pathForBundle, + getFSInfo: RNFSManager.getFSInfo, + unlink: RNFSManager.unlink, + exists: RNFSManager.exists, MainBundlePath: RNFSManager.MainBundlePath, CachesDirectoryPath: RNFSManager.NSCachesDirectoryPath, diff --git a/RNFSManager.m b/RNFSManager.m index 35780b15..5c02660a 100644 --- a/RNFSManager.m +++ b/RNFSManager.m @@ -30,7 +30,8 @@ - (dispatch_queue_t)methodQueue } RCT_EXPORT_METHOD(readDir:(NSString *)dirPath - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSFileManager *fileManager = [NSFileManager defaultManager]; NSError *error = nil; @@ -50,28 +51,30 @@ - (dispatch_queue_t)methodQueue }]; if (error) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; } - callback(@[[NSNull null], contents]); + resolve(contents); } RCT_EXPORT_METHOD(exists:(NSString *)filepath - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(__unused RCTPromiseRejectBlock)reject) { BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filepath]; - callback(@[[NSNull null], [NSNumber numberWithBool:fileExists]]); + resolve([NSNumber numberWithBool:fileExists]); } RCT_EXPORT_METHOD(stat:(NSString *)filepath - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSError *error = nil; NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filepath error:&error]; if (error) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; } attributes = @{ @@ -82,46 +85,49 @@ - (dispatch_queue_t)methodQueue @"mode": @([[NSString stringWithFormat:@"%ld", (long)[(NSNumber *)[attributes objectForKey:NSFilePosixPermissions] integerValue]] integerValue]) }; - callback(@[[NSNull null], attributes]); + resolve(attributes); } RCT_EXPORT_METHOD(writeFile:(NSString *)filepath contents:(NSString *)base64Content attributes:(NSDictionary *)attributes - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSData *data = [[NSData alloc] initWithBase64EncodedString:base64Content options:NSDataBase64DecodingIgnoreUnknownCharacters]; BOOL success = [[NSFileManager defaultManager] createFileAtPath:filepath contents:data attributes:attributes]; if (!success) { - return callback(@[[NSString stringWithFormat:@"Could not write file at path %@", filepath]]); + return reject([NSString stringWithFormat:@"Could not write file at path %@", filepath], nil, nil); } - callback(@[[NSNull null], [NSNumber numberWithBool:success], filepath]); + resolve([NSNumber numberWithBool:success]); } RCT_EXPORT_METHOD(unlink:(NSString*)filepath - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSFileManager *manager = [NSFileManager defaultManager]; BOOL exists = [manager fileExistsAtPath:filepath isDirectory:false]; if (!exists) { - return callback(@[[NSString stringWithFormat:@"File at path %@ does not exist", filepath]]); + return reject([NSString stringWithFormat:@"File at path %@ does not exist", filepath], nil, nil); } NSError *error = nil; BOOL success = [manager removeItemAtPath:filepath error:&error]; if (!success) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; } - callback(@[[NSNull null], [NSNumber numberWithBool:success], filepath]); + resolve([NSNumber numberWithBool:success]); } RCT_EXPORT_METHOD(mkdir:(NSString*)filepath excludeFromBackup:(BOOL)excludeFromBackup - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSFileManager *manager = [NSFileManager defaultManager]; @@ -129,7 +135,7 @@ - (dispatch_queue_t)methodQueue BOOL success = [manager createDirectoryAtPath:filepath withIntermediateDirectories:YES attributes:nil error:&error]; if (!success) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; } NSURL *url = [NSURL fileURLWithPath:filepath]; @@ -137,28 +143,30 @@ - (dispatch_queue_t)methodQueue success = [url setResourceValue: [NSNumber numberWithBool: excludeFromBackup] forKey: NSURLIsExcludedFromBackupKey error: &error]; if (!success) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; } - callback(@[[NSNull null], [NSNumber numberWithBool:success], filepath]); + resolve([NSNumber numberWithBool:success]); } RCT_EXPORT_METHOD(readFile:(NSString *)filepath - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSData *content = [[NSFileManager defaultManager] contentsAtPath:filepath]; NSString *base64Content = [content base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]; if (!base64Content) { - return callback(@[[NSString stringWithFormat:@"Could not read file at path %@", filepath]]); + return reject([NSString stringWithFormat:@"Could not read file at path %@", filepath], nil, nil); } - callback(@[[NSNull null], base64Content]); + resolve(base64Content); } RCT_EXPORT_METHOD(moveFile:(NSString *)filepath destPath:(NSString *)destPath - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSFileManager *manager = [NSFileManager defaultManager]; @@ -166,16 +174,17 @@ - (dispatch_queue_t)methodQueue BOOL success = [manager moveItemAtPath:filepath toPath:destPath error:&error]; if (!success) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; } - callback(@[[NSNull null], [NSNumber numberWithBool:success], destPath]); + resolve([NSNumber numberWithBool:success]); } RCT_EXPORT_METHOD(downloadFile:(NSString *)urlStr filepath:(NSString *)filepath jobId:(nonnull NSNumber *)jobId - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { DownloadParams* params = [DownloadParams alloc]; @@ -189,11 +198,11 @@ - (dispatch_queue_t)methodQueue if (bytesWritten) { [result setObject:bytesWritten forKey: @"bytesWritten"]; } - return callback(@[[NSNull null], result]); + return resolve(result); }; params.errorCallback = ^(NSError* error) { - return callback([self makeErrorPayload:error]); + return [self reject:reject withError:error]; }; params.beginCallback = ^(NSNumber* statusCode, NSNumber* contentLength, NSDictionary* headers) { @@ -230,7 +239,8 @@ - (dispatch_queue_t)methodQueue } RCT_EXPORT_METHOD(pathForBundle:(NSString *)bundleNamed - callback:(RCTResponseSenderBlock)callback) + resolver:(RCTPromiseResolveBlock)resolve + rejecter:(RCTPromiseRejectBlock)reject) { NSString *path = [[NSBundle mainBundle].bundlePath stringByAppendingFormat:@"/%@.bundle", bundleNamed]; NSBundle *bundle = [NSBundle bundleWithPath:path]; @@ -245,38 +255,37 @@ - (dispatch_queue_t)methodQueue } if (path) { - callback(@[[NSNull null], path]); + resolve(path); } else { - callback(@[[NSError errorWithDomain:NSPOSIXErrorDomain - code:NSFileNoSuchFileError - userInfo:nil].localizedDescription, - [NSNull null]]); + NSError *error = [NSError errorWithDomain:NSPOSIXErrorDomain + code:NSFileNoSuchFileError + userInfo:nil]; + + [self reject:reject withError:error]; } } -RCT_EXPORT_METHOD(getFSInfo:(RCTResponseSenderBlock)callback) +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]; - + 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]; - - callback(@[[NSNull null], - @{ - @"totalSpace": [NSNumber numberWithUnsignedLongLong:totalSpace], - @"freeSpace": [NSNumber numberWithUnsignedLongLong:totalFreeSpace] - } - ]); + + resolve(@{ + @"totalSpace": [NSNumber numberWithUnsignedLongLong:totalSpace], + @"freeSpace": [NSNumber numberWithUnsignedLongLong:totalFreeSpace] + }); } else { - callback(@[error, [NSNull null]]); + [self reject:reject withError:error]; } } @@ -285,12 +294,10 @@ - (NSNumber *)dateToTimeIntervalNumber:(NSDate *)date return @([date timeIntervalSince1970]); } -- (NSArray *)makeErrorPayload:(NSError *)error +- (void)reject:(RCTPromiseRejectBlock)reject withError:(NSError *)error { - return @[@{ - @"description": error.localizedDescription, - @"code": @(error.code) - }]; + NSString *codeWithDomain = [NSString stringWithFormat:@"E%@%zd", error.domain.uppercaseString, error.code]; + reject(codeWithDomain, error.localizedDescription, error); } - (NSString *)getPathForDirectory:(int)directory diff --git a/package.json b/package.json index 6065be92..cbb2244a 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,6 @@ "license": "MIT", "dependencies": { "base-64": "^0.1.0", - "bluebird": "^2.9.25", "utf8": "^2.1.1" }, "devDependencies": { From e12cc5a95d939a8498382c147ad20b216cffddb0 Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 22:29:17 +0200 Subject: [PATCH 2/7] Indent --- RNFSManager.m | 96 +++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/RNFSManager.m b/RNFSManager.m index 5c02660a..73086767 100644 --- a/RNFSManager.m +++ b/RNFSManager.m @@ -51,7 +51,7 @@ - (dispatch_queue_t)methodQueue }]; if (error) { - return [self reject:reject withError:error]; + return [self reject:reject withError:error]; } resolve(contents); @@ -74,7 +74,7 @@ - (dispatch_queue_t)methodQueue NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filepath error:&error]; if (error) { - return [self reject:reject withError:error]; + return [self reject:reject withError:error]; } attributes = @{ @@ -112,13 +112,13 @@ - (dispatch_queue_t)methodQueue BOOL exists = [manager fileExistsAtPath:filepath isDirectory:false]; if (!exists) { - return reject([NSString stringWithFormat:@"File at path %@ does not exist", filepath], nil, nil); + return reject([NSString stringWithFormat:@"File at path %@ does not exist", filepath], nil, nil); } NSError *error = nil; BOOL success = [manager removeItemAtPath:filepath error:&error]; if (!success) { - return [self reject:reject withError:error]; + return [self reject:reject withError:error]; } resolve([NSNumber numberWithBool:success]); @@ -168,16 +168,16 @@ - (dispatch_queue_t)methodQueue resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { - NSFileManager *manager = [NSFileManager defaultManager]; + NSFileManager *manager = [NSFileManager defaultManager]; - NSError *error = nil; - BOOL success = [manager moveItemAtPath:filepath toPath:destPath error:&error]; + NSError *error = nil; + BOOL success = [manager moveItemAtPath:filepath toPath:destPath error:&error]; - if (!success) { - return [self reject:reject withError:error]; - } + if (!success) { + return [self reject:reject withError:error]; + } - resolve([NSNumber numberWithBool:success]); + resolve([NSNumber numberWithBool:success]); } RCT_EXPORT_METHOD(downloadFile:(NSString *)urlStr @@ -242,51 +242,51 @@ - (dispatch_queue_t)methodQueue resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { - NSString *path = [[NSBundle mainBundle].bundlePath stringByAppendingFormat:@"/%@.bundle", bundleNamed]; - NSBundle *bundle = [NSBundle bundleWithPath:path]; + 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) { + bundle = [NSBundle bundleForClass:NSClassFromString(bundleNamed)]; + path = bundle.bundlePath; + } - if (!bundle.isLoaded) { - [bundle load]; - } + if (!bundle.isLoaded) { + [bundle load]; + } - if (path) { - resolve(path); - } else { - NSError *error = [NSError errorWithDomain:NSPOSIXErrorDomain - code:NSFileNoSuchFileError - userInfo:nil]; + if (path) { + resolve(path); + } else { + NSError *error = [NSError errorWithDomain:NSPOSIXErrorDomain + code:NSFileNoSuchFileError + userInfo:nil]; - [self reject:reject withError:error]; - } + [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]; - } + 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 From 3f0f2910024e8f438fda3d3283bf9d323b59ce83 Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 22:53:51 +0200 Subject: [PATCH 3/7] Android part - untested yet --- .../src/main/java/com/rnfs/RNFSManager.java | 86 ++++++++----------- 1 file changed, 36 insertions(+), 50 deletions(-) diff --git a/android/src/main/java/com/rnfs/RNFSManager.java b/android/src/main/java/com/rnfs/RNFSManager.java index 36825880..77680183 100644 --- a/android/src/main/java/com/rnfs/RNFSManager.java +++ b/android/src/main/java/com/rnfs/RNFSManager.java @@ -1,35 +1,24 @@ package com.rnfs; -import java.util.List; import java.util.Map; import java.util.HashMap; -import java.util.ArrayList; import android.os.Environment; -import android.os.AsyncTask; import android.os.StatFs; import android.util.Base64; -import android.content.Context; import android.support.annotation.Nullable; import android.util.SparseArray; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; -import java.io.BufferedInputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.IOException; import java.net.URL; -import java.net.URLConnection; -import java.net.HttpURLConnection; -import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; -import com.facebook.react.bridge.Callback; +import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.Arguments; @@ -59,7 +48,7 @@ public String getName() { } @ReactMethod - public void writeFile(String filepath, String base64Content, ReadableMap options, Callback callback) { + public void writeFile(String filepath, String base64Content, ReadableMap options, Promise promise) { try { byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT); @@ -67,26 +56,26 @@ public void writeFile(String filepath, String base64Content, ReadableMap options outputStream.write(bytes); outputStream.close(); - callback.invoke(null, true, filepath); + promise.resolve(filepath); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @ReactMethod - public void exists(String filepath, Callback callback) { + public void exists(String filepath, Promise promise) { try { File file = new File(filepath); - callback.invoke(null, file.exists()); + promise.resolve(file.exists()); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @ReactMethod - public void readFile(String filepath, Callback callback) { + public void readFile(String filepath, Promise promise) { try { File file = new File(filepath); @@ -98,29 +87,29 @@ public void readFile(String filepath, Callback callback) { String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP); - callback.invoke(null, base64Content); + promise.resolve(base64Content); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @ReactMethod - public void moveFile(String filepath, String destPath, Callback callback) { + public void moveFile(String filepath, String destPath, Promise promise) { try { File from = new File(filepath); File to = new File(destPath); from.renameTo(to); - callback.invoke(null, true, destPath); + promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @ReactMethod - public void readDir(String directory, Callback callback) { + public void readDir(String directory, Promise promise) { try { File file = new File(directory); @@ -141,16 +130,15 @@ public void readDir(String directory, Callback callback) { fileMaps.pushMap(fileMap); } - callback.invoke(null, fileMaps); - + promise.resolve(fileMaps); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @ReactMethod - public void stat(String filepath, Callback callback) { + public void stat(String filepath, Promise promise) { try { File file = new File(filepath); @@ -163,15 +151,15 @@ public void stat(String filepath, Callback callback) { statMap.putInt("size", (int)file.length()); statMap.putInt("type", file.isDirectory() ? 1 : 0); - callback.invoke(null, statMap); + promise.resolve(statMap); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @ReactMethod - public void unlink(String filepath, Callback callback) { + public void unlink(String filepath, Promise promise) { try { File file = new File(filepath); @@ -179,10 +167,10 @@ public void unlink(String filepath, Callback callback) { boolean success = DeleteRecursive(file); - callback.invoke(null, success, filepath); + promise.resolve(success); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @@ -197,7 +185,7 @@ private boolean DeleteRecursive(File fileOrDirectory) { } @ReactMethod - public void mkdir(String filepath, Boolean excludeFromBackup, Callback callback) { + public void mkdir(String filepath, Boolean excludeFromBackup, Promise promise) { try { File file = new File(filepath); @@ -205,21 +193,21 @@ public void mkdir(String filepath, Boolean excludeFromBackup, Callback callback) boolean success = file.exists(); - callback.invoke(null, success, filepath); + promise.resolve(success); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext - .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) - .emit(eventName, params); + .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) + .emit(eventName, params); } @ReactMethod - public void downloadFile(String urlStr, final String filepath, final int jobId, final Callback callback) { + public void downloadFile(String urlStr, final String filepath, final int jobId, final Promise promise) { try { File file = new File(filepath); URL url = new URL(urlStr); @@ -238,9 +226,9 @@ public void onTaskCompleted(DownloadResult res) { infoMap.putInt("statusCode", res.statusCode); infoMap.putInt("bytesWritten", res.bytesWritten); - callback.invoke(null, infoMap); + promise.resolve(infoMap); } else { - callback.invoke(makeErrorPayload(res.exception)); + reject(promise, ex); } } }; @@ -283,7 +271,7 @@ public void onDownloadProgress(int contentLength, int bytesWritten) { this.downloaders.put(jobId, downloader); } catch (Exception ex) { ex.printStackTrace(); - callback.invoke(makeErrorPayload(ex)); + reject(promise, ex); } } @@ -297,12 +285,12 @@ public void stopDownload(int jobId) { } @ReactMethod - public void pathForBundle(String bundleNamed, Callback callback) { + public void pathForBundle(String bundleNamed, Promise promise) { // TODO: Not sure what equilivent would be? } @ReactMethod - public void getFSInfo(Callback callback) { + public void getFSInfo(Promise promise) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long totalSpace; @@ -318,13 +306,11 @@ public void getFSInfo(Callback callback) { WritableMap info = Arguments.createMap(); info.putDouble("totalSpace", (double)totalSpace); // Int32 too small, must use Double info.putDouble("freeSpace", (double)freeSpace); - callback.invoke(null, info); + promise.resolve(info); } - private WritableMap makeErrorPayload(Exception ex) { - WritableMap error = Arguments.createMap(); - error.putString("message", ex.getMessage()); - return error; + private void reject(Promise promise, Exception ex) { + promise.reject(ex.getClass().getSimpleName(), ex.getMessage()); } @Override From 7ac79c538443cc5f97be1720142e491eccb85ccf Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 22:55:08 +0200 Subject: [PATCH 4/7] Fix writeFile resolve argument --- android/src/main/java/com/rnfs/RNFSManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/java/com/rnfs/RNFSManager.java b/android/src/main/java/com/rnfs/RNFSManager.java index 77680183..41e11e19 100644 --- a/android/src/main/java/com/rnfs/RNFSManager.java +++ b/android/src/main/java/com/rnfs/RNFSManager.java @@ -56,7 +56,7 @@ public void writeFile(String filepath, String base64Content, ReadableMap options outputStream.write(bytes); outputStream.close(); - promise.resolve(filepath); + promise.resolve(true); } catch (Exception ex) { ex.printStackTrace(); reject(promise, ex); From ed09935d741d8c7eaa6316a20b0a8554264a8ed8 Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 22:57:05 +0200 Subject: [PATCH 5/7] Use react from node_modules --- android/build.gradle | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/android/build.gradle b/android/build.gradle index 3724888f..9afd60b1 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -4,7 +4,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:1.1.3' + classpath 'com.android.tools.build:gradle:1.5.0' } } @@ -25,10 +25,6 @@ android { } } -repositories { - mavenCentral() -} - dependencies { - compile 'com.facebook.react:react-native:0.12.+' + compile 'com.facebook.react:react-native:+' } From fac71d5ba638a0622fa02a3ad6c3917922e837d6 Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 22:59:30 +0200 Subject: [PATCH 6/7] Fix ex being undefined --- android/src/main/java/com/rnfs/RNFSManager.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/android/src/main/java/com/rnfs/RNFSManager.java b/android/src/main/java/com/rnfs/RNFSManager.java index 41e11e19..d4e43af4 100644 --- a/android/src/main/java/com/rnfs/RNFSManager.java +++ b/android/src/main/java/com/rnfs/RNFSManager.java @@ -228,7 +228,7 @@ public void onTaskCompleted(DownloadResult res) { promise.resolve(infoMap); } else { - reject(promise, ex); + reject(promise, res.exception); } } }; @@ -320,9 +320,9 @@ public Map getConstants() { constants.put(NSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath()); File externalDirectory = this.getReactApplicationContext().getExternalFilesDir(null); if (externalDirectory != null) { - constants.put(NSExternalDirectoryPath, externalDirectory.getAbsolutePath()); + constants.put(NSExternalDirectoryPath, externalDirectory.getAbsolutePath()); } else { - constants.put(NSExternalDirectoryPath, null); + constants.put(NSExternalDirectoryPath, null); } constants.put(NSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()); constants.put(NSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath()); From 3285c3d3e82cd21b55249e7ec71d6faf48e7218f Mon Sep 17 00:00:00 2001 From: Mike Grabowski Date: Sat, 14 May 2016 23:14:22 +0200 Subject: [PATCH 7/7] Do not return code --- android/src/main/java/com/rnfs/RNFSManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/java/com/rnfs/RNFSManager.java b/android/src/main/java/com/rnfs/RNFSManager.java index d4e43af4..f20b7e70 100644 --- a/android/src/main/java/com/rnfs/RNFSManager.java +++ b/android/src/main/java/com/rnfs/RNFSManager.java @@ -310,7 +310,7 @@ public void getFSInfo(Promise promise) { } private void reject(Promise promise, Exception ex) { - promise.reject(ex.getClass().getSimpleName(), ex.getMessage()); + promise.reject(null, ex.getMessage()); } @Override