You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by pu...@apache.org on 2012/09/11 01:57:44 UTC
[35/52] [abbrv] [partial] re-org
http://git-wip-us.apache.org/repos/asf/incubator-cordova-windows/blob/03bf0cde/src/cordova-win8/js/file.js
----------------------------------------------------------------------
diff --git a/src/cordova-win8/js/file.js b/src/cordova-win8/js/file.js
deleted file mode 100755
index 80a7c93..0000000
--- a/src/cordova-win8/js/file.js
+++ /dev/null
@@ -1,1645 +0,0 @@
-var Metadata = function (time) {
- this.modificationTime = (typeof time != 'undefined' ? new Date(time) : null);
-};
-
-var FileSystemPersistentRoot = (function () {
- var filePath = Windows.Storage.ApplicationData.current.localFolder.path;
- return filePath;
-}());
-
-var FileSystemTemproraryRoot = (function () {
- var filePath = Windows.Storage.ApplicationData.current.temporaryFolder.path;
- return filePath;
-}());
-
-
-
-function LocalFileSystem() {
-};
-LocalFileSystem.TEMPORARY = 0;
-LocalFileSystem.PERSISTENT = 1;
-
-
-
- /**
- * Look up file system Entry referred to by local URI.
- * @param {DOMString} uri URI referring to a local file or directory
- * @param successCallback invoked with Entry object corresponding to URI
- * @param errorCallback invoked if error occurs retrieving file system entry
- */
-function resolveLocalFileSystemURI (uri, successCallback, errorCallback) {
- // error callback
- var fail = function(error) {
- if (typeof errorCallback === 'function') {
- errorCallback(new FileError(error));
- }
- };
- // if successful, return either a file or directory entry
- var success = function(entry) {
- var result;
-
- if (entry) {
- if (typeof successCallback === 'function') {
- // create appropriate Entry object
- result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath) : new FileEntry(entry.name, entry.fullPath);
- try {
- successCallback(result);
- }
- catch (e) {
- console.log('Error invoking callback: ' + e);
- }
- }
- }
- else {
-
- // no Entry object returned
- fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- var path = uri;
- path = path.split(" ").join("\ ");
-
- // support for file name with parameters
- if (/\?/g.test(path)) {
- path = String(path).split("\?")[0];
- };
-
- // support for encodeURI
- if (/\%5/g.test(path)) {
- path = decodeURI(path);
- };
-
- // support for special path start with file:///
- if (path.substr(0, 8) == "file:///") {
- path = FileSystemPersistentRoot + "\\" + String(path).substr(8).split("/").join("\\");
- Windows.Storage.StorageFile.getFileFromPathAsync(path).then(
- function (storageFile) {
- success(new FileEntry(storageFile.name, storageFile.path));
- },
- function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(
- function (storageFolder) {
- success(new DirectoryEntry(storageFolder.name, storageFolder.path));
- },
- function () {
- fail(FileError.NOT_FOUND_ERR);
- }
- )
- }
- )
- } else {
- Windows.Storage.StorageFile.getFileFromPathAsync(path).then(
- function (storageFile) {
- success(new FileEntry(storageFile.name, storageFile.path));
- },
- function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(
- function (storageFolder) {
- success(new DirectoryEntry(storageFolder.name, storageFolder.path));
- },
- function () {
- fail(FileError.ENCODING_ERR);
- }
- )
- }
- )
- }
-};
-
-function requestFileSystem(type, size, successCallback, errorCallback) {
- var fail = function (code) {
- if (typeof errorCallback === 'function') {
- errorCallback(new FileError(code));
- }
- };
-
- if (type < 0 || type > 3) {
- fail(FileError.SYNTAX_ERR);
- return;
- }
-
- // if successful, return a FileSystem object
- var success = function (file_system) {
- if (file_system) {
- if (typeof successCallback === 'function') {
- // grab the name and root from the file system object
- var result = new FileSystem(file_system.name, file_system.root);
- successCallback(result);
- }
- }
- else {
- // no FileSystem object returned
- fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- var filePath = "";
- var result = null;
- var fsTypeName = "";
-
- switch (type) {
- case LocalFileSystem.TEMPORARY:
- filePath = FileSystemTemproraryRoot;
- fsTypeName = "temporary";
- break;
- case LocalFileSystem.PERSISTENT:
- filePath = FileSystemPersistentRoot;
- fsTypeName = "persistent";
- break;
- }
-
- var MAX_SIZE = 10000000000;
- if (size > MAX_SIZE) {
- fail(FileError.QUOTA_EXCEEDED_ERR);
- return;
- }
-
- var fileSystem = new FileSystem(fsTypeName, new DirectoryEntry(fsTypeName, filePath));
- result = fileSystem;
- success(result);
-}
-
-
-
-function FileSystem(name, root) {
- this.name = name || null;
- if (root) {
- this.root = new DirectoryEntry(root.name, root.fullPath);
- }
-};
-
-
-function FileError(error) {
- this.code = error || null;
-}
-
-// File error codes
-// Found in DOMException
-FileError.NOT_FOUND_ERR = 1;
-FileError.SECURITY_ERR = 2;
-FileError.ABORT_ERR = 3;
-
-// Added by File API specification
-FileError.NOT_READABLE_ERR = 4;
-FileError.ENCODING_ERR = 5;
-FileError.NO_MODIFICATION_ALLOWED_ERR = 6;
-FileError.INVALID_STATE_ERR = 7;
-FileError.SYNTAX_ERR = 8;
-FileError.INVALID_MODIFICATION_ERR = 9;
-FileError.QUOTA_EXCEEDED_ERR = 10;
-FileError.TYPE_MISMATCH_ERR = 11;
-FileError.PATH_EXISTS_ERR = 12;
-
-
-function File(name, fullPath, type, lastModifiedDate, size) {
- this.name = name || '';
- this.fullPath = fullPath || null;
- this.type = type || null;
- this.lastModifiedDate = lastModifiedDate || null;
- this.size = size || 0;
-};
-
-function Flags(create, exclusive) {
- this.create = create || false;
- this.exclusive = exclusive || false;
-}
-
-
-
-/**
- * Represents a file or directory on the local file system.
- *
- * @param isFile
- * {boolean} true if Entry is a file (readonly)
- * @param isDirectory
- * {boolean} true if Entry is a directory (readonly)
- * @param name
- * {DOMString} name of the file or directory, excluding the path
- * leading to it (readonly)
- * @param fullPath
- * {DOMString} the absolute full path to the file or directory
- * (readonly)
- */
-function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
- this.isFile = (typeof isFile != 'undefined' ? isFile : false);
- this.isDirectory = (typeof isDirectory != 'undefined' ? isDirectory : false);
- this.name = name || '';
- this.fullPath = fullPath || '';
- this.filesystem = fileSystem || null;
-}
-
-/**
- * Look up the metadata of the entry.
- *
- * @param successCallback
- * {Function} is called with a Metadata object
- * @param errorCallback
- * {Function} is called with a FileError
- */
-Entry.prototype.getMetadata = function (successCallback, errorCallback) {
- var success = typeof successCallback !== 'function' ? null : function (lastModified) {
- var metadata = new Metadata(lastModified);
- successCallback(metadata);
- };
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
-
- if (this.isFile) {
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fullPath).done(
- function (storageFile) {
- storageFile.getBasicPropertiesAsync().then(
- function (basicProperties) {
- success(basicProperties.dateModified);
- },
- function () {
- fail(FileError.NOT_READABLE_ERR);
- }
- )
- },
- function () {
- fail(FileError.NOT_READABLE_ERR);
- }
- )
- }
-
- if (this.isDirectory) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(this.fullPath).done(
- function (storageFolder) {
- storageFolder.getBasicPropertiesAsync().then(
- function (basicProperties) {
- success(basicProperties.dateModified);
- },
- function () {
- fail(FileError.NOT_FOUND_ERR);
- }
- );
- },
- function () {
- fail(FileError.NOT_READABLE_ERR);
- }
- )
- }
-
-};
-
-
-
-
-/**
- * Move a file or directory to a new location.
- *
- * @param parent
- * {DirectoryEntry} the directory to which to move this entry
- * @param newName
- * {DOMString} new name of the entry, defaults to the current name
- * @param successCallback
- * {Function} called with the new DirectoryEntry object
- * @param errorCallback
- * {Function} called with a FileError
- */
-Entry.prototype.moveTo = function (parent, newName, successCallback, errorCallback) {
- var fail = function (code) {
- if (typeof errorCallback === 'function') {
- errorCallback(new FileError(code));
- }
- };
-
-
- // user must specify parent Entry
- if (!parent) {
- fail(FileError.NOT_FOUND_ERR);
- return;
- }
- // source path
- var srcPath = this.fullPath,
- // entry name
- name = newName || this.name,
- success = function (entry) {
- if (entry) {
- if (typeof successCallback === 'function') {
- // create appropriate Entry object
- var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath) : new FileEntry(entry.name, entry.fullPath);
- try {
- successCallback(result);
- }
- catch (e) {
- console.log('Error invoking callback: ' + e);
- }
- }
- }
- else {
- // no Entry object returned
- fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- //name can't be invalid
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) {
- fail(FileError.ENCODING_ERR);
- return;
- };
-
- var moveFiles = "";
-
-
- if (this.isFile) {
- moveFiles = function (srcPath, parentPath) {
- Windows.Storage.StorageFile.getFileFromPathAsync(srcPath).then(function (storageFile) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (storageFolder) {
- storageFile.moveAsync(storageFolder, name, Windows.Storage.NameCollisionOption.replaceExisting).then(function () {
- success(new FileEntry(name, storageFile.path));
- }, function () {
- fail(FileError.INVALID_MODIFICATION_ERR);
- });
- }, function () {
- fail(FileError.NOT_FOUND_ERR);
- });
- },function () {
- fail(FileError.NOT_FOUND_ERR);
- })
- };
- }
-
- if (this.isDirectory) {
- moveFiles = function (srcPath, parentPath) {
- return new WinJS.Promise(function (complete) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(function (storageFolder) {
- storageFolder.createFileQuery().getFilesAsync().then(function (fileList) {
- var filePromiseArr = [];
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (dstStorageFolder) {
- if (fileList) {
- for (var i = 0; i < fileList.length; i++) {
- filePromiseArr.push(fileList[i].moveAsync(dstStorageFolder));
- }
- }
- WinJS.Promise.join(filePromiseArr).then(function () {
- storageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) {
- var folderPromiseArr = [];
- if (folderList.length == 0) {
- // If failed, we must cancel the deletion of folders & files.So here wo can't delete the folder.
- complete();
- }
- else {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (storageFolderTarget) {
- var tempPromiseArr = [];
- var index = 0;
- for (var j = 0; j < folderList.length; j++) {
- tempPromiseArr[index++] = storageFolderTarget.createFolderAsync(folderList[j].name).then(function (targetFolder) {
- folderPromiseArr.push(moveFiles(folderList[j].path, targetFolder.path));
- })
- }
- WinJS.Promise.join(tempPromiseArr).then(function () {
- WinJS.Promise.join(folderPromiseArr).then(complete);
- });
- })
- }
- })
- }, function () { })
- });
- })
- });
- })
- }
- }
-
- // move
- var isDirectory = this.isDirectory;
- var isFile = this.isFile;
- var moveFinish = function (srcPath, parentPath) {
-
- if (isFile) {
- //can't copy onto itself
- if (srcPath == parentPath + "\\" + name) {
- fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- moveFiles(srcPath, parent.fullPath);
- }
- if (isDirectory) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(function (originFolder) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (storageFolder) {
- storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists).then(function (newStorageFolder) {
- //can't move onto directory that is not empty
- newStorageFolder.createFileQuery().getFilesAsync().then(function (fileList) {
- newStorageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) {
- if (fileList.length != 0 || folderList.length != 0) {
- fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- //can't copy onto itself
- if (srcPath == newStorageFolder.path) {
- fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- //can't copy into itself
- if (srcPath == parentPath) {
- fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- moveFiles(srcPath, newStorageFolder.path).then(function () {
- var successCallback = function () { success(new DirectoryEntry(name, newStorageFolder.path)); }
- new DirectoryEntry(originFolder.name, originFolder.path).removeRecursively(successCallback, fail);
-
- }, function () { console.log("error!"); });
- })
- })
- }, function () { fail(FileError.INVALID_MODIFICATION_ERR) })
- }, function () { fail(FileError.INVALID_MODIFICATION_ERR) })
- }, function () { fail(FileError.INVALID_MODIFICATION_ERR); });
- }
- };
- moveFinish(srcPath, parent.fullPath);
-};
-
-
-
-/**
- * Copy a directory to a different location.
- *
- * @param parent
- * {DirectoryEntry} the directory to which to copy the entry
- * @param newName
- * {DOMString} new name of the entry, defaults to the current name
- * @param successCallback
- * {Function} called with the new Entry object
- * @param errorCallback
- * {Function} called with a FileError
- */
-Entry.prototype.copyTo = function (parent, newName, successCallback, errorCallback) {
- var fail = function (code) {
- if (typeof errorCallback === 'function') {
- errorCallback(new FileError(code));
- }
- };
-
- // user must specify parent Entry
- if (!parent) {
- fail(FileError.NOT_FOUND_ERR);
- return;
- }
-
-
- // source path
- var srcPath = this.fullPath,
- // entry name
- name = newName || this.name,
- // success callback
- success = function (entry) {
- if (entry) {
- if (typeof successCallback === 'function') {
- // create appropriate Entry object
- var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath) : new FileEntry(entry.name, entry.fullPath);
- try {
- successCallback(result);
- }
- catch (e) {
- console.log('Error invoking callback: ' + e);
- }
- }
- }
- else {
- // no Entry object returned
- fail(FileError.NOT_FOUND_ERR);
- }
- };
- //name can't be invalid
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) {
- fail(FileError.ENCODING_ERR);
- return;
- };
- // copy
- var copyFiles = "";
- if (this.isFile) {
- copyFiles = function (srcPath, parentPath) {
- Windows.Storage.StorageFile.getFileFromPathAsync(srcPath).then(function (storageFile) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (storageFolder) {
- storageFile.copyAsync(storageFolder, name, Windows.Storage.NameCollisionOption.failIfExists).then(function (storageFile) {
-
- success(new FileEntry(storageFile.name, storageFile.path));
- }, function () {
-
- fail(FileError.INVALID_MODIFICATION_ERR);
- });
- }, function () {
-
- fail(FileError.NOT_FOUND_ERR);
- });
- }, function () {
-
- fail(FileError.NOT_FOUND_ERR);
- })
- };
- }
-
- if (this.isDirectory) {
- copyFiles = function (srcPath, parentPath) {
- return new WinJS.Promise(function (complete) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(function (storageFolder) {
- storageFolder.createFileQuery().getFilesAsync().then(function (fileList) {
- var filePromiseArr = [];
- if (fileList) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (targetStorageFolder) {
- for (var i = 0; i < fileList.length; i++) {
- filePromiseArr.push(fileList[i].copyAsync(targetStorageFolder));
- }
- WinJS.Promise.join(filePromiseArr).then(function () {
- storageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) {
- var folderPromiseArr = [];
- if (folderList.length == 0) { complete(); }
- else {
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (storageFolderTarget) {
- var tempPromiseArr = [];
- var index = 0;
- for (var j = 0; j < folderList.length; j++) {
- tempPromiseArr[index++] = storageFolderTarget.createFolderAsync(folderList[j].name).then(function (targetFolder) {
- folderPromiseArr.push(copyFiles(folderList[j].path, targetFolder.path));
- })
- }
- WinJS.Promise.join(tempPromiseArr).then(function () {
- WinJS.Promise.join(folderPromiseArr).then(complete);
- });
- })
- }
- })
- })
- })
- }
- })
- })
- })
- }
- }
-
- // copy
- var isFile = this.isFile;
- var isDirectory = this.isDirectory;
- var copyFinish = function (srcPath, parentPath) {
- if (isFile) {
- copyFiles(srcPath, parentPath);
- }
- if (isDirectory) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function(storageFolder){
- storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists).then(function (newStorageFolder) {
- //can't copy onto itself
- if (srcPath == newStorageFolder.path) {
- fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- //can't copy into itself
- if (srcPath == parentPath) {
- fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- copyFiles(srcPath, newStorageFolder.path).then(function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(newStorageFolder.path).done(
- function (storageFolder) {
- success(new DirectoryEntry(storageFolder.name, storageFolder.path));
- },
- function () { fail(FileError.NOT_FOUND_ERR) }
- )
- })
- }, function () { fail(FileError.INVALID_MODIFICATION_ERR); })
- }, function () { fail(FileError.INVALID_MODIFICATION_ERR);})
- }
- };
- copyFinish(srcPath, parent.fullPath);
-};
-
-/**
- * Return a URL that can be used to identify this entry.
- */
-Entry.prototype.toURL = function () {
- // fullPath attribute contains the full URL
- return this.fullPath;
-};
-
-/**
- * Returns a URI that can be used to identify this entry.
- *
- * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI.
- * @return uri
- */
-Entry.prototype.toURI = function (mimeType) {
- console.log("DEPRECATED: Update your code to use 'toURL'");
- // fullPath attribute contains the full URI
- return this.fullPath;
-};
-
-/**
- * Remove a file or directory. It is an error to attempt to delete a
- * directory that is not empty. It is an error to attempt to delete a
- * root directory of a file system.
- *
- * @param successCallback {Function} called with no parameters
- * @param errorCallback {Function} called with a FileError
- */
-Entry.prototype.remove = function (successCallback, errorCallback) {
-
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
-
- errorCallback(new FileError(code));
- };
- if (this.isFile) {
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fullPath).done(function (storageFile) {
- storageFile.deleteAsync().done(successCallback, function () {
- fail(FileError.INVALID_MODIFICATION_ERR);
-
- });
- });
- }
- if (this.isDirectory) {
-
- var fullPath = this.fullPath;
- var removeEntry = function () {
- var storageFolder = null;
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(fullPath).then(function (storageFolder) {
- //FileSystem root can't be removed!
- var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder;
- var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder;
- if (fullPath == storageFolderPer.path || fullPath == storageFolderTem.path) {
- fail(FileError.NO_MODIFICATION_ALLOWED_ERR);
- return;
- }
- storageFolder.createFileQuery().getFilesAsync().then(function (fileList) {
-
- if (fileList.length == 0) {
- storageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) {
-
- if (folderList.length == 0) {
- storageFolder.deleteAsync().done(successCallback, function () {
- fail(FileError.INVALID_MODIFICATION_ERR);
-
- });
- } else {
- fail(FileError.INVALID_MODIFICATION_ERR);
- }
- })
- } else {
- fail(FileError.INVALID_MODIFICATION_ERR);
- }
- });
-
- }, function () {
- fail(FileError.INVALID_MODIFICATION_ERR);
-
- })
-
-
- }
- removeEntry();
- }
-};
-
-/**
- * Look up the parent DirectoryEntry of this entry.
- *
- * @param successCallback {Function} called with the parent DirectoryEntry object
- * @param errorCallback {Function} called with a FileError
- */
-Entry.prototype.getParent = function (successCallback, errorCallback) {
- var win = typeof successCallback !== 'function' ? null : function (result) {
- var entry = new DirectoryEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
-
- var fullPath = this.fullPath;
-
- var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder;
- var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder;
-
- if (fullPath == FileSystemPersistentRoot) {
- win(new DirectoryEntry(storageFolderPer.name, storageFolderPer.path));
- return;
- } else if (fullPath == FileSystemTemproraryRoot) {
- win(new DirectoryEntry(storageFolderTem.name, storageFolderTem.path));
- return;
- }
- var splitArr = fullPath.split(new RegExp(/\/|\\/g));
-
- var popItem = splitArr.pop();
-
- var result = new DirectoryEntry(popItem, fullPath.substr(0, fullPath.length - popItem.length - 1));
- Windows.Storage.StorageFolder.getFolderFromPathAsync(result.fullPath).done(
- function () { win(result) },
- function () { fail(FileError.INVALID_STATE_ERR) }
- );
-};
-
-
-
-
-
-function FileEntry(name, fullPath) {
-
- FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath]);
-
-};
-utils.extend(FileEntry, Entry);
-/**
- * Creates a new FileWriter associated with the file that this FileEntry represents.
- *
- * @param {Function} successCallback is called with the new FileWriter
- * @param {Function} errorCallback is called with a FileError
- */
-
-FileEntry.prototype.createWriter = function (successCallback, errorCallback) {
- this.file(function (filePointer) {
- var writer = new FileWriter(filePointer);
-
- if (writer.fileName === null || writer.fileName === "") {
- if (typeof errorCallback === "function") {
- errorCallback(new FileError(FileError.INVALID_STATE_ERR));
- }
- } else {
- if (typeof successCallback === "function") {
- successCallback(writer);
- }
- }
- }, errorCallback);
-};
-
-/**
- * Returns a File that represents the current state of the file that this FileEntry represents.
- *
- * @param {Function} successCallback is called with the new File object
- * @param {Function} errorCallback is called with a FileError
- */
-FileEntry.prototype.file = function (successCallback, errorCallback) {
- var win = typeof successCallback !== 'function' ? null : function (f) {
- var file = new File(f.name, f.fullPath, f.type, f.lastModifiedDate, f.size);
- successCallback(file);
- };
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fullPath).done(function (storageFile) {
- storageFile.getBasicPropertiesAsync().then(function (basicProperties) {
- win(new File(storageFile.name, storageFile.path, storageFile.fileType, basicProperties.dateModified, basicProperties.size));
- }, function () {
- fail(FileError.NOT_READABLE_ERR);
- })
- }, function () { fail(FileError.NOT_FOUND_ERR) })
-};
-
-/**
- * An interface representing a directory on the file system.
- *
- * {boolean} isFile always false (readonly)
- * {boolean} isDirectory always true (readonly)
- * {DOMString} name of the directory, excluding the path leading to it (readonly)
- * {DOMString} fullPath the absolute full path to the directory (readonly)
- * {FileSystem} filesystem on which the directory resides (readonly)
- */
-function DirectoryEntry(name, fullPath) {
- DirectoryEntry.__super__.constructor.apply(this, [false, true, name, fullPath]);
-};
-
-
-utils.extend(DirectoryEntry, Entry);
-
-/**
- * Creates a new DirectoryReader to read entries from this directory
- */
-DirectoryEntry.prototype.createReader = function () {
- return new DirectoryReader(this.fullPath);
-};
-
-/**
- * Creates or looks up a directory
- *
- * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory
- * @param {Flags} options to create or excluively create the directory
- * @param {Function} successCallback is called with the new entry
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {
- var flag = "";
- if (options != null) {
- flag = new Flags(options.create, options.exclusive);
- } else {
- flag = new Flags(false, false);
- }
-
-
- var win = typeof successCallback !== 'function' ? null : function (result) {
- var entry = new DirectoryEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
- path = String(path).split(" ").join("\ ");
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(this.fullPath).then(function (storageFolder) {
-
- if (flag.create == true && flag.exclusive == true) {
- storageFolder.createFolderAsync(path, Windows.Storage.CreationCollisionOption.failIfExists).done(function (storageFolder) {
- win(new DirectoryEntry(storageFolder.name, storageFolder.path))
- }, function () {
- fail(FileError.PATH_EXISTS_ERR);
- })
- }
- else if (flag.create == true && flag.exclusive == false) {
- storageFolder.createFolderAsync(path, Windows.Storage.CreationCollisionOption.openIfExists).done(function (storageFolder) {
- win(new DirectoryEntry(storageFolder.name, storageFolder.path))
- }, function () {
- fail(FileError.INVALID_MODIFICATION_ERR);
- })
- }
- else if (flag.create == false) {
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) {
- fail(FileError.ENCODING_ERR);
- return;
- };
-
- storageFolder.getFolderAsync(path).done(function (storageFolder) {
-
- win(new DirectoryEntry(storageFolder.name, storageFolder.path))
- }, function () {
- fail(FileError.NOT_FOUND_ERR);
- })
- }
-
- }, function () {
- fail(FileError.NOT_FOUND_ERR)
- })
-
-};
-
-/**
- * Deletes a directory and all of it's contents
- *
- * @param {Function} successCallback is called with no parameters
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
-
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(this.fullPath).done(function (storageFolder) {
- var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder;
- var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder;
-
- if (storageFolder.path == storageFolderPer.path || storageFolder.path == storageFolderTem.path) {
- fail(FileError.NO_MODIFICATION_ALLOWED_ERR);
- return;
- }
-
- var removeFolders = function (path) {
- return new WinJS.Promise(function (complete) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
- var fileListPromise = storageFolder.createFileQuery().getFilesAsync();
- var filePromiseArr = [];
-
- fileListPromise.then(function (fileList) {
- if (fileList != null) {
- for (var i = 0; i < fileList.length; i++) {
- var filePromise = fileList[i].deleteAsync();
- filePromiseArr.push(filePromise);
- }
- }
- WinJS.Promise.join(filePromiseArr).then(function () {
- var folderListPromise = storageFolder.createFolderQuery().getFoldersAsync();
- folderListPromise.then(function (folderList) {
- var folderPromiseArr = [];
- if (folderList.length != 0) {
- for (var j = 0; j < folderList.length; j++) {
-
- folderPromiseArr.push(removeFolders(folderList[j].path));
- }
- WinJS.Promise.join(folderPromiseArr).then(function () {
- storageFolder.deleteAsync().then(complete);
- });
- } else {
- storageFolder.deleteAsync().then(complete);
- }
- }, function () { });
- });
- }, function () { })
- });
- });
- }
- removeFolders(storageFolder.path).then(function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(storageFolder.path).then(
- function () {
-
- },
- function () {
- if (typeof successCallback != 'undefined' && successCallback != null) { successCallback(); }
- })
- });
- })
-};
-
-/**
- * Creates or looks up a file
- *
- * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file
- * @param {Flags} options to create or excluively create the file
- * @param {Function} successCallback is called with the new entry
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {
- var flag = "";
- if (options != null) {
- flag = new Flags(options.create, options.exclusive);
- } else {
- flag = new Flags(false, false);
- }
-
- var win = typeof successCallback !== 'function' ? null : function (result) {
- var entry = new FileEntry(result.name, result.fullPath);
- successCallback(entry);
- };
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
- path = String(path).split(" ").join("\ ");
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(this.fullPath).then(function (storageFolder) {
- if (flag.create == true && flag.exclusive == true) {
- storageFolder.createFileAsync(path, Windows.Storage.CreationCollisionOption.failIfExists).done(function (storageFile) {
- win(new FileEntry(storageFile.name, storageFile.path))
- }, function () {
-
- fail(FileError.PATH_EXISTS_ERR);
- })
- }
- else if (flag.create == true && flag.exclusive == false) {
- storageFolder.createFileAsync(path, Windows.Storage.CreationCollisionOption.openIfExists).done(function (storageFile) {
-
- win(new FileEntry(storageFile.name, storageFile.path))
- }, function () {
-
- fail(FileError.INVALID_MODIFICATION_ERR);
- })
- }
- else if (flag.create == false) {
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) {
- fail(FileError.ENCODING_ERR);
- return;
- };
-
- storageFolder.getFileAsync(path).done(function (storageFile) {
- win(new FileEntry(storageFile.name, storageFile.path))
- }, function () {
- fail(FileError.NOT_FOUND_ERR);
- })
- }
- }, function () {
- fail(FileError.NOT_FOUND_ERR)
- })
-
-};
-var ProgressEvent = (function() {
-
- return function ProgressEvent(type, dict) {
- this.type = type;
- this.bubbles = false;
- this.cancelBubble = false;
- this.cancelable = false;
- this.lengthComputable = false;
- this.loaded = dict && dict.loaded ? dict.loaded : 0;
- this.total = dict && dict.total ? dict.total : 0;
- this.target = dict && dict.target ? dict.target : null;
- };
-
-})();
-
-
-
-
-
-/**
- * This class reads the mobile device file system.
- *
- * For Android:
- * The root directory is the root of the file system.
- * To read from the SD card, the file name is "sdcard/my_file.txt"
- * @constructor
- */
-function FileReader() {
- this.fileName = "";
-
- this.readyState = 0; // FileReader.EMPTY
-
- // File data
- this.result = null;
-
- // Error
- this.error = null;
-
- // Event handlers
- this.onloadstart = null; // When the read starts.
- this.onprogress = null; // While reading (and decoding) file or fileBlob data, and reporting partial file data (progess.loaded/progress.total)
- this.onload = null; // When the read has successfully completed.
- this.onerror = null; // When the read has failed (see errors).
- this.onloadend = null; // When the request has completed (either in success or failure).
- this.onabort = null; // When the read has been aborted. For instance, by invoking the abort() method.
-};
-
-// States
-FileReader.EMPTY = 0;
-FileReader.LOADING = 1;
-FileReader.DONE = 2;
-
-/**
- * Abort reading file.
- */
-FileReader.prototype.abort = function () {
- this.result = null;
-
- if (this.readyState == FileReader.DONE || this.readyState == FileReader.EMPTY) {
- return;
- }
-
- this.readyState = FileReader.DONE;
-
- // If abort callback
- if (typeof this.onabort === 'function') {
- this.onabort(new ProgressEvent('abort', { target: this }));
- }
- // If load end callback
- if (typeof this.onloadend === 'function') {
- this.onloadend(new ProgressEvent('loadend', { target: this }));
- }
-};
-
-/**
- * Read text file.
- *
- * @param file {File} File object containing file properties
- * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets)
- */
-FileReader.prototype.readAsText = function (file, encoding) {
- // Figure out pathing
- this.fileName = '';
- if (typeof file.fullPath === 'undefined') {
- this.fileName = file;
- } else {
- this.fileName = file.fullPath;
- }
-
- // Already loading something
- if (this.readyState == FileReader.LOADING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- // LOADING state
- this.readyState = FileReader.LOADING;
-
- // If loadstart callback
- if (typeof this.onloadstart === "function") {
- this.onloadstart(new ProgressEvent("loadstart", { target: this }));
- }
-
- // Default encoding is UTF-8
- var enc = encoding ? encoding : "Utf8";
-
- var me = this;
-
- // Read file
-
- // Success callback
- var win = function (r) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileReader.DONE) {
- return;
- }
-
- // Save result
- me.result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", { target: me }));
- }
-
- // DONE state
- me.readyState = FileReader.DONE;
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", { target: me }));
- }
- };
- // Error callback
- var fail = function (e) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me.readyState = FileReader.DONE;
-
- // null result
- me.result = null;
-
- // Save error
- me.error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", { target: me }));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", { target: me }));
- }
- };
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fileName).done(function (storageFile) {
- var value = Windows.Storage.Streams.UnicodeEncoding.utf8;
- if(enc == 'Utf16LE' || enc == 'utf16LE'){
- value = Windows.Storage.Streams.UnicodeEncoding.utf16LE;
- }else if(enc == 'Utf16BE' || enc == 'utf16BE'){
- value = Windows.Storage.Streams.UnicodeEncoding.utf16BE;
- }
- Windows.Storage.FileIO.readTextAsync(storageFile, value).done(function (fileContent) {
- win(fileContent);
- }, function () { fail(FileError.ENCODING_ERR) });
- }, function () { fail(FileError.NOT_FOUND_ERR) })
-
-
-};
-
-
-/**
- * Read file and return data as a base64 encoded data url.
- * A data url is of the form:
- * data:[<mediatype>][;base64],<data>
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsDataURL = function (file) {
- this.fileName = "";
- if (typeof file.fullPath === "undefined") {
- this.fileName = file;
- } else {
- this.fileName = file.fullPath;
- }
-
- // Already loading something
- if (this.readyState == FileReader.LOADING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- // LOADING state
- this.readyState = FileReader.LOADING;
-
- // If loadstart callback
- if (typeof this.onloadstart === "function") {
- this.onloadstart(new ProgressEvent("loadstart", { target: this }));
- }
-
- var me = this;
-
- // Read file
-
- // Success callback
- var win = function (r) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me.readyState = FileReader.DONE;
-
- // Save result
- me.result = r;
-
- // If onload callback
- if (typeof me.onload === "function") {
- me.onload(new ProgressEvent("load", { target: me }));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", { target: me }));
- }
- };
- // Error callback
- var fail = function (e) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me.readyState = FileReader.DONE;
-
- me.result = null;
-
- // Save error
- me.error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", { target: me }));
- }
-
- // If onloadend callback
- if (typeof me.onloadend === "function") {
- me.onloadend(new ProgressEvent("loadend", { target: me }));
- }
- };
-
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fileName).then(function (storageFile) {
- Windows.Storage.FileIO.readBufferAsync(storageFile).done(function (buffer) {
- var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
- //the method encodeToBase64String will add "77u/" as a prefix, so we should remove it
- if(String(strBase64).substr(0,4) == "77u/"){
- strBase64 = strBase64.substr(4);
- }
- var mediaType = storageFile.contentType;
- var result = "data:" + mediaType + ";base64," + strBase64;
- win(result);
- })
-
- }, function () { fail(FileError.NOT_FOUND_ERR) });
-
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsBinaryString = function (file) {
- // TODO - Can't return binary data to browser.
- console.log('method "readAsBinaryString" is not supported in cordova API.');
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsArrayBuffer = function (file) {
- // TODO - Can't return binary data to browser.
- console.log('This method is not supported in cordova API.');
-};
-
-
-
-
-
-function DirectoryReader(path) {
- this.path = path || null;
-}
-
-/**
- * Returns a list of entries from a directory.
- *
- * @param {Function} successCallback is called with a list of entries
- * @param {Function} errorCallback is called with a FileError
- */
-DirectoryReader.prototype.readEntries = function (successCallback, errorCallback) {
- var win = typeof successCallback !== 'function' ? null : function (result) {
- var retVal = [];
- for (var i = 0; i < result.length; i++) {
- var entry = null;
-
- if (result[i].isDirectory) {
- entry = new DirectoryEntry();
- }
- else if (result[i].isFile) {
- entry = new FileEntry();
- }
- entry.isDirectory = result[i].isDirectory;
- entry.isFile = result[i].isFile;
- entry.name = result[i].name;
- entry.fullPath = result[i].fullPath;
- retVal.push(entry);
- }
- successCallback(retVal);
- };
- var fail = typeof errorCallback !== 'function' ? null : function (code) {
- errorCallback(new FileError(code));
- };
- var result = new Array();
- var path = this.path;
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
- var promiseArr = [];
- var index = 0;
- promiseArr[index++] = storageFolder.createFileQuery().getFilesAsync().then(function (fileList) {
- if (fileList != null) {
- for (var i = 0; i < fileList.length; i++) {
- result.push(new FileEntry(fileList[i].name, fileList[i].path));
- }
- }
- })
- promiseArr[index++] = storageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) {
- if (folderList != null) {
- for (var j = 0; j < folderList.length; j++) {
- result.push(new FileEntry(folderList[j].name, folderList[j].path));
- }
- }
- })
- WinJS.Promise.join(promiseArr).then(function () {
- win(result);
- })
-
- }, function () { fail(FileError.NOT_FOUND_ERR) })
-};
-
-function FileWriter(file) {
- this.fileName = "";
- this.length = 0;
- if (file) {
- this.fileName = file.fullPath || file;
- this.length = file.size || 0;
- }
- // default is to write at the beginning of the file
- this.position = 0;
-
- this.readyState = 0; // EMPTY
-
- this.result = null;
-
- // Error
- this.error = null;
-
- // Event handlers
- this.onwritestart = null; // When writing starts
- this.onprogress = null; // While writing the file, and reporting partial file data
- this.onwrite = null; // When the write has successfully completed.
- this.onwriteend = null; // When the request has completed (either in success or failure).
- this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method.
- this.onerror = null; // When the write has failed (see errors).
-};
-
-// States
-FileWriter.INIT = 0;
-FileWriter.WRITING = 1;
-FileWriter.DONE = 2;
-
-/**
- * Abort writing file.
- */
-FileWriter.prototype.abort = function () {
- // check for invalid state
- if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- // set error
- this.error = new FileError(FileError.ABORT_ERR);
-
- this.readyState = FileWriter.DONE;
-
- // If abort callback
- if (typeof this.onabort === "function") {
- this.onabort(new ProgressEvent("abort", { "target": this }));
- }
-
- // If write end callback
- if (typeof this.onwriteend === "function") {
- this.onwriteend(new ProgressEvent("writeend", { "target": this }));
- }
-};
-
-/**
- * Writes data to the file
- *
- * @param text to be written
- */
-FileWriter.prototype.write = function (text) {
- // Throw an exception if we are already writing a file
- if (this.readyState === FileWriter.WRITING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- // WRITING state
- this.readyState = FileWriter.WRITING;
-
- var me = this;
-
- // If onwritestart callback
- if (typeof me.onwritestart === "function") {
- me.onwritestart(new ProgressEvent("writestart", { "target": me }));
- }
-
- // Write file
-
- // Success callback
- var win = function (r) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileWriter.DONE) {
- return;
- }
-
- // position always increases by bytes written because file would be extended
- me.position += r;
- // The length of the file is now where we are done writing.
-
- me.length = me.position;
-
- // DONE state
- me.readyState = FileWriter.DONE;
-
- // If onwrite callback
- if (typeof me.onwrite === "function") {
- me.onwrite(new ProgressEvent("write", { "target": me }));
- }
-
- // If onwriteend callback
- if (typeof me.onwriteend === "function") {
- me.onwriteend(new ProgressEvent("writeend", { "target": me }));
- }
- };
- // Error callback
- var fail = function (e) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileWriter.DONE) {
- return;
- }
-
- // DONE state
- me.readyState = FileWriter.DONE;
-
- // Save error
- me.error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", { "target": me }));
- }
-
- // If onwriteend callback
- if (typeof me.onwriteend === "function") {
- me.onwriteend(new ProgressEvent("writeend", { "target": me }));
- }
- };
-
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fileName).done(function (storageFile) {
-
- Windows.Storage.FileIO.writeTextAsync(storageFile,text,Windows.Storage.Streams.UnicodeEncoding.utf8).done(function(){
- win(String(text).length);
- }, function () {
- fail(FileError.INVALID_MODIFICATION_ERR);
- });
- },function(){
-
- fail(FileError.NOT_FOUND_ERR)
- })
-};
-
-/**
- * Moves the file pointer to the location specified.
- *
- * If the offset is a negative number the position of the file
- * pointer is rewound. If the offset is greater than the file
- * size the position is set to the end of the file.
- *
- * @param offset is the location to move the file pointer to.
- */
-FileWriter.prototype.seek = function (offset) {
- // Throw an exception if we are already writing a file
- if (this.readyState === FileWriter.WRITING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- if (!offset && offset !== 0) {
- return;
- }
-
- // See back from end of file.
- if (offset < 0) {
- this.position = Math.max(offset + this.length, 0);
- }
- // Offset is bigger then file size so set position
- // to the end of the file.
- else if (offset > this.length) {
- this.position = this.length;
- }
- // Offset is between 0 and file size so set the position
- // to start writing.
- else {
- this.position = offset;
- }
-};
-
-/**
- * Truncates the file to the size specified.
- *
- * @param size to chop the file at.
- */
-FileWriter.prototype.truncate = function (size) {
- // Throw an exception if we are already writing a file
- if (this.readyState === FileWriter.WRITING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- // WRITING state
- this.readyState = FileWriter.WRITING;
-
- var me = this;
-
- // If onwritestart callback
- if (typeof me.onwritestart === "function") {
- me.onwritestart(new ProgressEvent("writestart", { "target": this }));
- }
-
- // Write file
-
- // Success callback
- var win = function (r) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileWriter.DONE) {
- return;
- }
-
- // DONE state
- me.readyState = FileWriter.DONE;
-
- // Update the length of the file
- me.length = r;
- me.position = Math.min(me.position, r);
-
- // If onwrite callback
- if (typeof me.onwrite === "function") {
- me.onwrite(new ProgressEvent("write", { "target": me }));
- }
-
- // If onwriteend callback
- if (typeof me.onwriteend === "function") {
- me.onwriteend(new ProgressEvent("writeend", { "target": me }));
- }
- };
- // Error callback
- var fail = function (e) {
- // If DONE (cancelled), then don't do anything
- if (me.readyState === FileWriter.DONE) {
- return;
- }
-
- // DONE state
- me.readyState = FileWriter.DONE;
-
- // Save error
- me.error = new FileError(e);
-
- // If onerror callback
- if (typeof me.onerror === "function") {
- me.onerror(new ProgressEvent("error", { "target": me }));
- }
-
- // If onwriteend callback
- if (typeof me.onwriteend === "function") {
- me.onwriteend(new ProgressEvent("writeend", { "target": me }));
- }
- };
-
- Windows.Storage.StorageFile.getFileFromPathAsync(this.fileName).done(function(storageFile){
- //the current length of the file.
- var leng = 0;
-
- storageFile.getBasicPropertiesAsync().then(function (basicProperties) {
- leng = basicProperties.size;
- if (Number(size) >= leng) {
- win(this.length);
- return;
- }
- if (Number(size) >= 0) {
- Windows.Storage.FileIO.readTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.utf8).then(function (fileContent) {
- fileContent = fileContent.substr(0, size);
- var fullPath = storageFile.path;
- var name = storageFile.name;
- var entry = new Entry(true, false, name, fullPath);
- var parentPath = "";
- do {
- var successCallBack = function (entry) {
- parentPath = entry.fullPath;
- }
- entry.getParent(successCallBack, null);
- }
- while (parentPath == "");
- storageFile.deleteAsync().then(function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath).then(function (storageFolder) {
- storageFolder.createFileAsync(name).then(function (newStorageFile) {
- Windows.Storage.FileIO.writeTextAsync(newStorageFile, fileContent).done(function () {
- win(String(fileContent).length);
- }, function () {
- fail(FileError.NO_MODIFICATION_ALLOWED_ERR);
- });
- })
- })
- })
- }, function () { fail(FileError.NOT_FOUND_ERR) });
- }
- })
- }, function () { fail(FileError.NOT_FOUND_ERR) })
-
-};
http://git-wip-us.apache.org/repos/asf/incubator-cordova-windows/blob/03bf0cde/src/cordova-win8/js/filetransfer.js
----------------------------------------------------------------------
diff --git a/src/cordova-win8/js/filetransfer.js b/src/cordova-win8/js/filetransfer.js
deleted file mode 100755
index 294590e..0000000
--- a/src/cordova-win8/js/filetransfer.js
+++ /dev/null
@@ -1,172 +0,0 @@
-function FileTransferError (code , source , target) {
- this.code = code || null;
- this.source = source || null;
- this.target = target || null;
-};
-
-FileTransferError.FILE_NOT_FOUND_ERR = 1;
-FileTransferError.INVALID_URL_ERR = 2;
-FileTransferError.CONNECTION_ERR = 3;
-
-/**
- * FileTransfer uploads a file to a remote server.
- * @constructor
- */
-function FileTransfer() { };
-
-/**
-* Given an absolute file path, uploads a file on the device to a remote server
-* using a multipart HTTP request.
-* @param filePath {String} Full path of the file on the device
-* @param server {String} URL of the server to receive the file
-* @param successCallback (Function} Callback to be invoked when upload has completed
-* @param errorCallback {Function} Callback to be invoked upon error
-* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
-*/
-FileTransfer.prototype.upload = function (filePath, server, successCallback, errorCallback, options) {
- // check for options
- var fileKey = null;
- var fileName = null;
- var mimeType = null;
- var params = null;
- var chunkedMode = true;
- if (options) {
- fileKey = options.fileKey;
- fileName = options.fileName;
- mimeType = options.mimeType;
- if (options.chunkedMode !== null || typeof options.chunkedMode !== "undefined") {
- chunkedMode = options.chunkedMode;
- }
- if (options.params) {
- params = options.params;
- }
- else {
- params = {};
- }
- }
-
- var error = function (code) {
- errorCallback(new FileTransferError(code));
- }
-
- var win = function (fileUploadResult) {
- successCallback(fileUploadResult);
- }
-
- if (filePath == null || typeof filePath == 'undefined') {
- error(FileTransferError.FILE_NOT_FOUND_ERR);
- return;
- }
-
- if (String(filePath).substr(0, 8) == "file:///") {
- filePath = FileSystemPersistentRoot + String(filePath).substr(8).split("/").join("\\");
- }
-
- Windows.Storage.StorageFile.getFileFromPathAsync(filePath).then(function (storageFile) {
- storageFile.openAsync(Windows.Storage.FileAccessMode.read).then(function (stream) {
- var blob = MSApp.createBlobFromRandomAccessStream(storageFile.contentType, stream);
- var formData = new FormData();
- formData.append("source\";filename=\"" + storageFile.name + "\"", blob);
- WinJS.xhr({ type: "POST", url: server, data: formData }).then(function (response) {
- var code = response.status;
- storageFile.getBasicPropertiesAsync().done(function (basicProperties) {
-
- Windows.Storage.FileIO.readBufferAsync(storageFile).done(function (buffer) {
- var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
- var fileContent = dataReader.readString(buffer.length);
- dataReader.close();
- win(new FileUploadResult(basicProperties.size, code, fileContent));
-
- })
-
- })
- }, function () {
- error(FileTransferError.INVALID_URL_ERR);
- })
- })
-
- },function(){error(FileTransferError.FILE_NOT_FOUND_ERR);})
-};
-
-/**
- * Downloads a file form a given URL and saves it to the specified directory.
- * @param source {String} URL of the server to receive the file
- * @param target {String} Full path of the file on the device
- * @param successCallback (Function} Callback to be invoked when upload has completed
- * @param errorCallback {Function} Callback to be invoked upon error
- */
-FileTransfer.prototype.download = function (source, target, successCallback, errorCallback) {
- var win = function (result) {
- var entry = null;
- if (result.isDirectory) {
- entry = new DirectoryEntry();
- }
- else if (result.isFile) {
- entry = new FileEntry();
- }
- entry.isDirectory = result.isDirectory;
- entry.isFile = result.isFile;
- entry.name = result.name;
- entry.fullPath = result.fullPath;
- successCallback(entry);
- };
-
- var error = function (code) {
- errorCallback(new FileTransferError(code));
- }
-
- if (target == null || typeof target == undefined) {
- error(FileTransferError.FILE_NOT_FOUND_ERR);
- return;
- }
- if (String(target).substr(0, 8) == "file:///") {
- target = FileSystemPersistentRoot + String(target).substr(8).split("/").join("\\");
- }
- var path = target.substr(0, String(target).lastIndexOf("\\"));
- var fileName = target.substr(String(target).lastIndexOf("\\") + 1);
- if (path == null || fileName == null) {
- error(FileTransferError.FILE_NOT_FOUND_ERR);
- return;
- }
-
- var download = null;
-
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
- storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).then(function (storageFile) {
- var uri = Windows.Foundation.Uri(source);
- var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
- download = downloader.createDownload(uri, storageFile);
- download.startAsync().then(function () {
- win(new FileEntry(storageFile.name, storageFile.path));
- }, function () {
- error(FileTransferError.INVALID_URL_ERR);
- });
- })
- })
-};
-
-/**
- * Options to customize the HTTP request used to upload files.
- * @constructor
- * @param fileKey {String} Name of file request parameter.
- * @param fileName {String} Filename to be used by the server. Defaults to image.jpg.
- * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg.
- * @param params {Object} Object with key: value params to send to the server.
- */
-function FileUploadOptions (fileKey, fileName, mimeType, params) {
- this.fileKey = fileKey || null;
- this.fileName = fileName || null;
- this.mimeType = mimeType || null;
- this.params = params || null;
-};
-
-/**
- * FileUploadResult
- * @constructor
- */
-function FileUploadResult (bytesSent , responseCode , response) {
- this.bytesSent = bytesSent || 0;
- this.responseCode = responseCode || null;
- this.response = response || null;
-};
http://git-wip-us.apache.org/repos/asf/incubator-cordova-windows/blob/03bf0cde/src/cordova-win8/js/geolocation.js
----------------------------------------------------------------------
diff --git a/src/cordova-win8/js/geolocation.js b/src/cordova-win8/js/geolocation.js
deleted file mode 100755
index 6a97b61..0000000
--- a/src/cordova-win8/js/geolocation.js
+++ /dev/null
@@ -1,242 +0,0 @@
-/**
- * This class contains position information.
- * @param {Object} lat
- * @param {Object} lng
- * @param {Object} alt
- * @param {Object} acc
- * @param {Object} head
- * @param {Object} vel
- * @param {Object} altacc
- * @constructor
- */
-function Coordinates(lat, lng, alt, acc, head, vel, altacc) {
- /**
- * The latitude of the position.
- */
- this.latitude = lat;
- /**
- * The longitude of the position,
- */
- this.longitude = lng;
- /**
- * The accuracy of the position.
- */
- this.accuracy = acc;
- /**
- * The altitude of the position.
- */
- this.altitude = alt;
- /**
- * The direction the device is moving at the position.
- */
- this.heading = head;
- /**
- * The velocity with which the device is moving at the position.
- */
- this.speed = vel;
- /**
- * The altitude accuracy of the position.
- */
- this.altitudeAccuracy = (altacc !== undefined) ? altacc : null;
-};
-
-/**
- * Position error object
- *
- * @constructor
- * @param code
- * @param message
- */
-function PositionError(code, message) {
- this.code = code || null;
- this.message = message || '';
-};
-
-PositionError.PERMISSION_DENIED = 1;
-PositionError.POSITION_UNAVAILABLE = 2;
-PositionError.TIMEOUT = 3;
-
-function Position(coords, timestamp) {
- this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.speed, coords.altitudeAccuracy);
- this.timestamp = (timestamp !== undefined) ? timestamp : new Date().getTime();
-};
-
-
-
-var geolocationTimers = {}; // list of timers in use
-
-// Returns default params, overrides if provided with values
-function geolocationOptions(options) {
- var opt = {
- maximumAge: 10000,
- enableHighAccuracy: false,
- timeout: 10000
- };
-
- if (options) {
- if (options.maximumAge !== undefined) {
- opt.maximumAge = options.maximumAge;
- }
- if (options.enableHighAccuracy !== undefined) {
- opt.enableHighAccuracy = options.enableHighAccuracy;
- }
- if (options.timeout !== undefined) {
- opt.timeout = options.timeout;
- }
- }
-
- return opt;
-}
-
-
-/*
- * This class provides access to device GPS data.
- * @constructor
- */
-function Geolocation() { }
-
-
-/**
- * Asynchronously aquires the current position.
- *
- * @param {Function} successCallback The function to call when the position data is available
- * @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL)
- * @param {PositionOptions} options The options for getting the position data. (OPTIONAL)
- */
-Geolocation.prototype.getCurrentPosition = function (successCallback, errorCallback, options) {
- options = geolocationOptions(options);
- var win = function (p) {
- successCallback(new Position(
- {
- latitude: p.latitude,
- longitude: p.longitude,
- altitude: p.altitude,
- accuracy: p.accuracy,
- heading: p.heading,
- speed: p.speed,
- altitudeAccuracy: p.altitudeAccuracy
- },
- p.timestamp || new Date()
- ));
- };
- var fail = function (e) {
- errorCallback(new PositionError(e.code, e.message));
- };
-
- if (options.timeout <= 0 || options.maximumAge <= 1000) {
- var e = new Object();
- e.message = "getCurrentPosition error callback should be called if we set timeout to 0 and maximumAge to a very small number";
- e.code = PositionError.POSITION_UNAVAILABLE;
- fail(e);
- }
-
- var geolocator = new Windows.Devices.Geolocation.Geolocator();
- if (options.enableHighAccuracy) {
- geolocator.desiredAccuracy = Windows.Devices.Geolocation.PositionAccuracy.high;
- }
-
- geolocator.getGeopositionAsync(options.maximumAge, options.timeout).done(function (geoposition) {
- // Win8 JS API coordinate Object
- var coordinate = geoposition.coordinate;
- win(coordinate);
- }, function () {
- var e = new Object();
-
- switch (geolocator.locationStatus) {
- case Windows.Devices.Geolocation.PositionStatus.ready:
- // Location data is available
- e.message = "Location is available.";
- e.code = PositionError.TIMEOUT;
- fail (e);
- break;
- case Windows.Devices.Geolocation.PositionStatus.initializing:
- // This status indicates that a GPS is still acquiring a fix
- e.message = "A GPS device is still initializing.";
- e.code = PositionError.POSITION_UNAVAILABLE;
- fail(e);
- break;
- case Windows.Devices.Geolocation.PositionStatus.noData:
- // No location data is currently available
- e.message = "Data from location services is currently unavailable.";
- e.code = PositionError.POSITION_UNAVAILABLE;
- fail(e);
- break;
- case Windows.Devices.Geolocation.PositionStatus.disabled:
- // The app doesn't have permission to access location,
- // either because location has been turned off.
- e.message = "Your location is currently turned off. " +
- "Change your settings through the Settings charm " +
- " to turn it back on.";
- e.code = PositionError.PERMISSION_DENIED;
- fail(e);
- break;
- case Windows.Devices.Geolocation.PositionStatus.notInitialized:
- // This status indicates that the app has not yet requested
- // location data by calling GetGeolocationAsync() or
- // registering an event handler for the positionChanged event.
- e.message = "Location status is not initialized because " +
- "the app has not requested location data.";
- e.code = PositionError.POSITION_UNAVAILABLE;
- fail(e);
- break;
- case Windows.Devices.Geolocation.PositionStatus.notAvailable:
- // Location is not available on this version of Windows
- e.message = "You do not have the required location services " +
- "present on your system.";
- e.code = PositionError.POSITION_UNAVAILABLE;
- fail(e);
- break;
- default:
- e.code = PositionError.TIMEOUT;
- fail(e);
- break;
-
- }
- })
-
-}
-
-
-/**
- * Asynchronously watches the geolocation for changes to geolocation. When a change occurs,
- * the successCallback is called with the new location.
- *
- * @param {Function} successCallback The function to call each time the location data is available
- * @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL)
- * @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL)
- * @return String The watch id that must be passed to #clearWatch to stop watching.
- */
-Geolocation.prototype.watchPosition = function (successCallback, errorCallback, options) {
- options = geolocationOptions(options);
-
- var id = createUUID();
- geolocationTimers[id] = new Windows.Devices.Geolocation.Geolocator().getGeopositionAsync(options.maximumAge, options.timeout).done(function () {
- new Geolocation().getCurrentPosition(successCallback, errorCallback, options);
- })
- return id;
-}
-
-
-/**
- * Clears the specified heading watch.
- *
- * @param {String} id The ID of the watch returned from #watchPosition
- */
-Geolocation.prototype.clearWatch = function (id) {
- if (id && geolocationTimers[id] !== undefined) {
- //window.clearInterval(geolocationTimers[id]);
- delete geolocationTimers[id];
- }
-}
-
-
-if (typeof navigator.geolocation == "undefined") {
- // Win RT support the object geolocation , and is Read-Only , So for test , must to change the methods of Object
- var _geo = new Geolocation();
- navigator.geolocation.getCurrentPosition = _geo.getCurrentPosition;
- navigator.geolocation.clearWatch = _geo.clearWatch;
- navigator.geolocation.watchPosition = _geo.watchPosition;
-
-}
-
-
http://git-wip-us.apache.org/repos/asf/incubator-cordova-windows/blob/03bf0cde/src/cordova-win8/js/media.js
----------------------------------------------------------------------
diff --git a/src/cordova-win8/js/media.js b/src/cordova-win8/js/media.js
deleted file mode 100644
index 3dafd6b..0000000
--- a/src/cordova-win8/js/media.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- Notes
- Windows 8 supports by default mp3, wav, wma, cda, adx, wm, m3u, and wmx. This
- can be expanded on by installing new codecs, but Media.prototype.play() needs
- to updated.
- ##Todo
- find better method to implement filetype checking to allow for installed codecs
- record audio
- implement more error checking
-*/
-
-// Object to represnt a media error
-function MediaError(code, message) {
- this.code = code || null;
- this.message = message || null;
-}
-
-// Values defined by W3C spec for HTML5 audio
-MediaError.MEDIA_ERR_NONE_ACTIVE = 0;
-MediaError.MEDIA_ERR_ABORTED = 1;
-MediaError.MEDIA_ERR_NETWORK = 2;
-MediaError.MEDIA_ERR_DECODE = 3;
-MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;
-
-function Media(src, mediaSuccess, mediaError, mediaStatus) {
- this.id = createUUID();
-
- this.src = src;
-
- this.mediaSuccess = mediaSuccess || null;
-
- this.mediaError = mediaError || null;
-
- this.mediaStatus = mediaStatus || null;
-
- this._position = 0;
-
- this._duration = -1;
-
- // Private variable used to identify the audio
- this.node = null;
- this.mediaCaptureMgr = null;
-
-};
-
-// Returns the current position within an audio file
-Media.prototype.getCurrentPosition = function (success, failure) {
- this._position = this.node.currentTime;
- success(this._position);
-};
-
-// Returns the duration of an audio file
-Media.prototype.getDuration = function () {
- this._duration = this.node.duration;
- return this._duration;
-};
-
-// Starts or resumes playing an audio file.
-Media.prototype.play = function () {
- this.node = new Audio(this.src);
- var filename = this.src.split('.').pop(); // get the file extension
-
- if (filename === 'mp3' ||
- filename === 'wav' ||
- filename === 'wma' ||
- filename === 'cda' ||
- filename === 'adx' ||
- filename === 'wm' ||
- filename === 'm3u' ||
- filename === 'wmx') { // checks to see if file extension is correct
- if (this.node === null) {
- this.node.load();
- this._duration = this.node.duration;
- };
- this.node.play();
- } else {
- //invalid file name
- this.mediaError(new MediaError(MediaError.MEDIA_ERR_ABORTED, "Invalid file name"));
- };
-};
-
-// Pauses playing an audio file.
-Media.prototype.pause = function () {
- if (this.node) {
- this.node.pause();
- }
-};
-
-// Releases the underlying operating systems audio resources.
-Media.prototype.release = function () {
- delete node;
-};
-
-// Sets the current position within an audio file.
-Media.prototype.seekTo = function (milliseconds) {
- if (this.node) {
- this.node.currentTime = milliseconds / 1000;
- this.getCurrentPosition();
- }
-};
-
-// Starts recording an audio file.
-Media.prototype.startRecord = function () {
- // Initialize device
- var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings();
- captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio;
- this.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture();
- this.mediaCaptureMgr.addEventListener("failed", mediaError);
-
- this.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) {
- this.mediaCaptureMgr.addEventListener("recordlimitationexceeded", mediaError);
- this.mediaCaptureMgr.addEventListener("failed", mediaError);
- }, mediaError);
- // Start recording
- Windows.Storage.KnownFolders.musicLibrary.createFileAsync(src, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) {
- var storageFile = newFile;
- var fileType = this.src.split('.').pop();
- var encodingProfile = null;
- switch (fileType) {
- case 'm4a':
- encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
- break;
- case 'mp3':
- encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
- break;
- case 'wma':
- encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto);
- break;
- default:
- mediaError();
- break;
- };
- this.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, storageFile).done(function (result) { }, mediaError);
- }, mediaError);
-};
-
-// Stops recording an audio file.
-Media.prototype.stopRecord = function () {
- this.mediaCaptureMgr.stopRecordAsync().done(mediaSuccess, mediaError);
-
-};
-
-// Stops playing an audio file.
-Media.prototype.stop = function () {
- if (this._position > 0) {
- this.node.pause();
- this.node.currentTime = 0;
- this._position = this.node.currentTime;
- }
-};
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-cordova-windows/blob/03bf0cde/src/cordova-win8/js/network.js
----------------------------------------------------------------------
diff --git a/src/cordova-win8/js/network.js b/src/cordova-win8/js/network.js
deleted file mode 100644
index 46bc37b..0000000
--- a/src/cordova-win8/js/network.js
+++ /dev/null
@@ -1,45 +0,0 @@
-function Connection() {
- // Accesses Windows.Networking get the internetConnection Profile.
- this.type = function () {
- var ret;
- var profile = Windows.Networking.Connectivity.NetworkingInformation.getInternetConnectionProfile();
- if (profile) {
- // IANA Interface type represents the type of connection to the computer.
- // Values can be found at http://www.iana.org/assignments/ianaiftype-mib/ianaiftype-mib
- // Code should be updated to represent more values from the above link
- ret = profile.networkAdapter.ianaInterfaceType;
- switch (ret) {
- case 6: // 6 represents wired ethernet
- ret = Connection.ETHERNET;
- break;
- case 71: // 71 represents 802.11 wireless connection
- ret = Connection.WIFI;
- break;
- default: // Other values may exist
- ret = Connection.UNKNOWN;
- break;
- };
- } else {
- // If no profile is generated, no connection exists
- ret = Connection.NONE;
- };
- return ret;
- };
-};
-function Network() {
- this.connection = new Connection();
-
-};
-
-Connection.UNKNOWN = "unknown";
-Connection.ETHERNET = "ethernet";
-Connection.WIFI = "wifi";
-Connection.CELL_2G = "2g";
-Connection.CELL_3G = "3g";
-Connection.CELL_4G = "4g";
-Connection.NONE = "none";
-
-if (typeof navigator.network == "undefined") {
- // Win RT support the object network , and is Read-Only , So for test , must to change the methods of Object
- navigator.network = new Network();
-};
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-cordova-windows/blob/03bf0cde/src/cordova-win8/js/notification.js
----------------------------------------------------------------------
diff --git a/src/cordova-win8/js/notification.js b/src/cordova-win8/js/notification.js
deleted file mode 100644
index 5a1c50c..0000000
--- a/src/cordova-win8/js/notification.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * This class provides access to the notification code.
- */
-function Notification() { };
-
-Notification.prototype.alert = function (message, alertCallback, title, buttonName) {
- title = title || "Alert";
- buttonName = buttonName || "OK";
-
- var md = new Windows.UI.Popups.MessageDialog(message, title);
- md.commands.append(new Windows.UI.Popups.UICommand(buttonName));
- md.showAsync().then(alertCallback);
-};
-
-function alert(message) {
- navigator.notification.alert(message, function () { });
-};
-
-Notification.prototype.confirm = function (message, confirmCallback, title, buttonLabels) {
- title = title || "Confirm";
- buttonLabels = buttonLabels || "OK,Cancel";
-
- var md = new Windows.UI.Popups.MessageDialog(message, title);
- var button = buttonLabels.split(',');
- md.commands.append(new Windows.UI.Popups.UICommand(button[0]));
- md.commands.append(new Windows.UI.Popups.UICommand(button[1]));
- md.showAsync().then(confirmCallback);
-};
-
-/*
-Notification.prototype.beep = function (times) {
- var src = //filepath//
- var playTime = 500; // ms
- var quietTime = 1000; // ms
- var media = new Media(src, function(){});
- var hit = 1;
- var intervalId = window.setInterval( function () {
- media.play();
- sleep(playTime);
- media.stop();
- media.seekTo(0);
- if (hit < times) {
- hit++;
- } else {
- window.clearInterval(intervalId);
- }
- }, playTime + quietTime);
-} */
-
-if (typeof navigator.notification == "undefined") {
- navigator.notification = new Notification;
-}
\ No newline at end of file