From 70f743604f85ea9f144c4b83830fdbe2f1051ed3 Mon Sep 17 00:00:00 2001 From: jrouault Date: Mon, 20 Feb 2017 18:35:59 +0900 Subject: [PATCH] Remove check for assets in bundle (#20) Remove check for assets in bundle --- README.md | 3 +- .../www/phonegap/plugin/wizAssets/assets.db | Bin 4096 -> 0 bytes .../plugin/WizAssets/WizAssetManager.java | 237 ------------------ .../plugin/WizAssets/WizAssetsPlugin.java | 117 +++++---- .../Plugins/WizAssetsPlugin/WizAssetsPlugin.h | 3 +- .../Plugins/WizAssetsPlugin/WizAssetsPlugin.m | 57 +---- plugin.xml | 4 - .../plugin/wizAssets/WizAssetsError.js | 5 +- www/phonegap/plugin/wizAssets/assets.db | Bin 4096 -> 0 bytes 9 files changed, 89 insertions(+), 337 deletions(-) delete mode 100644 platforms/android/assets/www/phonegap/plugin/wizAssets/assets.db delete mode 100755 platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetManager.java delete mode 100644 www/phonegap/plugin/wizAssets/assets.db diff --git a/README.md b/README.md index d39883a..854f1b7 100644 --- a/README.md +++ b/README.md @@ -134,4 +134,5 @@ function fail(error) { | 7 | `FILE_CREATION_ERROR` | Saving the asset failed | | 8 | `JSON_CREATION_ERROR` | Your call to WizAssets' method failed and its error could not be processed internally | | 9 | `INITIALIZATION_ERROR` | WizAssets initialization failed | -| 10 | `UNREFERENCED_ERROR` | Unknown error: message string (error.message) will contains more information | +| 10 | `NOT_FOUND_ERROR` | Asset could not be found | +| 11 | `UNREFERENCED_ERROR` | Unknown error: message string (error.message) will contain more information | diff --git a/platforms/android/assets/www/phonegap/plugin/wizAssets/assets.db b/platforms/android/assets/www/phonegap/plugin/wizAssets/assets.db deleted file mode 100644 index 71c40e01703d21e400d13c9ea71d61387099e64b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHGK~4fO6n&kUglK{bm#zv42_)>ifTJO1A}FFHx*%rM5{V+hj0>0J!kf7D3|z#! z_*xiY5}Cx6CbX0Ow*SAj|GnQiJ8cePCHtevFpT9cJP3h3DFJM<>*lcw_Ko?RgJ}-L z+k3jm8;foajx&Wbbw_TLhx`vQwC*|fnQ)9d6Q}y0hR|?9C`80h5fc%)nCB2GXMklM{gq-#iaoI)uG zL{eFhi!i1L1CmpeUDF&>E`>+dP;s3Xbyrt3e`A%$hZypL`uxh8e$Crj`Q#-{F4^)5 z#?wtbDkJN1Eu7V<{8WqIJ&IJnqE1r(;kH=?tO9GNfc^j1uH=@mRlq7>6|f3e1@Hyw C " + returnObject.toString()); - - } catch (SQLiteException e3) { - // ignore - Log.e(TAG, "error -- " + e3.getMessage(), e3); - // on exception we send back an empty object - } - return returnObject; - } - - private void buildDB() { - // Init DB from bundle assets out to storage - Log.d(TAG, "Init DB"); - - // Open the .db file from assets directory - try { - InputStream is = that.getAssets().open(DATABASE_INTERNAL_FILE_PATH + DATABASE_NAME); - - // Copy the database into the destination - OutputStream os = new FileOutputStream(DATABASE_EXTERNAL_FILE_PATH + DATABASE_NAME); - - byte[] buffer = new byte[1024]; - int length; - while ((length = is.read(buffer)) > 0){ - os.write(buffer, 0, length); - } - os.flush(); - - os.close(); - is.close(); - - database = SQLiteDatabase.openDatabase(DATABASE_EXTERNAL_FILE_PATH + DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE); - Log.d(TAG, "Init DB Finish"); - - } catch (IOException e1) { - // log, ignore and send back nothing - Log.e(TAG, "IO error -- " + e1.getMessage(), e1); - } - - } - - public void downloadedAsset(String relativePath, String absolutePath) { - // Downloaded file, add / edit database - try { - // Will replace if exists - String sqlInsert = "insert or replace into " + DATABASE_TABLE_NAME + " values(?,?)"; - database.execSQL(sqlInsert, new Object[] { relativePath, absolutePath }); - } catch (Exception e) { - Log.e(TAG, "error -- " + e.getMessage(), e); - } - } - - public String getFile(String relpath) { - // returns file path to asset from database - Cursor cursor = null; - try { - // Will replace if exists - String sqlSearch = "select filePath from " + DATABASE_TABLE_NAME + " where uri= ?"; - cursor = database.rawQuery(sqlSearch, new String[] { relpath }); - } catch (Exception e) { - Log.e(TAG, "error -- " + e.getMessage(), e); - return ""; - } - - String result; - try { - if (cursor.moveToFirst()) { - result = cursor.getString(0); - } else { - // Cursor move error - result = "NotFoundError"; - } - } catch (CursorIndexOutOfBoundsException e) { - Log.e(TAG, "cursor not found error: " + e ); - result = "NotFoundError"; - } catch (Exception ex) { - Log.e(TAG, "cursor error: " + ex ); - result = "NotFoundError"; - } finally { - cursor.close(); - } - - return result; - } - - public void deleteFile(String filePath) { - try { - // Delete file - database.delete(DATABASE_TABLE_NAME, "filePath= ?", new String[] { filePath }); - } catch (Exception e) { - Log.e(TAG, "Delete file error -- " + e.getMessage(), e); - } - } - - public void deleteFolder(String filePath) { - try { - String pathPattern; - if (filePath.charAt(filePath.length() - 1) != File.separatorChar) { - pathPattern = filePath + File.separatorChar + '%'; - } else { - pathPattern = filePath.concat("%"); - } - // Delete all entries starting with the file path - database.delete(DATABASE_TABLE_NAME, "filePath like ?", new String[] { pathPattern }); - } catch (Exception e) { - Log.e(TAG, "Delete file error -- " + e.getMessage(), e); - } - } - - // If we detect a data structure created by plugin version <= 5.0.0 we want to clean up - private void checkForMigration() { - String deprecatedDbLocation = that.getCacheDir().getAbsolutePath() + File.separator + V5_0_0_DATABASE_NAME; - File deprecatedDbFile = new File(deprecatedDbLocation); - if (!deprecatedDbFile.exists()) { - return; - } - - Log.d(TAG, "Found a deprecated database: removing cached files and database"); - SQLiteDatabase deprecatedDb = SQLiteDatabase.openDatabase(deprecatedDbLocation, null, SQLiteDatabase.OPEN_READONLY); - int counter = 0; - try { - Cursor cursor = deprecatedDb.rawQuery("select * from " + V5_0_0_DATABASE_TABLE_NAME, null); - String filePath; - while (cursor.moveToNext()) { - filePath = cursor.getString(cursor.getColumnIndex("filePath")); - if (WizAssetsPlugin.deleteFile(new File(filePath))) { - counter++; - } - } - cursor.close(); - deprecatedDb.close(); - } catch (SQLiteException e3) { - Log.e(TAG, "error -- " + e3.getMessage(), e3); - } - Log.d(TAG, "removed " + counter + " cached files"); - deprecatedDbFile.delete(); - } -} \ No newline at end of file diff --git a/platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetsPlugin.java b/platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetsPlugin.java index de85a6c..7859dd0 100755 --- a/platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetsPlugin.java +++ b/platforms/android/src/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetsPlugin.java @@ -49,7 +49,6 @@ public class WizAssetsPlugin extends CordovaPlugin { private String TAG = "WizAssetsPlugin"; - private WizAssetManager wizAssetManager = null; private boolean initialized = false; public static final String PLUGIN_FOLDER = "wizAssets"; @@ -72,9 +71,11 @@ public class WizAssetsPlugin extends CordovaPlugin { private static final int FILE_CREATION_ERROR = 7; private static final int JSON_CREATION_ERROR = 8; private static final int INITIALIZATION_ERROR = 9; - private static final int UNREFERENCED_ERROR = 10; + private static final int NOT_FOUND_ERROR = 10; + private static final int UNREFERENCED_ERROR = 11; + + private static final String DEPRECATED_DATABASE_NAME = "assets.db"; - private String pathToDatabase; private String pathToAssets; private int blockSize; @@ -84,25 +85,40 @@ public void initialize(CordovaInterface cordova, CordovaWebView webView) { final Context applicationContext = cordova.getActivity().getApplicationContext(); - pathToDatabase = applicationContext.getCacheDir().getAbsolutePath() + File.separator + PLUGIN_FOLDER; - pathToAssets = pathToDatabase + File.separator + ASSETS_FOLDER; + String pathToCache = applicationContext.getCacheDir().getAbsolutePath() + File.separator; + + String pathToPlugin = pathToCache + PLUGIN_FOLDER; + pathToAssets = pathToPlugin + File.separator + ASSETS_FOLDER; - if (!createFolderIfRequired(pathToDatabase)) { - Log.e(TAG, "error -- unable to create folder: " + pathToDatabase); + if (!createFolderIfRequired(pathToPlugin)) { + Log.e(TAG, "error -- unable to create plugin folder: " + pathToPlugin); return; } else if (!createFolderIfRequired(pathToAssets)) { - Log.e(TAG, "error -- unable to create folder: " + pathToAssets); + Log.e(TAG, "error -- unable to create assets folder: " + pathToAssets); return; } - pathToDatabase += File.separator; pathToAssets += File.separator; setBlockSize(); - wizAssetManager = new WizAssetManager(applicationContext, pathToDatabase); + removeDeprecatedDatabases(pathToCache); - initialized = wizAssetManager.isReady(); + initialized = true; + } + + public void removeDeprecatedDatabases(String pathToCache) { + // Removing database version 6.x.x + String deprecatedDatabasePath = pathToCache + PLUGIN_FOLDER + File.separator + DEPRECATED_DATABASE_NAME; + if (!deleteIfExists(deprecatedDatabasePath)) { + Log.e(TAG, "Unable to delete deprecated database version 6.x.x at path: " + deprecatedDatabasePath); + } + + // Removing database version <= 5.x.x + deprecatedDatabasePath = pathToCache + DEPRECATED_DATABASE_NAME; + if (!deleteIfExists(deprecatedDatabasePath)) { + Log.e(TAG, "Unable to delete deprecated database version <= 5.x.x at path: " + deprecatedDatabasePath); + } } @SuppressWarnings("deprecation") @@ -139,13 +155,12 @@ public boolean execute(String action, JSONArray args, CallbackContext callbackCo final CallbackContext _callbackContext = callbackContext; cordova.getThreadPool().execute(new Runnable() { public void run() { - String filePathInDB = getAssetFilePathFromUri(uri); String filePath = buildAssetFilePathFromUri(uri); File file = new File(filePath); - if (filePathInDB != null && file.exists()) { + if (file.exists()) { // File is already in cache folder, don't download it Log.d(TAG, "[Is in cache] " + uri); - String result = "file://" + file.getAbsolutePath(); + String result = buildLocalFileUrl(file.getAbsolutePath()); _callbackContext.success(result); } else { // File is not in cache folder, download it @@ -159,28 +174,28 @@ public void run() { return true; } else if (action.equals(GET_FILE_URI_ACTION)) { Log.d(TAG, "[getFileURI] search full file path for: "+ args.toString() ); - String asset = null; - try { - String relativePath = args.getString(0); - asset = getAssetFilePathFromUri(relativePath); - } catch (JSONException e) { - Log.d(TAG, "[getFileURI] error: " + e.toString()); - callbackContext.error(e.toString()); - } - - if (asset == null) { - callbackContext.error("NotFoundError"); - } else { + String uri = args.getString(0); + String filePath = buildAssetFilePathFromUri(uri); + File file = new File(filePath); + if (file.exists()) { + String asset = buildLocalFileUrl(filePath); Log.d(TAG, "[getFileURI] Returning full path: " + asset); callbackContext.success(asset); + } else { + callbackContext.error(NOT_FOUND_ERROR); } return true; } else if (action.equals(GET_FILE_URIS_ACTION)) { // Return all assets as asset map object Log.d(TAG, "[getFileURIs] returning all assets as map"); - JSONObject assetObject = wizAssetManager.getAllAssets(); - callbackContext.success(assetObject); + try { + JSONObject assetObject = getAllAssets(); + callbackContext.success(assetObject); + } catch (JSONException e) { + Log.d(TAG, "[getFileURIs] error: " + e.toString()); + callbackContext.error(JSON_CREATION_ERROR); + } return true; } else if (action.equals(DELETE_FILES_ACTION)) { // Delete all files from given array @@ -206,13 +221,28 @@ public void run() { return false; // Returning false results in a "MethodNotFound" error. } - private String getAssetFilePathFromUri(String file) { - String asset = wizAssetManager.getFile(file); - if (asset == null || asset == "" || asset.contains("NotFoundError")) { - return null; + private JSONObject getAllAssets() throws JSONException { + JSONObject assets = new JSONObject(); + File assetsRoot = new File(pathToAssets); + getAllAssets(assetsRoot, assets); + return assets; + } + + private void getAllAssets(File file, JSONObject assets) throws JSONException { + if (file.isDirectory()) { + String files[] = file.list(); + for (String filename : files) { + File subFile = new File(file, filename); + getAllAssets(subFile, assets); + } + } else { + String filePath = file.getAbsolutePath(); + assets.put(buildUriFromAssetFilePath(filePath), buildLocalFileUrl(filePath)); } + } - return asset; + private String buildUriFromAssetFilePath(String filePath) { + return filePath.substring(pathToAssets.length()); } private String buildAssetFilePathFromUri(String uri) { @@ -222,6 +252,10 @@ private String buildAssetFilePathFromUri(String uri) { return pathToAssets + uri; } + private String buildLocalFileUrl(String filePath) { + return "file://" + filePath; + } + private void deleteFiles(JSONArray uris, CallbackContext callbackContext) { DeleteAssetsCallback callback = new DeleteAssetsCallback(callbackContext); AsyncDelete asyncDelete = new AsyncDelete(callback); @@ -232,17 +266,10 @@ 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); if (!deleteSucceed) { throw new IOException(filePath + " could not be deleted."); } - // Delete from database - if (isDirectory) { - wizAssetManager.deleteFolder(filePath); - } else { - wizAssetManager.deleteFile(filePath); - } } } @@ -281,6 +308,11 @@ private boolean createFolderIfRequired(String folderPath) { return folder.mkdir(); } + private boolean deleteIfExists(String path) { + File file = new File(path); + return !file.exists() || file.delete(); + } + public class DeleteAssetsCallback { private CallbackContext callbackContext; @@ -503,9 +535,8 @@ protected Void doInBackground(File... params) { // Tell Asset Manager to register this download to asset database String fileAbsolutePath = file.getAbsolutePath(); Log.d(TAG, "[Downloaded ] " + fileAbsolutePath); - wizAssetManager.downloadedAsset(this.uri, fileAbsolutePath); - this.callbackContext.success("file://" + fileAbsolutePath); + this.callbackContext.success(buildLocalFileUrl(fileAbsolutePath)); } catch (JSONException e) { this.callbackContext.error(JSON_CREATION_ERROR); return null; @@ -540,4 +571,4 @@ JSONObject createDownloadFileError(int code, int status, String message) throws } return errorObject; } -} \ No newline at end of file +} diff --git a/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.h b/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.h index 9a8fccd..d0f2aae 100755 --- a/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.h +++ b/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.h @@ -22,7 +22,8 @@ enum CDVWizAssetsError { FILE_CREATION_ERROR = 7, JSON_CREATION_ERROR = 8, INITIALIZATION_ERROR = 9, - UNREFERENCED_ERROR = 10 + NOT_FOUND_ERROR = 10, + UNREFERENCED_ERROR = 11 }; typedef int CDVWizAssetsError; diff --git a/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.m b/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.m index 135dcbb..293bf35 100755 --- a/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.m +++ b/platforms/ios/HelloCordova/Plugins/WizAssetsPlugin/WizAssetsPlugin.m @@ -177,42 +177,14 @@ - (void)scanDir:(NSString *)basePath relPath:(NSString *)relPath assetMap:(NSMut */ - (void)getFileURI:(CDVInvokedUrlCommand *)command { CDVPluginResult *pluginResult; - NSString *findFile = [command.arguments objectAtIndex:0]; - NSString *returnURI = @""; - - // Example: [0]img, [1]ui, [2]bob.mp3 - NSMutableArray *fileStruct = [[NSMutableArray alloc] initWithArray:[findFile componentsSeparatedByString:@"/"]]; - - // Example: bob.mp3 - NSString *fileName = [fileStruct lastObject]; - - [fileStruct removeLastObject]; - - // Example img/ui - NSString *findFilePath = [fileStruct componentsJoinedByString:@"/"]; - - // Cut out suffix from file name, example: [0]bob, [1]mp3, - NSMutableArray *fileTypeStruct = [[NSMutableArray alloc] initWithArray:[fileName componentsSeparatedByString:@"."]]; + NSString *uri = [command.arguments objectAtIndex:0]; - if ([[NSBundle mainBundle] pathForResource:[fileTypeStruct objectAtIndex:0] - ofType:[fileTypeStruct objectAtIndex:1] - inDirectory:[@"www" stringByAppendingFormat:@"/assets/%@", findFilePath]]) { - // Check local path to bundle resources - NSString *bundlePath = [[NSBundle mainBundle] resourcePath]; - NSString *bundleSearchPath = [NSString stringWithFormat:@"%@/%@/%@/%@", bundlePath , @"www", @"assets", findFile]; + NSString *filePath = [self buildAssetFilePathFromUri:uri]; - // We have locally return same string - returnURI = bundleSearchPath; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:returnURI]; + if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES) { + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:filePath]; } else { - // Check in path to app library/caches - NSMutableDictionary *resourceMap = [NSMutableDictionary dictionary]; - - [self scanDir:self.cachePath relPath:@"" assetMap:resourceMap]; - - // Return URI to storage folder - returnURI = [resourceMap objectForKey:findFile]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:returnURI]; + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERROR]; } [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; @@ -224,24 +196,11 @@ - (void)getFileURI:(CDVInvokedUrlCommand *)command { - (void)getFileURIs:(CDVInvokedUrlCommand *)command { WizLog(@"[WizAssetsPlugin] ******* getfileURIs-> " ); - CDVPluginResult *pluginResult; - - // Path to bundle resources - NSString *bundlePath = [[NSBundle mainBundle] resourcePath]; - NSString *bundleSearchPath = [NSString stringWithFormat:@"%@/%@/%@", bundlePath , @"www", @"assets"]; - - // Scan bundle assets - NSMutableDictionary *bundleAssetMap = [NSMutableDictionary dictionary]; - [self scanDir:bundleSearchPath relPath:@"" assetMap:bundleAssetMap]; - // Scan downloaded assets - NSMutableDictionary *docAssetMap = [NSMutableDictionary dictionary]; - [self scanDir:self.cachePath relPath:@"" assetMap:docAssetMap]; - - NSMutableDictionary *assetMap = [docAssetMap mutableCopy]; - [assetMap addEntriesFromDictionary:bundleAssetMap]; + NSMutableDictionary *assetMap = [NSMutableDictionary dictionary]; + [self scanDir:self.cachePath relPath:@"" assetMap:assetMap]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:assetMap]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:assetMap]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } diff --git a/plugin.xml b/plugin.xml index 8b47357..43dafbe 100644 --- a/plugin.xml +++ b/plugin.xml @@ -51,12 +51,8 @@ - - - diff --git a/www/phonegap/plugin/wizAssets/WizAssetsError.js b/www/phonegap/plugin/wizAssets/WizAssetsError.js index a72ec2b..ed786b0 100644 --- a/www/phonegap/plugin/wizAssets/WizAssetsError.js +++ b/www/phonegap/plugin/wizAssets/WizAssetsError.js @@ -55,6 +55,7 @@ WizAssetsError.DIRECTORY_CREATION_ERROR = 6; WizAssetsError.FILE_CREATION_ERROR = 7; WizAssetsError.JSON_CREATION_ERROR = 8; WizAssetsError.INITIALIZATION_ERROR = 9; -WizAssetsError.UNREFERENCED_ERROR = 10; +WizAssetsError.NOT_FOUND_ERROR = 10; +WizAssetsError.UNREFERENCED_ERROR = 11; -module.exports = WizAssetsError; \ No newline at end of file +module.exports = WizAssetsError; diff --git a/www/phonegap/plugin/wizAssets/assets.db b/www/phonegap/plugin/wizAssets/assets.db deleted file mode 100644 index 71c40e01703d21e400d13c9ea71d61387099e64b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmeHGK~4fO6n&kUglK{bm#zv42_)>ifTJO1A}FFHx*%rM5{V+hj0>0J!kf7D3|z#! z_*xiY5}Cx6CbX0Ow*SAj|GnQiJ8cePCHtevFpT9cJP3h3DFJM<>*lcw_Ko?RgJ}-L z+k3jm8;foajx&Wbbw_TLhx`vQwC*|fnQ)9d6Q}y0hR|?9C`80h5fc%)nCB2GXMklM{gq-#iaoI)uG zL{eFhi!i1L1CmpeUDF&>E`>+dP;s3Xbyrt3e`A%$hZypL`uxh8e$Crj`Q#-{F4^)5 z#?wtbDkJN1Eu7V<{8WqIJ&IJnqE1r(;kH=?tO9GNfc^j1uH=@mRlq7>6|f3e1@Hyw C