Changed all usages of FileHelper to use the new DataResource mechanism.

This commit is contained in:
Shravan Narayan 2013-05-05 05:32:20 -04:00 committed by Braden Shepherdson
parent 62c3e46529
commit 867358ea81
5 changed files with 101 additions and 108 deletions

View File

@ -20,7 +20,7 @@ package org.apache.cordova;
import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.DataResource;
import android.content.Context; import android.content.Context;
import android.media.AudioManager; import android.media.AudioManager;
@ -56,6 +56,11 @@ public class AudioHandler extends CordovaPlugin {
this.pausedForPhone = new ArrayList<AudioPlayer>(); this.pausedForPhone = new ArrayList<AudioPlayer>();
} }
public String getFilePath(String url, String source){
DataResource dataResource = DataResource.initiateNewDataRequestForUri(url, this.webView.pluginManager, cordova, source);
return dataResource.getRealFile().getPath();
}
/** /**
* Executes the request and returns PluginResult. * Executes the request and returns PluginResult.
* @param action The action to execute. * @param action The action to execute.
@ -68,13 +73,13 @@ public class AudioHandler extends CordovaPlugin {
String result = ""; String result = "";
if (action.equals("startRecordingAudio")) { if (action.equals("startRecordingAudio")) {
this.startRecordingAudio(args.getString(0), FileHelper.stripFileProtocol(args.getString(1))); this.startRecordingAudio(args.getString(0), getFilePath(args.getString(1), "AudioHandler.startRecordingAudio"));
} }
else if (action.equals("stopRecordingAudio")) { else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0)); this.stopRecordingAudio(args.getString(0));
} }
else if (action.equals("startPlayingAudio")) { else if (action.equals("startPlayingAudio")) {
this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(args.getString(1))); this.startPlayingAudio(args.getString(0), getFilePath(args.getString(1), "AudioHandler.startPlayingAudio"));
} }
else if (action.equals("seekToAudio")) { else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1)); this.seekToAudio(args.getString(0), args.getInt(1));
@ -102,7 +107,7 @@ public class AudioHandler extends CordovaPlugin {
} }
else if (action.equals("create")) { else if (action.equals("create")) {
String id = args.getString(0); String id = args.getString(0);
String src = FileHelper.stripFileProtocol(args.getString(1)); String src = getFilePath(args.getString(1), "AudioHandler.create");
AudioPlayer audio = new AudioPlayer(this, id, src); AudioPlayer audio = new AudioPlayer(this, id, src);
this.players.put(id, audio); this.players.put(id, audio);
} }

View File

@ -20,15 +20,16 @@ package org.apache.cordova;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.DataResource;
import org.apache.cordova.api.LOG; import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
@ -42,7 +43,6 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.graphics.Matrix; import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.media.MediaScannerConnection; import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient; import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri; import android.net.Uri;
@ -290,7 +290,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// If sending base64 image back // If sending base64 image back
if (destType == DATA_URL) { if (destType == DATA_URL) {
bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString())); bitmap = getScaledBitmap(imageUri.toString());
if (bitmap == null) { if (bitmap == null) {
// Try to get the bitmap from intent. // Try to get the bitmap from intent.
bitmap = (Bitmap)intent.getExtras().get("data"); bitmap = (Bitmap)intent.getExtras().get("data");
@ -316,7 +316,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
if (this.saveToPhotoAlbum) { if (this.saveToPhotoAlbum) {
Uri inputUri = getUriFromMediaStore(); Uri inputUri = getUriFromMediaStore();
//Just because we have a media URI doesn't mean we have a real file, we need to make it //Just because we have a media URI doesn't mean we have a real file, we need to make it
uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova))); DataResource dataResource = DataResource.initiateNewDataRequestForUri(inputUri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent");
File file = dataResource.getRealFile();
uri = Uri.fromFile(file);
} else { } else {
uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg")); uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
} }
@ -332,14 +334,15 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
this.callbackContext.success(uri.toString()); this.callbackContext.success(uri.toString());
} else { } else {
bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString())); bitmap = getScaledBitmap(imageUri.toString());
if (rotate != 0 && this.correctOrientation) { if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif); bitmap = getRotatedBitmap(rotate, bitmap, exif);
} }
// Add compressed version of captured image to returned media store Uri // Add compressed version of captured image to returned media store Uri
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); DataResource dataResource = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent");
OutputStream os = dataResource.getOs();
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close(); os.close();
@ -347,7 +350,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
if (this.encodingType == JPEG) { if (this.encodingType == JPEG) {
String exifPath; String exifPath;
if (this.saveToPhotoAlbum) { if (this.saveToPhotoAlbum) {
exifPath = FileHelper.getRealPath(uri, this.cordova); exifPath = dataResource.getRealFile().getPath();
} else { } else {
exifPath = uri.getPath(); exifPath = uri.getPath();
} }
@ -398,8 +401,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
this.callbackContext.success(uri.toString()); this.callbackContext.success(uri.toString());
} else { } else {
String uriString = uri.toString(); String uriString = uri.toString();
DataResource dataResource = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent");
// Get the path to the image. Makes loading so much easier. // Get the path to the image. Makes loading so much easier.
String mimeType = FileHelper.getMimeType(uriString, this.cordova); String mimeType = dataResource.getMimeType();
// If we don't have a valid image so quit. // If we don't have a valid image so quit.
if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) { if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {
Log.d(LOG_TAG, "I either have a null image path or bitmap"); Log.d(LOG_TAG, "I either have a null image path or bitmap");
@ -440,7 +444,8 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// Create an ExifHelper to save the exif data that is lost during compression // Create an ExifHelper to save the exif data that is lost during compression
String resizePath = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg"; String resizePath = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
// Some content: URIs do not map to file paths (e.g. picasa). // Some content: URIs do not map to file paths (e.g. picasa).
String realPath = FileHelper.getRealPath(uri, this.cordova); File realFile = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.CameraExitIntent").getRealFile();
String realPath = realFile != null? realFile.getPath() : null;
ExifHelper exif = new ExifHelper(); ExifHelper exif = new ExifHelper();
if (realPath != null && this.encodingType == JPEG) { if (realPath != null && this.encodingType == JPEG) {
try { try {
@ -534,8 +539,15 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
*/ */
private void writeUncompressedImage(Uri uri) throws FileNotFoundException, private void writeUncompressedImage(Uri uri) throws FileNotFoundException,
IOException { IOException {
FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(imageUri.toString())); DataResource inputDataResource = DataResource.initiateNewDataRequestForUri(imageUri, webView.pluginManager, cordova, "CameraLauncher.writeUncompressedImage");
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); InputStream fis = inputDataResource.getIs();
DataResource outDataResource = DataResource.initiateNewDataRequestForUri(uri, webView.pluginManager, cordova, "CameraLauncher.writeUncompressedImage");
OutputStream os = outDataResource.getOs();
if(fis == null) {
throw new FileNotFoundException("Could not get the input file");
} else if(os == null) {
throw new FileNotFoundException("Could not get the output file");
}
byte[] buffer = new byte[4096]; byte[] buffer = new byte[4096];
int len; int len;
while ((len = fis.read(buffer)) != -1) { while ((len = fis.read(buffer)) != -1) {
@ -578,14 +590,15 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
*/ */
private Bitmap getScaledBitmap(String imageUrl) throws IOException { private Bitmap getScaledBitmap(String imageUrl) throws IOException {
// If no new width or height were specified return the original bitmap // If no new width or height were specified return the original bitmap
DataResource dataResource = DataResource.initiateNewDataRequestForUri(imageUrl, webView.pluginManager, cordova, "CameraLauncher.getScaledBitmap");
if (this.targetWidth <= 0 && this.targetHeight <= 0) { if (this.targetWidth <= 0 && this.targetHeight <= 0) {
return BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova)); return BitmapFactory.decodeStream(dataResource.getIs());
} }
// figure out the original width and height of the image // figure out the original width and height of the image
BitmapFactory.Options options = new BitmapFactory.Options(); BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options); BitmapFactory.decodeStream(dataResource.getIs(), null, options);
//CB-2292: WTF? Why is the width null? //CB-2292: WTF? Why is the width null?
if(options.outWidth == 0 || options.outHeight == 0) if(options.outWidth == 0 || options.outHeight == 0)
@ -599,7 +612,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// Load in the smallest bitmap possible that is closest to the size we want // Load in the smallest bitmap possible that is closest to the size we want
options.inJustDecodeBounds = false; options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight); options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options); Bitmap unscaledBitmap = BitmapFactory.decodeStream(dataResource.getIs(), null, options);
if (unscaledBitmap == null) { if (unscaledBitmap == null) {
return null; return null;
} }
@ -698,16 +711,20 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
bitmap.recycle(); bitmap.recycle();
} }
// Clean up initial camera-written image file. DataResource dataResource = DataResource.initiateNewDataRequestForUri(oldImage, webView.pluginManager, cordova, "CameraLauncher.cleanup");
(new File(FileHelper.stripFileProtocol(oldImage.toString()))).delete(); File file = dataResource.getRealFile();
if(file != null) {
// Clean up initial camera-written image file.
file.delete();
checkForDuplicateImage(imageType); checkForDuplicateImage(imageType);
// Scan for the gallery to update pic refs in gallery // Scan for the gallery to update pic refs in gallery
if (this.saveToPhotoAlbum && newImage != null) { if (this.saveToPhotoAlbum && newImage != null) {
this.scanForGallery(newImage); this.scanForGallery(newImage);
}
System.gc();
} }
System.gc();
} }
/** /**

View File

@ -26,6 +26,7 @@ import java.io.OutputStream;
import android.os.Build; import android.os.Build;
import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.DataResource;
import org.apache.cordova.api.LOG; import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.json.JSONArray; import org.json.JSONArray;
@ -129,7 +130,8 @@ public class Capture extends CordovaPlugin {
// If the mimeType isn't set the rest will fail // If the mimeType isn't set the rest will fail
// so let's see if we can determine it. // so let's see if we can determine it.
if (mimeType == null || mimeType.equals("") || "null".equals(mimeType)) { if (mimeType == null || mimeType.equals("") || "null".equals(mimeType)) {
mimeType = FileHelper.getMimeType(filePath, cordova); DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "Capture.dataResource");
mimeType = dataResource.getMimeType();
} }
Log.d(LOG_TAG, "Mime type = " + mimeType); Log.d(LOG_TAG, "Mime type = " + mimeType);
@ -156,7 +158,8 @@ public class Capture extends CordovaPlugin {
private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException { private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException {
BitmapFactory.Options options = new BitmapFactory.Options(); BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(FileHelper.stripFileProtocol(filePath), options); DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "Capture.getImageData");
BitmapFactory.decodeFile(dataResource.getRealFile().getPath(), options);
obj.put("height", options.outHeight); obj.put("height", options.outHeight);
obj.put("width", options.outWidth); obj.put("width", options.outWidth);
return obj; return obj;
@ -348,7 +351,8 @@ public class Capture extends CordovaPlugin {
* @throws IOException * @throws IOException
*/ */
private JSONObject createMediaFile(Uri data) { private JSONObject createMediaFile(Uri data) {
File fp = new File(FileHelper.getRealPath(data, this.cordova)); DataResource dataResource = DataResource.initiateNewDataRequestForUri(data, webView.pluginManager, cordova, "Capture.createMediaFile");
File fp = dataResource.getRealFile();
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
try { try {
@ -358,6 +362,7 @@ public class Capture extends CordovaPlugin {
// Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
// are reported as video/3gpp. I'm doing this hacky check of the URI to see if it // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
// is stored in the audio or video content store. // is stored in the audio or video content store.
if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) { if (fp.getAbsoluteFile().toString().endsWith(".3gp") || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
if (data.toString().contains("/audio/")) { if (data.toString().contains("/audio/")) {
obj.put("type", AUDIO_3GPP); obj.put("type", AUDIO_3GPP);
@ -365,7 +370,7 @@ public class Capture extends CordovaPlugin {
obj.put("type", VIDEO_3GPP); obj.put("type", VIDEO_3GPP);
} }
} else { } else {
obj.put("type", FileHelper.getMimeType(fp.getAbsolutePath(), cordova)); obj.put("type", dataResource.getMimeType());
} }
obj.put("lastModifiedDate", fp.lastModified()); obj.put("lastModifiedDate", fp.lastModified());

View File

@ -18,8 +18,6 @@
*/ */
package org.apache.cordova; package org.apache.cordova;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment; import android.os.Environment;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.util.Log; import android.util.Log;
@ -27,6 +25,7 @@ import android.util.Log;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.CallbackContext; import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin; import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.DataResource;
import org.apache.cordova.api.PluginResult; import org.apache.cordova.api.PluginResult;
import org.apache.cordova.file.EncodingException; import org.apache.cordova.file.EncodingException;
import org.apache.cordova.file.FileExistsException; import org.apache.cordova.file.FileExistsException;
@ -46,8 +45,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
/** /**
@ -234,7 +231,7 @@ public class FileUtils extends CordovaPlugin {
* @param filePath the path to check * @param filePath the path to check
*/ */
private void notifyDelete(String filePath) { private void notifyDelete(String filePath) {
String newFilePath = FileHelper.getRealPath(filePath, cordova); String newFilePath = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.notifyDelete").getRealFile().getPath();
try { try {
this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?", MediaStore.Images.Media.DATA + " = ?",
@ -256,37 +253,10 @@ public class FileUtils extends CordovaPlugin {
* @throws IOException if the user can't read the file * @throws IOException if the user can't read the file
* @throws JSONException * @throws JSONException
*/ */
@SuppressWarnings("deprecation")
private JSONObject resolveLocalFileSystemURI(String url) throws IOException, JSONException { private JSONObject resolveLocalFileSystemURI(String url) throws IOException, JSONException {
String decoded = URLDecoder.decode(url, "UTF-8"); File fp = DataResource.initiateNewDataRequestForUri(url, webView.pluginManager, cordova, "FileUtils.resolveLocalFileSystemURI").getRealFile();
File fp = null; if (fp == null || !fp.exists()) {
// Handle the special case where you get an Android content:// uri.
if (decoded.startsWith("content:")) {
Cursor cursor = this.cordova.getActivity().managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
// Note: MediaStore.Images/Audio/Video.Media.DATA is always "_data"
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
fp = new File(cursor.getString(column_index));
} else {
// Test to see if this is a valid URL first
@SuppressWarnings("unused")
URL testUrl = new URL(decoded);
if (decoded.startsWith("file://")) {
int questionMark = decoded.indexOf("?");
if (questionMark < 0) {
fp = new File(decoded.substring(7, decoded.length()));
} else {
fp = new File(decoded.substring(7, questionMark));
}
} else {
fp = new File(decoded);
}
}
if (!fp.exists()) {
throw new FileNotFoundException(); throw new FileNotFoundException();
} }
if (!fp.canRead()) { if (!fp.canRead()) {
@ -304,9 +274,9 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException * @throws JSONException
*/ */
private JSONArray readEntries(String fileName) throws FileNotFoundException, JSONException { private JSONArray readEntries(String fileName) throws FileNotFoundException, JSONException {
File fp = createFileObject(fileName); File fp = DataResource.initiateNewDataRequestForUri(fileName, webView.pluginManager, cordova, "FileUtils.readEntries").getRealFile();
if (!fp.exists()) { if (fp == null || !fp.exists()) {
// The directory we are listing doesn't exist so we should fail. // The directory we are listing doesn't exist so we should fail.
throw new FileNotFoundException(); throw new FileNotFoundException();
} }
@ -341,8 +311,10 @@ public class FileUtils extends CordovaPlugin {
* @throws FileExistsException * @throws FileExistsException
*/ */
private JSONObject transferTo(String fileName, String newParent, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException { private JSONObject transferTo(String fileName, String newParent, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
String newFileName = FileHelper.getRealPath(fileName, cordova); DataResource dataResourceFrom = DataResource.initiateNewDataRequestForUri(fileName, webView.pluginManager, cordova, "FileUtils.transferTo");
newParent = FileHelper.getRealPath(newParent, cordova); String newFileName = dataResourceFrom.getRealFile().getPath();
DataResource dataResourceTo = DataResource.initiateNewDataRequestForUri(newParent, webView.pluginManager, cordova, "FileUtils.transferTo");
newParent = dataResourceTo.getRealFile().getPath();
// Check for invalid file name // Check for invalid file name
if (newName != null && newName.contains(":")) { if (newName != null && newName.contains(":")) {
@ -613,7 +585,7 @@ public class FileUtils extends CordovaPlugin {
* @throws FileExistsException * @throws FileExistsException
*/ */
private boolean removeRecursively(String filePath) throws FileExistsException { private boolean removeRecursively(String filePath) throws FileExistsException {
File fp = createFileObject(filePath); File fp = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.readEntries").getRealFile();
// You can't delete the root directory. // You can't delete the root directory.
if (atRootDirectory(filePath)) { if (atRootDirectory(filePath)) {
@ -654,7 +626,7 @@ public class FileUtils extends CordovaPlugin {
* @throws InvalidModificationException * @throws InvalidModificationException
*/ */
private boolean remove(String filePath) throws NoModificationAllowedException, InvalidModificationException { private boolean remove(String filePath) throws NoModificationAllowedException, InvalidModificationException {
File fp = createFileObject(filePath); File fp = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.readEntries").getRealFile();
// You can't delete the root directory. // You can't delete the root directory.
if (atRootDirectory(filePath)) { if (atRootDirectory(filePath)) {
@ -698,7 +670,8 @@ public class FileUtils extends CordovaPlugin {
throw new EncodingException("This file has a : in it's name"); throw new EncodingException("This file has a : in it's name");
} }
File fp = createFileObject(dirPath, fileName); String filePath = getFullFilePath(dirPath, fileName);
File fp = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getFile").getRealFile();
if (create) { if (create) {
if (exclusive && fp.exists()) { if (exclusive && fp.exists()) {
@ -740,15 +713,14 @@ public class FileUtils extends CordovaPlugin {
* @param fileName new file name * @param fileName new file name
* @return * @return
*/ */
private File createFileObject(String dirPath, String fileName) { private String getFullFilePath(String dirPath, String fileName) {
File fp = null;
if (fileName.startsWith("/")) { if (fileName.startsWith("/")) {
fp = new File(fileName); return fileName;
} else { } else {
dirPath = FileHelper.getRealPath(dirPath, cordova); DataResource dataResource = DataResource.initiateNewDataRequestForUri(dirPath, webView.pluginManager, cordova, "FileUtils.getFullFilePath");
fp = new File(dirPath + File.separator + fileName); dirPath = dataResource.getRealFile().getPath();
return dirPath + File.separator + fileName;
} }
return fp;
} }
/** /**
@ -760,12 +732,13 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException * @throws JSONException
*/ */
private JSONObject getParent(String filePath) throws JSONException { private JSONObject getParent(String filePath) throws JSONException {
filePath = FileHelper.getRealPath(filePath, cordova); DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getParent");
filePath = dataResource.getRealFile().getPath();
if (atRootDirectory(filePath)) { if (atRootDirectory(filePath)) {
return getEntry(filePath); return getEntry(filePath);
} }
return getEntry(new File(filePath).getParent()); return getEntry(dataResource.getRealFile().getParent());
} }
/** /**
@ -776,7 +749,7 @@ public class FileUtils extends CordovaPlugin {
* @return true if we are at the root, false otherwise. * @return true if we are at the root, false otherwise.
*/ */
private boolean atRootDirectory(String filePath) { private boolean atRootDirectory(String filePath) {
filePath = FileHelper.getRealPath(filePath, cordova); filePath = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.atRootDirectory").getRealFile().getPath();
if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + cordova.getActivity().getPackageName() + "/cache") || if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + cordova.getActivity().getPackageName() + "/cache") ||
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) || filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
@ -786,19 +759,6 @@ public class FileUtils extends CordovaPlugin {
return false; return false;
} }
/**
* Create a File object from the passed in path
*
* @param filePath
* @return
*/
private File createFileObject(String filePath) {
filePath = FileHelper.getRealPath(filePath, cordova);
File file = new File(filePath);
return file;
}
/** /**
* Look up metadata about this entry. * Look up metadata about this entry.
* *
@ -807,9 +767,9 @@ public class FileUtils extends CordovaPlugin {
* @throws FileNotFoundException * @throws FileNotFoundException
*/ */
private long getMetadata(String filePath) throws FileNotFoundException { private long getMetadata(String filePath) throws FileNotFoundException {
File file = createFileObject(filePath); File file = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getMetadata").getRealFile();
if (!file.exists()) { if (file == null || !file.exists()) {
throw new FileNotFoundException("Failed to find file in getMetadata"); throw new FileNotFoundException("Failed to find file in getMetadata");
} }
@ -825,15 +785,16 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException * @throws JSONException
*/ */
private JSONObject getFileMetadata(String filePath) throws FileNotFoundException, JSONException { private JSONObject getFileMetadata(String filePath) throws FileNotFoundException, JSONException {
File file = createFileObject(filePath); DataResource dataResource = DataResource.initiateNewDataRequestForUri(filePath, webView.pluginManager, cordova, "FileUtils.getMetadata");
File file = dataResource.getRealFile();
if (!file.exists()) { if (file == null || !file.exists()) {
throw new FileNotFoundException("File: " + filePath + " does not exist."); throw new FileNotFoundException("File: " + filePath + " does not exist.");
} }
JSONObject metadata = new JSONObject(); JSONObject metadata = new JSONObject();
metadata.put("size", file.length()); metadata.put("size", file.length());
metadata.put("type", FileHelper.getMimeType(filePath, cordova)); metadata.put("type", dataResource.getMimeType());
metadata.put("name", file.getName()); metadata.put("name", file.getName());
metadata.put("fullPath", filePath); metadata.put("fullPath", filePath);
metadata.put("lastModifiedDate", file.lastModified()); metadata.put("lastModifiedDate", file.lastModified());
@ -935,7 +896,8 @@ public class FileUtils extends CordovaPlugin {
this.cordova.getThreadPool().execute(new Runnable() { this.cordova.getThreadPool().execute(new Runnable() {
public void run() { public void run() {
try { try {
byte[] bytes = readAsBinaryHelper(filename, start, end); DataResource dataResource = DataResource.initiateNewDataRequestForUri(filename, webView.pluginManager, cordova, "FileUtils.readFileAs");
byte[] bytes = readAsBinaryHelper(dataResource.getIs(), start, end);
PluginResult result; PluginResult result;
switch (resultType) { switch (resultType) {
@ -949,7 +911,7 @@ public class FileUtils extends CordovaPlugin {
result = new PluginResult(PluginResult.Status.OK, bytes, true); result = new PluginResult(PluginResult.Status.OK, bytes, true);
break; break;
default: // Base64. default: // Base64.
String contentType = FileHelper.getMimeType(filename, cordova); String contentType = dataResource.getMimeType();
byte[] base64 = Base64.encodeBase64(bytes); byte[] base64 = Base64.encodeBase64(bytes);
String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII"); String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
result = new PluginResult(PluginResult.Status.OK, s); result = new PluginResult(PluginResult.Status.OK, s);
@ -976,10 +938,9 @@ public class FileUtils extends CordovaPlugin {
* @return Contents of the file as a byte[]. * @return Contents of the file as a byte[].
* @throws IOException * @throws IOException
*/ */
private byte[] readAsBinaryHelper(String filename, int start, int end) throws IOException { private byte[] readAsBinaryHelper(InputStream inputStream, int start, int end) throws IOException {
int numBytesToRead = end - start; int numBytesToRead = end - start;
byte[] bytes = new byte[numBytesToRead]; byte[] bytes = new byte[numBytesToRead];
InputStream inputStream = FileHelper.getInputStreamFromUriString(filename, cordova);
int numBytesRead = 0; int numBytesRead = 0;
if (start > 0) { if (start > 0) {
@ -1008,7 +969,8 @@ public class FileUtils extends CordovaPlugin {
throw new NoModificationAllowedException("Couldn't write to file given its content URI"); throw new NoModificationAllowedException("Couldn't write to file given its content URI");
} }
filename = FileHelper.getRealPath(filename, cordova); DataResource dataResource = DataResource.initiateNewDataRequestForUri(filename, webView.pluginManager, cordova, "FileUtils.write");
filename = dataResource.getRealFile().getPath();
boolean append = false; boolean append = false;
if (offset > 0) { if (offset > 0) {
@ -1037,13 +999,16 @@ public class FileUtils extends CordovaPlugin {
* @throws NoModificationAllowedException * @throws NoModificationAllowedException
*/ */
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException, NoModificationAllowedException { private long truncateFile(String filename, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
if (filename.startsWith("content://")) { DataResource dataResource = DataResource.initiateNewDataRequestForUri(filename, webView.pluginManager, cordova, "FileUtils.truncateFile");
throw new NoModificationAllowedException("Couldn't truncate file given its content URI"); if(!dataResource.isWritable()) {
throw new NoModificationAllowedException("Couldn't truncate file as it is not writable");
}
File file = dataResource.getRealFile();
if(file == null) {
throw new FileNotFoundException("Couldn't get the file");
} }
filename = FileHelper.getRealPath(filename, cordova); RandomAccessFile raf = new RandomAccessFile(file, "rw");
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
try { try {
if (raf.length() >= size) { if (raf.length() >= size) {
FileChannel channel = raf.getChannel(); FileChannel channel = raf.getChannel();

View File

@ -49,6 +49,7 @@ public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
new DataResourceContext("WebViewClient.shouldInterceptRequest", true /* this is from a browser request*/)); new DataResourceContext("WebViewClient.shouldInterceptRequest", true /* this is from a browser request*/));
url = dataResource.getUri().toString(); url = dataResource.getUri().toString();
// This mechanism is no longer needed due to the dataResource mechanism. It would be awesome to just get rid of it.
//Check if plugins intercept the request //Check if plugins intercept the request
WebResourceResponse ret = super.shouldInterceptRequest(view, url); WebResourceResponse ret = super.shouldInterceptRequest(view, url);
// The below bugfix is taken care of by the dataResource mechanism // The below bugfix is taken care of by the dataResource mechanism