cordova-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From agri...@apache.org
Subject [10/22] git commit: Navigation to launch app and return. Added Q lib. Fixed angularJS usage. App is now a single page app.
Date Mon, 22 Apr 2013 20:14:50 GMT
Navigation to launch app and return. Added Q lib. Fixed angularJS usage. App is now a single
page app.


Project: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/commit/22d2d337
Tree: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/tree/22d2d337
Diff: http://git-wip-us.apache.org/repos/asf/cordova-app-harness/diff/22d2d337

Branch: refs/heads/master
Commit: 22d2d337ff641eff38965d54e9ab50228fb656a9
Parents: 6e1af67
Author: Shravan Narayan <shravanrn@google.com>
Authored: Thu Apr 11 16:37:50 2013 -0400
Committer: Shravan Narayan <shravanrn@google.com>
Committed: Tue Apr 16 17:28:08 2013 -0400

----------------------------------------------------------------------
 .jshintrc             |    4 +-
 README.md             |    5 +
 contextMenu.html      |   47 +
 index.html            |    6 +-
 js/AddCtrl.js         |   50 +-
 js/AppConstants.js    |   13 +-
 js/AppsService.js     |  104 +
 js/ContextMenu.js     |   38 +
 js/ListCtrl.js        |   38 +-
 js/ResourcesLoader.js |  310 ++-
 js/libs/cordova.js    | 6786 --------------------------------------------
 js/libs/q.min.js      |   19 +
 views/add.html        |    2 +-
 views/list.html       |    1 +
 14 files changed, 444 insertions(+), 6979 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/.jshintrc
----------------------------------------------------------------------
diff --git a/.jshintrc b/.jshintrc
index 46057ef..f1bc9d0 100644
--- a/.jshintrc
+++ b/.jshintrc
@@ -23,9 +23,9 @@
     "eqnull":true,
 
     //environment
-    "browser": true,
+    "browser": false,
     "devel":true,
 
     //other
-    "globals": {"angular": false }
+    "globals": {"angular": false, "Q": false }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
index 08549ee..fbf7132 100644
--- a/README.md
+++ b/README.md
@@ -2,3 +2,8 @@ cordova-app-harness
 ===================
 
 An App harness for Cordova that can download and run Cordova apps as well as Chrome packaged
apps. This enables an edit &amp; refresh workflow. Also enables local development of apps
without needing the Android / iOS SDK.
+
+#Building
+
+This app needs the following plugins:
+zip - https://github.com/MobileChromeApps/zip
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/contextMenu.html
----------------------------------------------------------------------
diff --git a/contextMenu.html b/contextMenu.html
new file mode 100644
index 0000000..27ddd0d
--- /dev/null
+++ b/contextMenu.html
@@ -0,0 +1,47 @@
+<!-- Keep stylesheet as a part of the html as this file gets injected into the app -->
+<style>
+#__cordovaappharness_contextMenu_div
+{
+    position: fixed;
+    left : 0px;
+    top : 0px;
+    z-index: 2000;
+    background-color:rgba(0,0,0,0.75);
+    width: 100%;
+    height: 100%;
+    display: none;
+}
+#__cordovaappharness_contextMenu_div p
+{
+    color: white;
+    text-align: center;
+}
+
+#__cordovaappharness_contextMenu_div ul
+{
+    list-style-type: none;
+    margin-left: 20%;
+    margin-right: 20%;
+    padding: 0;
+    width: 60%;
+}
+
+#__cordovaappharness_contextMenu_div li, #__cordovaappharness_contextMenu_div button
+{
+    width: 100%;
+}
+</style>
+<div id="__cordovaappharness_contextMenu_div">
+    <p>Tap Anywhere to Close</p>
+    <ul>
+        <li>
+            <button>Update</button>
+        </li>
+        <li>
+            <button>Restart</button>
+        </li>
+        <li>
+            <a href="file://__cordovaappharness_contextMenu_mainmenu"><button>Back
to Main Menu</button></a>
+        </li>
+    </ul>
+</div>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/index.html
----------------------------------------------------------------------
diff --git a/index.html b/index.html
index 53b53db..c897d14 100644
--- a/index.html
+++ b/index.html
@@ -2,11 +2,13 @@
 <html>
     <head>
         <title>Cordova App Harness</title>
-        <script type="text/javascript" src="js/libs/cordova.js"></script>
-        <script type="text/javascript" src="js/libs/angular-min.js"></script>
+        <script type="text/javascript" src="cordova.js"></script>
+        <script type="text/javascript" src="js/libs/q.min.js"></script>
+        <script type="text/javascript" src="js/libs/angular.min.js"></script>
         <script type="text/javascript" src="js/app.js"></script>
         <script type="text/javascript" src="js/AppConstants.js"></script>
         <script type="text/javascript" src="js/ResourcesLoader.js"></script>
+        <script type="text/javascript" src="js/AppsService.js"></script>
         <script type="text/javascript" src="js/ListCtrl.js"></script>
         <script type="text/javascript" src="js/AddCtrl.js"></script>
     </head>

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/js/AddCtrl.js
----------------------------------------------------------------------
diff --git a/js/AddCtrl.js b/js/AddCtrl.js
index 9e5a4c2..f828f54 100644
--- a/js/AddCtrl.js
+++ b/js/AddCtrl.js
@@ -1,48 +1,24 @@
 (function(){
     "use strict";
     /* global myApp */
-    myApp.controller("AddCtrl", ["$scope", "resourcesLoader", "INSTALL_DIRECTORY", "TEMP_DIRECTORY",
function ($scope, resourcesLoader, INSTALL_DIRECTORY, TEMP_DIRECTORY) {
+    myApp.controller("AddCtrl", ["$scope", "AppsService", function ($scope, AppsService)
{
 
         $scope.addApp = function(appName, appSource, appUrl) {
-            if(appSource === "url") {
-                if(appUrl) {
-                    addAppFromUrl(appName, appUrl);
-                } else {
+            if(appSource === "urlToZip") {
+                if(!appUrl) {
                     alert("Url not specified");
+                    return;
                 }
+
+                AppsService.addAppFromZipUrl(appName, appUrl)
+                .then(function() {
+                    alert("Successfully installed");
+                }, function(error) {
+                    console.error(error);
+                    alert("Unable to add application because: \n" + JSON.stringify(error));
+                });
             }
         };
-
-        function addAppFromUrl(appName, appUrl) {
-            var gotDirectoriesCallback = function(directoryNames, errorString) {
-                if(errorString) {
-                    console.error(errorString);
-                    alert("There was an error retrieving the list of installed applications.
Please try again.");
-                } else {
-                    if(directoryNames.indexOf(appName) !== -1) {
-                        alert("An app with this name already exists");
-                    } else {
-                        addNewAppFromUrl(appName, appUrl);
-                    }
-                }
-            };
-
-            resourcesLoader.getSubDirectories(INSTALL_DIRECTORY, gotDirectoriesCallback,
true);
-        }
-
-        function addNewAppFromUrl(appName, appUrl) {
-            var fileName = TEMP_DIRECTORY + appName + ".zip";
-
-            var downloadCallback = function(fullFilePath, errorString) {
-                if(errorString) {
-                    console.error(errorString);
-                    alert("There was an error downloading the app. Please try again.");
-                } else {
-                    alert("Downloaded " + fullFilePath);
-                }
-            };
-
-            resourcesLoader.downloadFromUrl(appUrl, fileName, downloadCallback);
-        }
     }]);
+
 })();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/js/AppConstants.js
----------------------------------------------------------------------
diff --git a/js/AppConstants.js b/js/AppConstants.js
index bb2e9c3..461c700 100644
--- a/js/AppConstants.js
+++ b/js/AppConstants.js
@@ -1,3 +1,10 @@
-/* global myApp */
-myApp.value("TEMP_DIRECTORY", "cordova_app_harness_tempDir/");
-myApp.value("INSTALL_DIRECTORY", "cordova_app_harness_installed_apps/");
\ No newline at end of file
+(function() {
+    var TEMP_DIRECTORY = "cordova_app_harness_tempDir/";
+    var INSTALL_DIRECTORY = "cordova_app_harness_installed_apps/";
+    var APPS_JSON = "cordova_app_harness_installed_apps/apps.json";
+
+    /* global myApp */
+    myApp.value("TEMP_DIRECTORY", TEMP_DIRECTORY);
+    myApp.value("INSTALL_DIRECTORY", INSTALL_DIRECTORY);
+    myApp.value("APPS_JSON", APPS_JSON);
+})();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/js/AppsService.js
----------------------------------------------------------------------
diff --git a/js/AppsService.js b/js/AppsService.js
new file mode 100644
index 0000000..ba012a9
--- /dev/null
+++ b/js/AppsService.js
@@ -0,0 +1,104 @@
+(function() {
+    "use strict";
+    /* global myApp */
+    myApp.factory("AppsService", [ "ResourcesLoader", "INSTALL_DIRECTORY", "TEMP_DIRECTORY",
"APPS_JSON", "$window", function(ResourcesLoader, INSTALL_DIRECTORY, TEMP_DIRECTORY, APPS_JSON,
$window) {
+
+        function addNewAppFromUrl(appName, appUrl) {
+            var fileName = TEMP_DIRECTORY + appName + ".zip";
+            var _fullFilePath;
+
+            return ResourcesLoader.downloadFromUrl(appUrl, fileName)
+            .then(function(fullFilePath){
+                _fullFilePath = fullFilePath;
+                return ResourcesLoader.ensureDirectoryExists(INSTALL_DIRECTORY + appName);
+            })
+            .then(function(directoryPath){
+                return extractZipToDirectory(_fullFilePath, directoryPath);
+            })
+            .then(function(){
+                return registerApp(appName, "urlToZip", appUrl);
+            });
+        }
+
+        function extractZipToDirectory(fileName, outputDirectory){
+            var deferred = Q.defer();
+
+            var onZipDone = function(returnCode) {
+                if(returnCode !== 0) {
+                    deferred.reject(new Error("Something went wrong during the unzipping
of: " + fileName));
+                } else {
+                    deferred.resolve();
+                }
+            };
+
+            /* global zip */
+            zip.unzip(fileName, outputDirectory, onZipDone);
+            return deferred.promise;
+        }
+
+        function registerApp(appName, appSource, appUrl) {
+            return ResourcesLoader.readJSONFileContents(APPS_JSON)
+            .then(function(result){
+                result.installedApps = result.installedApps || [];
+                result.installedApps.push({
+                    "Name" :  appName,
+                    "Source" : appSource,
+                    "Url" : appUrl
+                });
+                return ResourcesLoader.writeJSONFileContents(APPS_JSON, result);
+            });
+        }
+
+        function getAbsoluteUrl(relativeUrl) {
+            // Can't use $document from angularJS as it does not provie the create constructor
+            /* global document */
+            var a = document.createElement("a");
+            a.href = relativeUrl;
+            return a.href;
+        }
+
+        function getAppStartPageFromAppLocation(appLocation) {
+            appLocation += (appLocation.substring(appLocation.length - 1) === "/") ? "" :
"/";
+            var startLocation = appLocation + "www/index.html";
+            return startLocation;
+        }
+
+        return {
+            //return promise with the array of apps
+            getAppsList : function() {
+                return ResourcesLoader.ensureDirectoryExists(APPS_JSON)
+                .then(function() {
+                    return ResourcesLoader.readJSONFileContents(APPS_JSON);
+                })
+                .then(function(result){
+                    result.installedApps = result.installedApps || [];
+                    var newAppsList = [];
+
+                    for(var i = 0; i < result.installedApps.length; i++){
+                        newAppsList.push(result.installedApps[i].Name);
+                    }
+
+                    return newAppsList;
+                });
+            },
+
+            launchApp : function(appName) {
+                return ResourcesLoader.getFullFilePath(INSTALL_DIRECTORY + appName)
+                .then(function(appLocation) {
+                    var startLocation = getAppStartPageFromAppLocation(appLocation);
+                    document.location = startLocation;
+                });
+            },
+
+            addAppFromZipUrl : function(appName, appUrl) {
+                return this.getAppsList()
+                .then(function(appsList){
+                    if(appsList.indexOf(appName) !== -1) {
+                        throw new Error("An app with this name already exists");
+                    }
+                    return addNewAppFromUrl(appName, appUrl);
+                });
+            }
+        };
+    }]);
+})();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/js/ContextMenu.js
----------------------------------------------------------------------
diff --git a/js/ContextMenu.js b/js/ContextMenu.js
new file mode 100644
index 0000000..1e3a760
--- /dev/null
+++ b/js/ContextMenu.js
@@ -0,0 +1,38 @@
+(function () {
+
+    function initialise() {
+        var contextHTMLUrl = "file://__cordovaappharness_contextMenu_page.html";
+        var xhr = new window.XMLHttpRequest();
+        xhr.onreadystatechange=function()
+        {
+            if (xhr.readyState==4 && xhr.status==200)
+            {
+                var stringifiedHtml = xhr.responseText;
+                onInject(stringifiedHtml);
+            }
+        };
+        // retrieve the context menu
+        xhr.open("GET", contextHTMLUrl, true);
+        xhr.send();
+    }
+
+    function onInject(stringifiedHtml) {
+
+        document.body.innerHTML += stringifiedHtml;
+
+        var contextDiv = "__cordovaappharness_contextMenu_div";
+        // Setup the listeners to toggle the context menu
+        document.addEventListener("touchmove", function (event) {
+            if(event.touches.length >= 3) {
+                document.getElementById(contextDiv).style.display = "inline";
+            }
+        }, false);
+
+        document.getElementById(contextDiv).onclick = function() {
+            document.getElementById(contextDiv).style.display = "none";
+        };
+    }
+
+    initialise();
+})();
+

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/js/ListCtrl.js
----------------------------------------------------------------------
diff --git a/js/ListCtrl.js b/js/ListCtrl.js
index 280f475..233c0dc 100644
--- a/js/ListCtrl.js
+++ b/js/ListCtrl.js
@@ -1,24 +1,32 @@
 (function(){
     "use strict";
     /* global myApp */
-    myApp.controller("ListCtrl", [ "$scope", "resourcesLoader", "INSTALL_DIRECTORY", function
($scope, resourcesLoader, INSTALL_DIRECTORY) {
+    myApp.controller("ListCtrl", [ "$scope", "$document", "AppsService", function ($scope,
$document, AppsService) {
 
         $scope.appsList = [];
 
-        $scope.loadAppsList = function(source) {
-            var gotDirectoriesCallback = function(directoryNames, errorString) {
-                if(errorString) {
-                    console.error(errorString);
-                    alert("There was an error retrieving the list of installed applications.
Please try again.");
-                } else {
-                    $scope.appsList.splice(0, $scope.appsList);
-                    angular.extend($scope.appsList, directoryNames);
-                    if(source === "deviceready") {
-                        $scope.$apply();
-                    }
+        $scope.loadAppsList = function( source ) {
+            AppsService.getAppsList()
+            .then(function(newAppsList){
+                //clear the old apps list
+                $scope.appsList.splice(0, $scope.appsList.length);
+                angular.extend($scope.appsList, newAppsList);
+                if(source === "deviceready") {
+                    $scope.$apply();
                 }
-            };
-            resourcesLoader.getSubDirectories(INSTALL_DIRECTORY, gotDirectoriesCallback,
true);
+            }, function(error){
+                var str = "There was an error retrieving the apps list";
+                console.error(str + JSON.stringify(error));
+                alert(str);
+            });
+        };
+
+        $scope.launchApp = function(app){
+            AppsService.launchApp(app)
+            .then(null, function(error){
+                console.error("Error during loading of app: " + error);
+                alert("Something went wrong during the loading of the app. Please try again.");
+            });
         };
 
         $scope.refreshApp = function(app) {
@@ -29,6 +37,6 @@
             alert("removeApp called: " + app);
         };
 
-        document.addEventListener("deviceready", function() { $scope.loadAppsList("deviceready");
}, false);
+        $document.bind("deviceready", function() { $scope.loadAppsList("deviceready"); });
     }]);
 })();
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cordova-app-harness/blob/22d2d337/js/ResourcesLoader.js
----------------------------------------------------------------------
diff --git a/js/ResourcesLoader.js b/js/ResourcesLoader.js
index 80255cd..2b4f768 100644
--- a/js/ResourcesLoader.js
+++ b/js/ResourcesLoader.js
@@ -1,6 +1,8 @@
 (function() {
     "use strict";
-    function ResourcesLoader() {
+
+    /* global myApp */
+    myApp.factory("ResourcesLoader", [ "$window", "$document", function ($window, $document)
{
         var fs;
         var initialised = false;
 
@@ -20,178 +22,220 @@
             };
 
             try {
-                /* global LocalFileSystem */
-                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, failedFileSystemLookUp);
+                $window.requestFileSystem($window.LocalFileSystem.PERSISTENT, 0, success,
failedFileSystemLookUp);
             } catch (e) {
                 failedFileSystemLookUp(e);
             }
         }
 
-        function ensureDirectoryExists(directory, success, fail) {
-            //remove the filename if it exists
-            var lastLevelIndex = directory.search(/\/[\w ]+\.[\w ]+$/g);
-            if(lastLevelIndex !== -1) {
-                directory = directory.substring(0, lastLevelIndex);
-            }
+        $document.bind("deviceready", function() { initialise(); });
 
-            //we need the directory name w.r.t the root, so remove any slashes in the beginning
-            if(directory.indexOf("/") === 0) {
-                directory = directory.substring(1);
-            }
+        //promise returns full path to downloaded file
+        function downloadFromUrl(url, fullFilePath) {
+            var deferred = Q.defer();
 
-            var gotDirEntry = function() {
-                success();
+            var downloadFail = function(error) {
+                var str = "There was an error while downloading the file " + JSON.stringify(error);
+                deferred.reject(new Error(str));
             };
 
-            var failedToGetDirEntry = function(error) {
-                fail("There was an error checking the directory: " + directory, error);
+            var downloadSuccess = function(fileEntry) {
+                deferred.resolve(fileEntry.fullPath);
             };
 
-            fs.root.getDirectory(directory, {create: true, exclusive: false}, gotDirEntry,
failedToGetDirEntry);
+            var fileTransfer = new $window.FileTransfer();
+            var uri = encodeURI(url);
+            fileTransfer.download(uri, fullFilePath, downloadSuccess, downloadFail);
+            return deferred.promise;
         }
 
-        function getFullFilePath(filePath, success, fail) {
-            // Use the file"s parent folder to get the full path
-            var directory = filePath;
-            var fileName = "";
-
-            //remove the filename if it exists
-            var lastLevelIndex = directory.search(/\/[\w ]+\.[\w ]+$/g);
-            if(lastLevelIndex !== -1) {
-                directory = filePath.substring(0, lastLevelIndex);
-                fileName = filePath.substring(lastLevelIndex + 1);
-            }
+        function trim(str) {
+            return str && str.replace(/^\s+|\s+$/g, "");
+        }
 
-            //we need the directory name w.r.t the root, so remove any slashes in the beginning
-            if(directory.indexOf("/") === 0) {
-                directory = directory.substring(1);
+        function makeRelativeToRoot(path) {
+            if(path && (path.charAt(0) === "/")) {
+                path = path.substring(1);
+            } else if(path && path.substring(0, 8) === "file:///") {
+                path = path.substring(8);
             }
-
-            var gotFullPath = function(dirEntry) {
-                var fullFilePath = dirEntry.fullPath + "/" + fileName;
-                success(fullFilePath);
-            };
-
-            var failedToGetFullPath = function(error) {
-                fail("There was an error getting the full path of file: " + filePath, error);
-            };
-
-            fs.root.getDirectory(directory, {create: true, exclusive: false}, gotFullPath,
failedToGetFullPath);
+            return path;
         }
 
-        // callback -> fn (fullFilePath, optional error string if any)
-        this.downloadFromUrl = function(url, filePath, callback) {
-            var fail = function(errorString, error) {
-                if(error) {
-                    errorString += " " + JSON.stringify(error);
-                }
-                callback(undefined, errorString);
-            };
+        //promise returns the file entry
+        function getFileEntry(fileName) {
+            var deferred = Q.defer();
 
-            var success = function(result) {
-                callback(result, undefined);
+            var errorWhileGettingFileEntry = function(error) {
+                var str = "There was an error while getting the file entry for file " + fileName
+ " " + JSON.stringify(error);
+                deferred.reject(new Error(str));
             };
-
-            if(!fs) {
-                fail("The file system was not initialised.");
-            }
-
-            var directoryExistsCallback = function() {
-                var gotFullFilePath = function(fullFilePath) {
-                    downloadFromUrlToFullFilePath(url, fullFilePath, success, fail);
-                };
-                getFullFilePath(filePath, gotFullFilePath, fail);
+            var success = function(fileEntry) {
+                deferred.resolve(fileEntry);
             };
+            fs.root.getFile(fileName, {create: true, exclusive: false}, success, errorWhileGettingFileEntry);
+            return deferred.promise;
+        }
 
-            ensureDirectoryExists(filePath, directoryExistsCallback, fail);
-        };
-
-        function downloadFromUrlToFullFilePath(url, fullFilePath, success, fail) {
-            if(fullFilePath) {
+        //promise returns the file
+        function getFile(fileName) {
+            return getFileEntry(fileName).
+            then(function(fileEntry){
+                var deferred = Q.defer();
 
-                var downloadFail = function(error) {
-                    fail("There was an error while downloading the file", error);
+                var errorWhileGettingFile = function(error) {
+                    var str = "There was an error while getting the file for file " + fileName
+ " " + JSON.stringify(error);
+                    deferred.reject(new Error(str));
                 };
 
-                var downloadSuccess = function(fileEntry) {
-                    if(fileEntry) {
-                        success(fileEntry.fullPath);
-                    } else {
-                        fail("There was anrror while getting the file entry after downloading.");
-                    }
-                };
+                fileEntry.file(deferred.resolve, errorWhileGettingFile);
+                return deferred.promise;
+            });
+        }
 
-                /* global FileTransfer */
-                var fileTransfer = new FileTransfer();
-                var uri = encodeURI(url);
-                fileTransfer.download(uri, fullFilePath, downloadSuccess, downloadFail);
-            } else {
-                fail("There was an error resolving the path specified to save the downloaded
file.");
+        function truncateToDirectoryPath(path) {
+            //remove the filename if it exists
+            var lastLevelIndex = path.search(/[\w ]+(\.[\w ]+)+$/g);
+            if(lastLevelIndex !== -1) {
+                path = path.substring(0, lastLevelIndex);
             }
+            return path;
         }
 
-        // callback -> fn (array of dir names, optional error string if any)
-        this.getSubDirectories = function(directoryPath, callback, createIfUnavailable) {
-            var fail = function(errorString, error) {
-                if(error) {
-                    errorString += " " + JSON.stringify(error);
-                }
-                callback(undefined, errorString);
-            };
+        return {
+            // returns a promise with a full path to the dir
+            ensureDirectoryExists : function(directory) {
+                var deferred = Q.defer();
 
-            var success = function(result) {
-                callback(result, undefined);
-            };
+                directory = truncateToDirectoryPath(directory);
+                directory = makeRelativeToRoot(directory);
 
-            if(!fs) {
-                fail("The file system was not initialised.");
-            }
+                var gotDirEntry = function(dirEntry) {
+                    deferred.resolve(dirEntry.fullPath);
+                };
+
+                var failedToGetDirEntry = function(error) {
+                    var str = "There was an error checking the directory: " + directory +
" " + JSON.stringify(error);
+                    deferred.reject(new Error(str));
+                };
 
-            createIfUnavailable = createIfUnavailable || false;
+                fs.root.getDirectory(directory, {create: true, exclusive: false}, gotDirEntry,
failedToGetDirEntry);
+                return deferred.promise;
+            },
 
-            var failedDirectoryLookUp = function(error) {
-                fail("Could not look up the directory. Check if the directory exists.", error);
-            };
+            // promise returns full path to file
+            getFullFilePath : function(filePath) {
+                var deferred = Q.defer();
 
-            var gotDirectory = function (dirEntry) {
-                getSubDirectoriesForDirectoryEntry(dirEntry, success, fail);
-            };
+                // Use the file's parent folder to get the full path
+                var directory = filePath;
+                var fileName = "";
 
-            fs.root.getDirectory(directoryPath, {create: createIfUnavailable, exclusive:
false}, gotDirectory , failedDirectoryLookUp);
-        };
+                //remove the filename if it exists
+                var lastLevelIndex = directory.search(/\/[\w ]+\.[\w ]+$/g);
+                if(lastLevelIndex !== -1) {
+                    directory = filePath.substring(0, lastLevelIndex);
+                    fileName = filePath.substring(lastLevelIndex + 1);
+                }
 
-        function getSubDirectoriesForDirectoryEntry(dirEntry, success, fail) {
-            if(dirEntry) {
-                var directoryReader = dirEntry.createReader();
+                //we need the directory name w.r.t the root, so remove any slashes in the
beginning
+                if(directory.indexOf("/") === 0) {
+                    directory = directory.substring(1);
+                }
 
-                var failedToGetDirectoryEntries = function(error) {
-                    fail("There was an error while iterating through the directory " + dirEntry.fullPath,
error);
+                var gotFullPath = function(dirEntry) {
+                    var fullFilePath = dirEntry.fullPath + "/" + fileName;
+                    deferred.resolve(fullFilePath);
                 };
 
-                var gotDirectoryEntries = function(entries) {
-                    if(entries) {
-                        var dirList = [];
-                        for(var i = 0; i < entries.length; i++) {
-                            if(entries[i].isDirectory === true) {
-                                dirList.push(entries[i].name);
-                            }
-                        }
-                        success(dirList);
-                    } else {
-                        fail("There was an error retrieving names after listing the files");
-                    }
+                var failedToGetFullPath = function(error) {
+                    var str = "There was an error getting the full path of file: " + filePath
+ " " + JSON.stringify(error);
+                    deferred.reject(new Error(str));
                 };
 
-                // Get a list of all the entries in the directory
-                directoryReader.readEntries(gotDirectoryEntries, failedToGetDirectoryEntries);
-            } else {
-                fail("There was an error while retrieving the directory entry.");
+                fs.root.getDirectory(directory, {create: true, exclusive: false}, gotFullPath,
failedToGetFullPath);
+                return deferred.promise;
+            },
+
+            // returns a promise with a full path to the downloaded file
+            downloadFromUrl : function(url, filePath) {
+                var self = this;
+                return this.ensureDirectoryExists(filePath)
+                .then(function(){
+                    return self.getFullFilePath(filePath);
+                })
+                .then(function(fullFilePath){
+                    return downloadFromUrl(url, fullFilePath);
+                });
+            },
+
+            //returns a promise with the contents of the file
+            readFileContents : function(fileName) {
+                return getFile(fileName)
+                .then(function(file){
+                    var deferred = Q.defer();
+
+                    var reader = new $window.FileReader();
+                    reader.onload = function(evt) {
+                        var text = evt.target.result;
+                        deferred.resolve(text);
+                    };
+                    reader.onerror = function(evt) {
+                        deferred.reject(new Error(evt));
+                    };
+                    reader.readAsText(file);
+
+                    return deferred.promise;
+                });
+            },
+
+            //returns a promise with the json contents of the file
+            readJSONFileContents : function(fileName) {
+                return this.readFileContents(fileName)
+                .then(function (text) {
+                    text = trim(text);
+                    var resultJson = {};
+                    if(text) {
+                        resultJson = JSON.parse(text);
+                    }
+                    return resultJson;
+                });
+            },
+
+            //returns a promise when file is written
+            writeFileContents : function(fileName, contents) {
+                return getFileEntry(fileName)
+                .then(function(fileEntry){
+                    var deferred = Q.defer();
+
+                    var errorGettingFileWriter = function(error) {
+                        var str = "There was an error writing the file." + JSON.stringify(error);
+                        deferred.reject(new Error(str));
+                    };
+
+                    var gotFileWriter = function(writer) {
+                        writer.onwrite = deferred.resolve;
+                        writer.onerror = function(evt) {
+                            deferred.reject(new Error(evt));
+                        };
+                        writer.write(contents);
+                    };
+                    fileEntry.createWriter(gotFileWriter, errorGettingFileWriter);
+                    return deferred.promise;
+                });
+            },
+
+            //returns a promise when json file is written
+            writeJSONFileContents : function(fileName, contents) {
+                var stringContents;
+                if(typeof contents === "string") {
+                    stringContents = contents;
+                } else {
+                    stringContents = JSON.stringify(contents);
+                }
+                return this.writeFileContents(fileName, stringContents);
             }
-        }
-
-        document.addEventListener("deviceready", function() { initialise(); }, false);
-    }
+        };
+    }]);
 
-    /* global myApp */
-    myApp.value("resourcesLoader", new ResourcesLoader());
 })();
\ No newline at end of file


Mime
View raw message