Files
react-native-fs/android/src/main/java/com/rnfs/RNFSManager.java
T

355 lines
11 KiB
Java
Raw Normal View History

2015-10-19 14:40:05 +01:00
package com.rnfs;
2015-11-23 16:29:25 +00:00
import java.util.List;
2015-10-19 14:40:05 +01:00
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import android.os.Environment;
import android.os.AsyncTask;
2016-03-18 10:53:00 -07:00
import android.os.StatFs;
2015-10-19 14:40:05 +01:00
import android.util.Base64;
import android.content.Context;
2015-11-20 00:16:13 +00:00
import android.support.annotation.Nullable;
2015-11-23 16:29:25 +00:00
import android.util.SparseArray;
2015-10-19 14:40:05 +01:00
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
2015-10-21 00:17:03 +01:00
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
2015-10-21 00:17:03 +01:00
import java.net.URL;
import java.net.URLConnection;
2015-11-20 00:16:13 +00:00
import java.net.HttpURLConnection;
2015-10-19 14:40:05 +01:00
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.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
2016-05-14 23:19:27 +02:00
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
2015-11-20 00:16:13 +00:00
2015-10-19 14:40:05 +01:00
public class RNFSManager extends ReactContextBaseJavaModule {
private static final String NSDocumentDirectoryPath = "NSDocumentDirectoryPath";
private static final String NSExternalDirectoryPath = "NSExternalDirectoryPath";
private static final String NSPicturesDirectoryPath = "NSPicturesDirectoryPath";
2016-05-14 23:42:57 +02:00
private static final String NSTemporaryDirectoryPath = "NSTemporaryDirectoryPath";
private static final String NSCachesDirectoryPath = "NSCachesDirectoryPath";
2015-10-19 14:40:05 +01:00
private static final String NSDocumentDirectory = "NSDocumentDirectory";
private static final String NSFileTypeRegular = "NSFileTypeRegular";
private static final String NSFileTypeDirectory = "NSFileTypeDirectory";
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
private SparseArray<Downloader> downloaders = new SparseArray<Downloader>();
2015-10-19 14:40:05 +01:00
public RNFSManager(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return "RNFSManager";
}
@ReactMethod
public void writeFile(String filepath, String base64Content, ReadableMap options, Callback callback) {
try {
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
FileOutputStream outputStream = new FileOutputStream(filepath);
outputStream.write(bytes);
outputStream.close();
2015-10-22 01:25:52 +01:00
callback.invoke(null, true, filepath);
2015-10-19 14:40:05 +01:00
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
2016-04-07 15:29:36 -04:00
2016-01-28 21:36:31 +08:00
@ReactMethod
2016-01-29 02:20:02 +08:00
public void exists(String filepath, Callback callback) {
2016-01-28 21:36:31 +08:00
try {
File file = new File(filepath);
callback.invoke(null, file.exists());
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
2015-10-19 14:40:05 +01:00
}
}
@ReactMethod
public void readFile(String filepath, Callback callback) {
try {
File file = new File(filepath);
if (!file.exists()) throw new Exception("File does not exist");
FileInputStream inputStream = new FileInputStream(filepath);
byte[] buffer = new byte[(int)file.length()];
inputStream.read(buffer);
2015-10-22 01:25:52 +01:00
String base64Content = Base64.encodeToString(buffer, Base64.NO_WRAP);
2015-10-19 14:40:05 +01:00
callback.invoke(null, base64Content);
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
2016-01-27 16:52:56 +00:00
@ReactMethod
public void moveFile(String filepath, String destPath, Callback callback) {
try {
File from = new File(filepath);
File to = new File(destPath);
from.renameTo(to);
callback.invoke(null, true, destPath);
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
2015-10-19 14:40:05 +01:00
@ReactMethod
2015-10-22 01:25:52 +01:00
public void readDir(String directory, Callback callback) {
2015-10-19 14:40:05 +01:00
try {
2015-10-22 01:25:52 +01:00
File file = new File(directory);
2015-10-19 14:40:05 +01:00
2015-10-22 01:25:52 +01:00
if (!file.exists()) throw new Exception("Folder does not exist");
2015-10-20 23:31:29 +01:00
2015-10-19 14:40:05 +01:00
File[] files = file.listFiles();
WritableArray fileMaps = Arguments.createArray();
for (File childFile : files) {
WritableMap fileMap = Arguments.createMap();
fileMap.putString("name", childFile.getName());
fileMap.putString("path", childFile.getAbsolutePath());
2015-10-20 23:31:29 +01:00
fileMap.putInt("size", (int)childFile.length());
fileMap.putInt("type", childFile.isDirectory() ? 1 : 0);
2015-10-19 14:40:05 +01:00
fileMaps.pushMap(fileMap);
}
callback.invoke(null, fileMaps);
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
@ReactMethod
public void stat(String filepath, Callback callback) {
try {
File file = new File(filepath);
if (!file.exists()) throw new Exception("File does not exist");
WritableMap statMap = Arguments.createMap();
statMap.putInt("ctime", (int)(file.lastModified() / 1000));
statMap.putInt("mtime", (int)(file.lastModified() / 1000));
statMap.putInt("size", (int)file.length());
statMap.putInt("type", file.isDirectory() ? 1 : 0);
callback.invoke(null, statMap);
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
@ReactMethod
public void unlink(String filepath, Callback callback) {
try {
File file = new File(filepath);
if (!file.exists()) throw new Exception("File does not exist");
2015-10-20 23:31:29 +01:00
boolean success = DeleteRecursive(file);
callback.invoke(null, success, filepath);
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
private boolean DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
return fileOrDirectory.delete();
2015-11-20 00:16:13 +00:00
}
2015-10-20 23:31:29 +01:00
@ReactMethod
2015-10-22 01:25:52 +01:00
public void mkdir(String filepath, Boolean excludeFromBackup, Callback callback) {
2015-10-20 23:31:29 +01:00
try {
File file = new File(filepath);
file.mkdirs();
boolean success = file.exists();
2015-10-19 14:40:05 +01:00
callback.invoke(null, success, filepath);
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
2015-11-20 00:16:13 +00:00
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
reactContext
2016-05-14 23:19:27 +02:00
.getJSModule(RCTNativeAppEventEmitter.class)
2015-11-23 16:29:25 +00:00
.emit(eventName, params);
2015-11-20 00:16:13 +00:00
}
2015-10-21 00:17:03 +01:00
@ReactMethod
public void downloadFile(ReadableMap options, final Callback callback) {
2015-10-21 00:17:03 +01:00
try {
File file = new File(options.getString("toFile"));
URL url = new URL(options.getString("fromUrl"));
final int jobId = options.getInt("jobId");
ReadableMap headers = options.getMap("headers");
int progressDivider = options.getInt("progressDivider");
2015-10-21 00:17:03 +01:00
DownloadParams params = new DownloadParams();
2016-04-07 15:29:36 -04:00
params.src = url;
params.dest = file;
2016-06-03 23:59:08 +01:00
params.headers = headers;
2016-05-31 12:46:03 +03:00
params.progressDivider = progressDivider;
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
params.onTaskCompleted = new DownloadParams.OnTaskCompleted() {
public void onTaskCompleted(DownloadResult res) {
if (res.exception == null) {
WritableMap infoMap = Arguments.createMap();
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
infoMap.putInt("jobId", jobId);
infoMap.putInt("statusCode", res.statusCode);
infoMap.putInt("bytesWritten", res.bytesWritten);
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
callback.invoke(null, infoMap);
} else {
2015-11-23 16:29:25 +00:00
callback.invoke(makeErrorPayload(res.exception));
}
}
};
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
params.onDownloadBegin = new DownloadParams.OnDownloadBegin() {
public void onDownloadBegin(int statusCode, int contentLength, Map<String, String> headers) {
WritableMap headersMap = Arguments.createMap();
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
for (Map.Entry<String, String> entry : headers.entrySet()) {
headersMap.putString(entry.getKey(), entry.getValue());
}
2016-04-07 15:29:36 -04:00
2015-11-20 00:16:13 +00:00
WritableMap data = Arguments.createMap();
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
data.putInt("jobId", jobId);
2015-11-20 00:16:13 +00:00
data.putInt("statusCode", statusCode);
data.putInt("contentLength", contentLength);
2015-11-23 16:29:25 +00:00
data.putMap("headers", headersMap);
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
sendEvent(getReactApplicationContext(), "DownloadBegin-" + jobId, data);
}
};
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
params.onDownloadProgress = new DownloadParams.OnDownloadProgress() {
public void onDownloadProgress(int contentLength, int bytesWritten) {
WritableMap data = Arguments.createMap();
2016-04-07 15:29:36 -04:00
data.putInt("jobId", jobId);
2015-11-23 16:29:25 +00:00
data.putInt("contentLength", contentLength);
2015-11-20 00:16:13 +00:00
data.putInt("bytesWritten", bytesWritten);
sendEvent(getReactApplicationContext(), "DownloadProgress-" + jobId, data);
}
};
2015-10-21 00:17:03 +01:00
2015-11-23 16:29:25 +00:00
Downloader downloader = new Downloader();
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
downloader.execute(params);
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
this.downloaders.put(jobId, downloader);
2015-10-21 00:17:03 +01:00
} catch (Exception ex) {
ex.printStackTrace();
callback.invoke(makeErrorPayload(ex));
}
}
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
@ReactMethod
public void stopDownload(int jobId) {
Downloader downloader = this.downloaders.get(jobId);
2016-04-07 15:29:36 -04:00
2015-11-23 16:29:25 +00:00
if (downloader != null) {
2016-04-07 15:29:36 -04:00
downloader.stop();
}
2015-11-20 00:16:13 +00:00
}
2015-10-19 14:40:05 +01:00
@ReactMethod
public void pathForBundle(String bundleNamed, Callback callback) {
// TODO: Not sure what equilivent would be?
}
2016-03-18 10:53:00 -07:00
@ReactMethod
public void getFSInfo(Callback callback) {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long totalSpace;
long freeSpace;
if (android.os.Build.VERSION.SDK_INT >= 18) {
totalSpace = stat.getTotalBytes();
freeSpace = stat.getFreeBytes();
} else {
long blockSize = stat.getBlockSize();
totalSpace = blockSize * stat.getBlockCount();
freeSpace = blockSize * stat.getAvailableBlocks();
}
WritableMap info = Arguments.createMap();
info.putDouble("totalSpace", (double)totalSpace); // Int32 too small, must use Double
info.putDouble("freeSpace", (double)freeSpace);
2016-03-18 10:53:00 -07:00
callback.invoke(null, info);
}
2015-10-19 14:40:05 +01:00
private WritableMap makeErrorPayload(Exception ex) {
WritableMap error = Arguments.createMap();
error.putString("message", ex.getMessage());
return error;
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(NSDocumentDirectory, 0);
constants.put(NSDocumentDirectoryPath, this.getReactApplicationContext().getFilesDir().getAbsolutePath());
2016-05-19 09:39:19 +02:00
constants.put(NSTemporaryDirectoryPath, null);
File externalDirectory = this.getReactApplicationContext().getExternalFilesDir(null);
if (externalDirectory != null) {
constants.put(NSExternalDirectoryPath, externalDirectory.getAbsolutePath());
} else {
constants.put(NSExternalDirectoryPath, null);
}
constants.put(NSPicturesDirectoryPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath());
constants.put(NSCachesDirectoryPath, this.getReactApplicationContext().getCacheDir().getAbsolutePath());
2015-10-19 14:40:05 +01:00
constants.put(NSFileTypeRegular, 0);
constants.put(NSFileTypeDirectory, 1);
return constants;
}
}