Skip to content

Commit

Permalink
Merge pull request #11 from jrouault/fix/deleteByURI
Browse files Browse the repository at this point in the history
Delete files now specifying URI instead of file URI.
  • Loading branch information
jrouault committed Jul 13, 2015
2 parents 1f8d54c + 5ceb39b commit ac36b78
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 136 deletions.
30 changes: 15 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

# Description

PhoneGap plugin for managing application assets with javascript asset maps. Includes( iOS background threaded) downloadFile, getFileURI, getFileURIs, deleteFile.
PhoneGap plugin for managing application assets with javascript asset maps. Includes (iOS background threaded) downloadFile, getFileURI, getFileURIs, deleteFile, deleteFiles.


## Install (with Plugman)
Expand All @@ -24,41 +24,41 @@ PhoneGap plugin for managing application assets with javascript asset maps. Incl

### downloadFile()

**wizAssets.downloadFile(String URL, String filePathToBeStoredWithFilename, Function success, Function fail);**
**wizAssets.downloadFile(String remoteURL, String assetId, Function success, Function fail);**

- downloads a file to native App directory @ ./ + gameDir+ / +filePathToBeStoredWithFilename <br />
- A success returns URI string like; file://documents/settings/img/cards/card001.jpg <br />
- A success returns a local URL string like; file://documents/settings/img/cards/card001.jpg <br />
- example;

```
wizAssets.downloadFile("http://google.com/logo.jpg", "img/ui/logo.jpg", successCallback, failCallback);
```

### deleteFile()
### deleteFile()

**wizAssets.deleteFile(string URI, Function success, Function fail);**
**wizAssets.deleteFile(string assetId, Function success, Function fail);**

- deletes the file specified by the URI <br />
- if the URI does not exist fail will be called with error NotFoundError <br />
- if the URI cannot be deleted (i.e. file resides in read-only memory) fail will be called with error NotModificationAllowedError
- deletes the file specified by the asset id <br />
- if the asset id does not exist fail will be called with error NotFoundError <br />
- if the asset id cannot be deleted (i.e. file resides in read-only memory) fail will be called with error NotModificationAllowedError

```
wizAssets.deleteFile("file://documents/settings/img/cards/card001.jpg", successCallback, failCallback);
```

### deleteFiles()

**wizAssets.deleteFiles(Array manyURIs, Function success, Function fail );**
**wizAssets.deleteFiles(Array assetIds, Function success, Function fail );**

- delete all URIs in Array like; [ "file://documents/settings/img/cards/card001.jpg", "file://documents/settings/img/cards/card002.jpg " .. ] <br />
- if you do not specify a filename only dir, then all contents of dir will be deleted; file://documents/settings/img/cards <br />
- the array CAN contain one URI string
- delete files specified by their asset id in Array like; [ "img/cards/card001.jpg", "img/cards/card002.jpg " .. ] <br />
- if an asset id uses a path format and matches a folder, then the folder content will be deleted; img/cards <br />
- the array CAN contain one asset id

### getFileURI()

**wizAssets.getFileURI(String filePathWithFilename, Function success, Function fail);**
**wizAssets.getFileURI(String assetId, Function success, Function fail);**

- A success returns URI string like file://documents/settings/img/cards/card001.jpg <br />
- A success returns a local URL string like file://documents/settings/img/cards/card001.jpg <br />
- example;

```
Expand All @@ -69,7 +69,7 @@ wizAssets.getFileURI("img/ui/logo.jpg", successCallback, failCallback);

**wizAssets.getFileURIs(Function success, Function fail);**

- A success returns URI hashmap such as
- A success returns a hashmap of asset id matching its local URL such as

```
{
Expand Down
45 changes: 15 additions & 30 deletions platforms/android/assets/www/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -372,36 +372,24 @@
);
}

function deleteFile(path, download_button, delete_button, img) {
function deleteFile(uri, download_button, delete_button, img) {

// Define success callback for getting the URI.
function getFileURISuccessCallback(fileUri) {

// Define success callback for deleting the URI.
function deleteFileSuccessCallback() {
// Hide the image, enable download button, and disable delete button
hideImage(img);
document.getElementById(download_button).disabled = false;
document.getElementById(delete_button).disabled = true;
alert("Delete Success:\n" + path + "\nURI:\n" + fileUri);
}

// Define error callback for deleting the URI.
function deleteFileErrorCallback(error) {
alert("Delete Fail:\n" + error + "\nFile was probably already deleted.");
}

// Delete the URI (and invoke appropriate callback).
window.wizAssets.deleteFile(fileUri, deleteFileSuccessCallback, deleteFileErrorCallback);
// Define success callback for deleting the URI.
function deleteFileSuccessCallback() {
// Hide the image, enable download button, and disable delete button
hideImage(img);
document.getElementById(download_button).disabled = false;
document.getElementById(delete_button).disabled = true;
alert("Delete Success:\n" + uri);
}

// Define error callback for getting the URI.
function getFileURIErrorCallback(error) {
alert("Failed to get file URI error: " + error);
// Define error callback for deleting the URI.
function deleteFileErrorCallback(error) {
alert("Delete Fail:\n" + error + "\nFile was probably already deleted.");
}

// Get the URI (and invoke appropriate callback).
window.wizAssets.getFileURI(path, getFileURISuccessCallback, getFileURIErrorCallback);
// Delete the URI (and invoke appropriate callback).
window.wizAssets.deleteFile(uri, deleteFileSuccessCallback, deleteFileErrorCallback);
}

function getFileURI(path) {
Expand Down Expand Up @@ -459,11 +447,8 @@
}

// Delete the URIs (and invoke appropriate callback).
alert( "Deleting " + Object.keys(fileUriMap).length + " files" );
var files = [];
for ( var key in fileUriMap) {
files.push( fileUriMap[key] );
}
var files = Object.keys(fileUriMap);
alert("Deleting " + files.length + " files");
window.wizAssets.deleteFiles(files, deleteFilesSuccessCallback, deleteFilesErrorCallback);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,16 +127,16 @@ public void run() {

// Delete all files from given array
Log.d(TAG, "[deleteFiles] *********** ");
deleteAssets(args, false, new DeleteAssetsCallback(callbackContext));
deleteFiles(args, callbackContext);

return true;

} else if (action.equals(DELETE_FILE_ACTION)) {

Log.d(TAG, "[deleteFile] *********** " + args.getString(0));
String filePath = args.getString(0);
String uri = args.getString(0);
try {
deleteAsset(filePath, false);
deleteAsset(uri);
} catch (IOException e) {
callbackContext.error("Deleting file failed.");
return true;
Expand All @@ -163,17 +163,15 @@ private String buildAssetFilePathFromUri(String uri) {
return pathToStorage + uri;
}

private void deleteAssets(JSONArray files, boolean isUri, DeleteAssetsCallback callback) {
AsyncDelete asyncDelete = new AsyncDelete(callback, isUri);
asyncDelete.execute(files);
private void deleteFiles(JSONArray uris, CallbackContext callbackContext) {
DeleteAssetsCallback callback = new DeleteAssetsCallback(callbackContext);
AsyncDelete asyncDelete = new AsyncDelete(callback);
asyncDelete.execute(uris);
}

private void deleteAsset(String filePath, boolean isUri) throws IOException {
// If file is in bundle we cannot delete so ignore and protect whole cache folder from being deleted
if (filePath != "" && !filePath.contains("www/assets")) {
if (isUri) {
filePath = buildAssetFilePathFromUri(filePath);
}
private void deleteAsset(String uri) throws IOException {
if (uri != "") {
String filePath = buildAssetFilePathFromUri(uri);
File file = new File(filePath);
boolean isDirectory = file.isDirectory();
boolean deleteSucceed = deleteFile(file);
Expand Down Expand Up @@ -247,7 +245,6 @@ public String getErrorMessage(int errorCode) {

private class AsyncDelete extends AsyncTask<JSONArray, Integer, Integer> {
private DeleteAssetsCallback callback;
private boolean isUri;

private static final int NO_ERROR = 0;
private static final int JSON_TYPE_ERROR = -1;
Expand All @@ -263,9 +260,8 @@ private class AsyncDelete extends AsyncTask<JSONArray, Integer, Integer> {
private static final String CALLBACK_ERROR_MESSAGE = "Call to delete callback failed.";

// Constructor
public AsyncDelete(DeleteAssetsCallback callback, boolean isUri) {
public AsyncDelete(DeleteAssetsCallback callback) {
this.callback = callback;
this.isUri = isUri;
}

protected Integer doInBackground(JSONArray... jsonArrays) {
Expand All @@ -276,10 +272,10 @@ protected Integer doInBackground(JSONArray... jsonArrays) {

// We only process one array, no more than one JSON array should be passed
JSONArray jsonArray = jsonArrays[0];
int countFiles = jsonArray.length();
for (int i = 0; i < countFiles; i++) {
int countUris = jsonArray.length();
for (int i = 0; i < countUris; i++) {
try {
deleteAsset(jsonArray.getString(i), isUri);
deleteAsset(jsonArray.getString(i));
} catch (JSONException e) {
return JSON_TYPE_ERROR;
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,9 @@ - (void)getFileURIs:(CDVInvokedUrlCommand *)command {
*/
- (void)deleteFile:(CDVInvokedUrlCommand *)command {
CDVPluginResult *pluginResult;
NSString *filePath = [command.arguments objectAtIndex:0];
NSString *uri = [command.arguments objectAtIndex:0];

if ([self deleteAsset:filePath isUri:NO error:nil]) {
if ([self deleteAsset:uri error:nil]) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Deleting file failed."];
Expand All @@ -280,38 +280,21 @@ - (void)deleteFile:(CDVInvokedUrlCommand *)command {
* deleteFiles - delete all resources specified in array from app folder
*/
- (void)deleteFiles:(CDVInvokedUrlCommand *)command {
[self deleteAssets:command isUri:NO];
[self performSelectorInBackground:@selector(backgroundDelete:) withObject:command];
}

/*
* deleteAssets - delete all resources specified in array from app folder
*/
- (void)deleteAssets:(CDVInvokedUrlCommand *)command isUri:(BOOL)isUri {
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
command, @"command",
[NSNumber numberWithBool:isUri], @"isUri",
nil];
[self performSelectorInBackground:@selector(backgroundDelete:) withObject:args];
}

- (void)backgroundDelete:(NSDictionary *)args {
- (void)backgroundDelete:(CDVInvokedUrlCommand *)command {
// Create a pool
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

CDVInvokedUrlCommand *command = [args objectForKey:@"command"];
BOOL isUri = [[args objectForKey:@"isUri"] boolValue];

NSMutableArray *fileArray = [[NSMutableArray alloc] initWithArray:command.arguments copyItems:YES];
NSMutableArray *uris = [[NSMutableArray alloc] initWithArray:command.arguments copyItems:YES];

NSError *error = nil;
for (int i=0; i< [fileArray count]; i++) {
NSString *filePath = [fileArray objectAtIndex:i];
if (![self deleteAsset:filePath isUri:isUri error:nil]) {
error = [NSError errorWithDomain:assetsErrorKey code:100 userInfo:nil];
break;
}
for (int i=0; i< [uris count]; i++) {
NSString *uri = [uris objectAtIndex:i];
[self deleteAsset:uri error:&error];
}
[fileArray release];
[uris release];

NSArray *callbackData = [[NSArray alloc] initWithObjects:command.callbackId, error, nil];

Expand Down Expand Up @@ -347,26 +330,28 @@ - (void)completeDelete:(NSArray *)callbackdata {
/*
* deleteAsset - delete resource specified in string from app folder
*/
- (BOOL)deleteAsset:(NSString *)filePath isUri:(BOOL)isUri error:(NSError **)error {
NSFileManager *filemgr = [NSFileManager defaultManager];

if (filePath && [filePath length] > 0) {
// Check if the file is not in the bundle..
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
if ([filePath rangeOfString:bundlePath].location == NSNotFound) {
if (isUri) {
filePath = [self buildAssetFilePathFromUri:filePath];
}
- (BOOL)deleteAsset:(NSString *)uri error:(NSError **)error {
NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *localError = nil;
if ([filemgr fileExistsAtPath:filePath] && ![filemgr removeItemAtPath:filePath error:&localError] && error != NULL) {
*error = [NSError errorWithDomain:assetsErrorKey code:200 userInfo:nil];
return NO;
}
} else if (error != NULL) {
if (!uri || [uri length] == 0) {
if (error != nil) {
*error = [NSError errorWithDomain:assetsErrorKey code:200 userInfo:nil];
return NO;
}
return NO;
}

NSError *localError = nil;
NSString *filePath = [self buildAssetFilePathFromUri:uri];
if (![fileManager removeItemAtPath:filePath error:&localError]) {
// File didn't exist in the first place, it's not an error
if ([[localError domain] isEqualToString:NSCocoaErrorDomain] && [localError code] == NSFileNoSuchFileError) {
return YES;
}
// File deletion failed, it's an error
if (error != nil) {
*error = localError;
}
return NO;
}
return YES;
}
Expand Down
45 changes: 15 additions & 30 deletions platforms/ios/www/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -372,36 +372,24 @@
);
}

function deleteFile(path, download_button, delete_button, img) {
function deleteFile(uri, download_button, delete_button, img) {

// Define success callback for getting the URI.
function getFileURISuccessCallback(fileUri) {

// Define success callback for deleting the URI.
function deleteFileSuccessCallback() {
// Hide the image, enable download button, and disable delete button
hideImage(img);
document.getElementById(download_button).disabled = false;
document.getElementById(delete_button).disabled = true;
alert("Delete Success:\n" + path + "\nURI:\n" + fileUri);
}

// Define error callback for deleting the URI.
function deleteFileErrorCallback(error) {
alert("Delete Fail:\n" + error + "\nFile was probably already deleted.");
}

// Delete the URI (and invoke appropriate callback).
window.wizAssets.deleteFile(fileUri, deleteFileSuccessCallback, deleteFileErrorCallback);
// Define success callback for deleting the URI.
function deleteFileSuccessCallback() {
// Hide the image, enable download button, and disable delete button
hideImage(img);
document.getElementById(download_button).disabled = false;
document.getElementById(delete_button).disabled = true;
alert("Delete Success:\n" + uri);
}

// Define error callback for getting the URI.
function getFileURIErrorCallback(error) {
alert("Failed to get file URI error: " + error);
// Define error callback for deleting the URI.
function deleteFileErrorCallback(error) {
alert("Delete Fail:\n" + error + "\nFile was probably already deleted.");
}

// Get the URI (and invoke appropriate callback).
window.wizAssets.getFileURI(path, getFileURISuccessCallback, getFileURIErrorCallback);
// Delete the URI (and invoke appropriate callback).
window.wizAssets.deleteFile(uri, deleteFileSuccessCallback, deleteFileErrorCallback);
}

function getFileURI(path) {
Expand Down Expand Up @@ -459,11 +447,8 @@
}

// Delete the URIs (and invoke appropriate callback).
alert( "Deleting " + Object.keys(fileUriMap).length + " files" );
var files = [];
for ( var key in fileUriMap) {
files.push( fileUriMap[key] );
}
var files = Object.keys(fileUriMap);
alert("Deleting " + files.length + " files");
window.wizAssets.deleteFiles(files, deleteFilesSuccessCallback, deleteFilesErrorCallback);
}

Expand Down

0 comments on commit ac36b78

Please sign in to comment.