You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by ia...@apache.org on 2014/04/25 20:13:47 UTC
[1/8] CB-6521: Remove development branch
Repository: cordova-plugin-file
Updated Branches:
refs/heads/dev 757e692ff -> 9976b3068
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/wp/FileUploadOptions.js
----------------------------------------------------------------------
diff --git a/www/wp/FileUploadOptions.js b/www/wp/FileUploadOptions.js
deleted file mode 100644
index 696573a..0000000
--- a/www/wp/FileUploadOptions.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * 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.
- */
-var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) {
- this.fileKey = fileKey || null;
- this.fileName = fileName || null;
- this.mimeType = mimeType || null;
- this.headers = headers || null;
- this.httpMethod = httpMethod || null;
-
- if(params && typeof params != typeof "") {
- var arrParams = [];
- for(var v in params) {
- arrParams.push(v + "=" + params[v]);
- }
- this.params = encodeURIComponent(arrParams.join("&"));
- }
- else {
- this.params = params || null;
- }
-};
-
-module.exports = FileUploadOptions;
[3/8] CB-6521: Remove development branch
Posted by ia...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/wp/File.cs
----------------------------------------------------------------------
diff --git a/src/wp/File.cs b/src/wp/File.cs
deleted file mode 100644
index 07143b9..0000000
--- a/src/wp/File.cs
+++ /dev/null
@@ -1,1683 +0,0 @@
-/*
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.IO.IsolatedStorage;
-using System.Runtime.Serialization;
-using System.Security;
-using System.Text;
-using System.Windows;
-using System.Windows.Resources;
-
-namespace WPCordovaClassLib.Cordova.Commands
-{
- /// <summary>
- /// Provides access to isolated storage
- /// </summary>
- public class File : BaseCommand
- {
- // Error codes
- public const int NOT_FOUND_ERR = 1;
- public const int SECURITY_ERR = 2;
- public const int ABORT_ERR = 3;
- public const int NOT_READABLE_ERR = 4;
- public const int ENCODING_ERR = 5;
- public const int NO_MODIFICATION_ALLOWED_ERR = 6;
- public const int INVALID_STATE_ERR = 7;
- public const int SYNTAX_ERR = 8;
- public const int INVALID_MODIFICATION_ERR = 9;
- public const int QUOTA_EXCEEDED_ERR = 10;
- public const int TYPE_MISMATCH_ERR = 11;
- public const int PATH_EXISTS_ERR = 12;
-
- // File system options
- public const int TEMPORARY = 0;
- public const int PERSISTENT = 1;
- public const int RESOURCE = 2;
- public const int APPLICATION = 3;
-
- /// <summary>
- /// Temporary directory name
- /// </summary>
- private readonly string TMP_DIRECTORY_NAME = "tmp";
-
- /// <summary>
- /// Represents error code for callback
- /// </summary>
- [DataContract]
- public class ErrorCode
- {
- /// <summary>
- /// Error code
- /// </summary>
- [DataMember(IsRequired = true, Name = "code")]
- public int Code { get; set; }
-
- /// <summary>
- /// Creates ErrorCode object
- /// </summary>
- public ErrorCode(int code)
- {
- this.Code = code;
- }
- }
-
- /// <summary>
- /// Represents File action options.
- /// </summary>
- [DataContract]
- public class FileOptions
- {
- /// <summary>
- /// File path
- /// </summary>
- ///
- private string _fileName;
- [DataMember(Name = "fileName")]
- public string FilePath
- {
- get
- {
- return this._fileName;
- }
-
- set
- {
- int index = value.IndexOfAny(new char[] { '#', '?' });
- this._fileName = index > -1 ? value.Substring(0, index) : value;
- }
- }
-
- /// <summary>
- /// Full entryPath
- /// </summary>
- [DataMember(Name = "fullPath")]
- public string FullPath { get; set; }
-
- /// <summary>
- /// Directory name
- /// </summary>
- [DataMember(Name = "dirName")]
- public string DirectoryName { get; set; }
-
- /// <summary>
- /// Path to create file/directory
- /// </summary>
- [DataMember(Name = "path")]
- public string Path { get; set; }
-
- /// <summary>
- /// The encoding to use to encode the file's content. Default is UTF8.
- /// </summary>
- [DataMember(Name = "encoding")]
- public string Encoding { get; set; }
-
- /// <summary>
- /// Uri to get file
- /// </summary>
- ///
- private string _uri;
- [DataMember(Name = "uri")]
- public string Uri
- {
- get
- {
- return this._uri;
- }
-
- set
- {
- int index = value.IndexOfAny(new char[] { '#', '?' });
- this._uri = index > -1 ? value.Substring(0, index) : value;
- }
- }
-
- /// <summary>
- /// Size to truncate file
- /// </summary>
- [DataMember(Name = "size")]
- public long Size { get; set; }
-
- /// <summary>
- /// Data to write in file
- /// </summary>
- [DataMember(Name = "data")]
- public string Data { get; set; }
-
- /// <summary>
- /// Position the writing starts with
- /// </summary>
- [DataMember(Name = "position")]
- public int Position { get; set; }
-
- /// <summary>
- /// Type of file system requested
- /// </summary>
- [DataMember(Name = "type")]
- public int FileSystemType { get; set; }
-
- /// <summary>
- /// New file/directory name
- /// </summary>
- [DataMember(Name = "newName")]
- public string NewName { get; set; }
-
- /// <summary>
- /// Destination directory to copy/move file/directory
- /// </summary>
- [DataMember(Name = "parent")]
- public string Parent { get; set; }
-
- /// <summary>
- /// Options for getFile/getDirectory methods
- /// </summary>
- [DataMember(Name = "options")]
- public CreatingOptions CreatingOpt { get; set; }
-
- /// <summary>
- /// Creates options object with default parameters
- /// </summary>
- public FileOptions()
- {
- this.SetDefaultValues(new StreamingContext());
- }
-
- /// <summary>
- /// Initializes default values for class fields.
- /// Implemented in separate method because default constructor is not invoked during deserialization.
- /// </summary>
- /// <param name="context"></param>
- [OnDeserializing()]
- public void SetDefaultValues(StreamingContext context)
- {
- this.Encoding = "UTF-8";
- this.FilePath = "";
- this.FileSystemType = -1;
- }
- }
-
- /// <summary>
- /// Stores image info
- /// </summary>
- [DataContract]
- public class FileMetadata
- {
- [DataMember(Name = "fileName")]
- public string FileName { get; set; }
-
- [DataMember(Name = "fullPath")]
- public string FullPath { get; set; }
-
- [DataMember(Name = "type")]
- public string Type { get; set; }
-
- [DataMember(Name = "lastModifiedDate")]
- public string LastModifiedDate { get; set; }
-
- [DataMember(Name = "size")]
- public long Size { get; set; }
-
- public FileMetadata(string filePath)
- {
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (string.IsNullOrEmpty(filePath))
- {
- throw new FileNotFoundException("File doesn't exist");
- }
- else if (!isoFile.FileExists(filePath))
- {
- // attempt to get it from the resources
- if (filePath.IndexOf("www") == 0)
- {
- Uri fileUri = new Uri(filePath, UriKind.Relative);
- StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri);
- if (streamInfo != null)
- {
- this.Size = streamInfo.Stream.Length;
- this.FileName = filePath.Substring(filePath.LastIndexOf("/") + 1);
- this.FullPath = filePath;
- }
- }
- else
- {
- throw new FileNotFoundException("File doesn't exist");
- }
- }
- else
- {
- //TODO get file size the other way if possible
- using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.Read, isoFile))
- {
- this.Size = stream.Length;
- }
- this.FullPath = filePath;
- this.FileName = System.IO.Path.GetFileName(filePath);
- this.LastModifiedDate = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
- }
- this.Type = MimeTypeMapper.GetMimeType(this.FileName);
- }
- }
- }
-
- /// <summary>
- /// Represents file or directory modification metadata
- /// </summary>
- [DataContract]
- public class ModificationMetadata
- {
- /// <summary>
- /// Modification time
- /// </summary>
- [DataMember]
- public string modificationTime { get; set; }
- }
-
- /// <summary>
- /// Represents file or directory entry
- /// </summary>
- [DataContract]
- public class FileEntry
- {
-
- /// <summary>
- /// File type
- /// </summary>
- [DataMember(Name = "isFile")]
- public bool IsFile { get; set; }
-
- /// <summary>
- /// Directory type
- /// </summary>
- [DataMember(Name = "isDirectory")]
- public bool IsDirectory { get; set; }
-
- /// <summary>
- /// File/directory name
- /// </summary>
- [DataMember(Name = "name")]
- public string Name { get; set; }
-
- /// <summary>
- /// Full path to file/directory
- /// </summary>
- [DataMember(Name = "fullPath")]
- public string FullPath { get; set; }
-
- public bool IsResource { get; set; }
-
- public static FileEntry GetEntry(string filePath, bool bIsRes=false)
- {
- FileEntry entry = null;
- try
- {
- entry = new FileEntry(filePath, bIsRes);
-
- }
- catch (Exception ex)
- {
- Debug.WriteLine("Exception in GetEntry for filePath :: " + filePath + " " + ex.Message);
- }
- return entry;
- }
-
- /// <summary>
- /// Creates object and sets necessary properties
- /// </summary>
- /// <param name="filePath"></param>
- public FileEntry(string filePath, bool bIsRes = false)
- {
- if (string.IsNullOrEmpty(filePath))
- {
- throw new ArgumentException();
- }
-
- if(filePath.Contains(" "))
- {
- Debug.WriteLine("FilePath with spaces :: " + filePath);
- }
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- IsResource = bIsRes;
- IsFile = isoFile.FileExists(filePath);
- IsDirectory = isoFile.DirectoryExists(filePath);
- if (IsFile)
- {
- this.Name = Path.GetFileName(filePath);
- }
- else if (IsDirectory)
- {
- this.Name = this.GetDirectoryName(filePath);
- if (string.IsNullOrEmpty(Name))
- {
- this.Name = "/";
- }
- }
- else
- {
- if (IsResource)
- {
- this.Name = Path.GetFileName(filePath);
- }
- else
- {
- throw new FileNotFoundException();
- }
- }
-
- try
- {
- this.FullPath = filePath.Replace('\\', '/'); // new Uri(filePath).LocalPath;
- }
- catch (Exception)
- {
- this.FullPath = filePath;
- }
- }
- }
-
- /// <summary>
- /// Extracts directory name from path string
- /// Path should refer to a directory, for example \foo\ or /foo.
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- private string GetDirectoryName(string path)
- {
- if (String.IsNullOrEmpty(path))
- {
- return path;
- }
-
- string[] split = path.Split(new char[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
- if (split.Length < 1)
- {
- return null;
- }
- else
- {
- return split[split.Length - 1];
- }
- }
- }
-
-
- /// <summary>
- /// Represents info about requested file system
- /// </summary>
- [DataContract]
- public class FileSystemInfo
- {
- /// <summary>
- /// file system type
- /// </summary>
- [DataMember(Name = "name", IsRequired = true)]
- public string Name { get; set; }
-
- /// <summary>
- /// Root directory entry
- /// </summary>
- [DataMember(Name = "root", EmitDefaultValue = false)]
- public FileEntry Root { get; set; }
-
- /// <summary>
- /// Creates class instance
- /// </summary>
- /// <param name="name"></param>
- /// <param name="rootEntry"> Root directory</param>
- public FileSystemInfo(string name, FileEntry rootEntry = null)
- {
- Name = name;
- Root = rootEntry;
- }
- }
-
- [DataContract]
- public class CreatingOptions
- {
- /// <summary>
- /// Create file/directory if is doesn't exist
- /// </summary>
- [DataMember(Name = "create")]
- public bool Create { get; set; }
-
- /// <summary>
- /// Generate an exception if create=true and file/directory already exists
- /// </summary>
- [DataMember(Name = "exclusive")]
- public bool Exclusive { get; set; }
-
-
- }
-
- // returns null value if it fails.
- private string[] getOptionStrings(string options)
- {
- string[] optStings = null;
- try
- {
- optStings = JSON.JsonHelper.Deserialize<string[]>(options);
- }
- catch (Exception)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), CurrentCommandCallbackId);
- }
- return optStings;
- }
-
- /// <summary>
- /// Gets amount of free space available for Isolated Storage
- /// </summary>
- /// <param name="options">No options is needed for this method</param>
- public void getFreeDiskSpace(string options)
- {
- string callbackId = getOptionStrings(options)[0];
-
- try
- {
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isoFile.AvailableFreeSpace), callbackId);
- }
- }
- catch (IsolatedStorageException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
-
- /// <summary>
- /// Check if file exists
- /// </summary>
- /// <param name="options">File path</param>
- public void testFileExists(string options)
- {
- IsDirectoryOrFileExist(options, false);
- }
-
- /// <summary>
- /// Check if directory exists
- /// </summary>
- /// <param name="options">directory name</param>
- public void testDirectoryExists(string options)
- {
- IsDirectoryOrFileExist(options, true);
- }
-
- /// <summary>
- /// Check if file or directory exist
- /// </summary>
- /// <param name="options">File path/Directory name</param>
- /// <param name="isDirectory">Flag to recognize what we should check</param>
- public void IsDirectoryOrFileExist(string options, bool isDirectory)
- {
- string[] args = getOptionStrings(options);
- string callbackId = args[1];
- FileOptions fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(args[0]);
- string filePath = args[0];
-
- if (fileOptions == null)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
- }
-
- try
- {
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- bool isExist;
- if (isDirectory)
- {
- isExist = isoFile.DirectoryExists(fileOptions.DirectoryName);
- }
- else
- {
- isExist = isoFile.FileExists(fileOptions.FilePath);
- }
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, isExist), callbackId);
- }
- }
- catch (IsolatedStorageException) // default handler throws INVALID_MODIFICATION_ERR
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
- }
-
- }
-
- public void readAsDataURL(string options)
- {
- string[] optStrings = getOptionStrings(options);
- string filePath = optStrings[0];
- int startPos = int.Parse(optStrings[1]);
- int endPos = int.Parse(optStrings[2]);
- string callbackId = optStrings[3];
-
- if (filePath != null)
- {
- try
- {
- string base64URL = null;
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (!isoFile.FileExists(filePath))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
- string mimeType = MimeTypeMapper.GetMimeType(filePath);
-
- using (IsolatedStorageFileStream stream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
- {
- string base64String = GetFileContent(stream);
- base64URL = "data:" + mimeType + ";base64," + base64String;
- }
- }
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, base64URL), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
- }
-
- public void readAsArrayBuffer(string options)
- {
- string[] optStrings = getOptionStrings(options);
- string filePath = optStrings[0];
- int startPos = int.Parse(optStrings[1]);
- int endPos = int.Parse(optStrings[2]);
- string callbackId = optStrings[3];
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId);
- }
-
- public void readAsBinaryString(string options)
- {
- string[] optStrings = getOptionStrings(options);
- string filePath = optStrings[0];
- int startPos = int.Parse(optStrings[1]);
- int endPos = int.Parse(optStrings[2]);
- string callbackId = optStrings[3];
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR), callbackId);
- }
-
- public void readAsText(string options)
- {
- string[] optStrings = getOptionStrings(options);
- string filePath = optStrings[0];
- string encStr = optStrings[1];
- int startPos = int.Parse(optStrings[2]);
- int endPos = int.Parse(optStrings[3]);
- string callbackId = optStrings[4];
-
- try
- {
- string text = "";
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (!isoFile.FileExists(filePath))
- {
- readResourceAsText(options);
- return;
- }
- Encoding encoding = Encoding.GetEncoding(encStr);
-
- using (IsolatedStorageFileStream reader = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
- {
- if (startPos < 0)
- {
- startPos = Math.Max((int)reader.Length + startPos, 0);
- }
- else if (startPos > 0)
- {
- startPos = Math.Min((int)reader.Length, startPos);
- }
-
- if (endPos > 0)
- {
- endPos = Math.Min((int)reader.Length, endPos);
- }
- else if (endPos < 0)
- {
- endPos = Math.Max(endPos + (int)reader.Length, 0);
- }
-
-
- var buffer = new byte[endPos - startPos];
-
- reader.Seek(startPos, SeekOrigin.Begin);
- reader.Read(buffer, 0, buffer.Length);
-
- text = encoding.GetString(buffer, 0, buffer.Length);
-
- }
- }
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
-
- /// <summary>
- /// Reads application resource as a text
- /// </summary>
- /// <param name="options">Path to a resource</param>
- public void readResourceAsText(string options)
- {
- string[] optStrings = getOptionStrings(options);
- string pathToResource = optStrings[0];
- string encStr = optStrings[1];
- int start = int.Parse(optStrings[2]);
- int endMarker = int.Parse(optStrings[3]);
- string callbackId = optStrings[4];
-
- try
- {
- if (pathToResource.StartsWith("/"))
- {
- pathToResource = pathToResource.Remove(0, 1);
- }
-
- var resource = Application.GetResourceStream(new Uri(pathToResource, UriKind.Relative));
-
- if (resource == null)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
-
- string text;
- StreamReader streamReader = new StreamReader(resource.Stream);
- text = streamReader.ReadToEnd();
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, text), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
-
- public void truncate(string options)
- {
- string[] optStrings = getOptionStrings(options);
-
- string filePath = optStrings[0];
- int size = int.Parse(optStrings[1]);
- string callbackId = optStrings[2];
-
- try
- {
- long streamLength = 0;
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (!isoFile.FileExists(filePath))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
-
- using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
- {
- if (0 <= size && size <= stream.Length)
- {
- stream.SetLength(size);
- }
- streamLength = stream.Length;
- }
- }
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
-
- //write:[filePath,data,position,isBinary,callbackId]
- public void write(string options)
- {
- string[] optStrings = getOptionStrings(options);
-
- string filePath = optStrings[0];
- string data = optStrings[1];
- int position = int.Parse(optStrings[2]);
- bool isBinary = bool.Parse(optStrings[3]);
- string callbackId = optStrings[4];
-
- try
- {
- if (string.IsNullOrEmpty(data))
- {
- Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath);
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
- return;
- }
-
- char[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize<char[]>(data) :
- data.ToCharArray();
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- // create the file if not exists
- if (!isoFile.FileExists(filePath))
- {
- var file = isoFile.CreateFile(filePath);
- file.Close();
- }
-
- using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile))
- {
- if (0 <= position && position <= stream.Length)
- {
- stream.SetLength(position);
- }
- using (BinaryWriter writer = new BinaryWriter(stream))
- {
- writer.Seek(0, SeekOrigin.End);
- writer.Write(dataToWrite);
- }
- }
- }
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
-
- /// <summary>
- /// Look up metadata about this entry.
- /// </summary>
- /// <param name="options">filePath to entry</param>
- public void getMetadata(string options)
- {
- string[] optStings = getOptionStrings(options);
- string filePath = optStings[0];
- string callbackId = optStings[1];
-
- if (filePath != null)
- {
- try
- {
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (isoFile.FileExists(filePath))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK,
- new ModificationMetadata() { modificationTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString() }), callbackId);
- }
- else if (isoFile.DirectoryExists(filePath))
- {
- string modTime = isoFile.GetLastWriteTime(filePath).DateTime.ToString();
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new ModificationMetadata() { modificationTime = modTime }), callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
-
- }
- }
- catch (IsolatedStorageException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
-
- }
-
-
- /// <summary>
- /// Returns a File that represents the current state of the file that this FileEntry represents.
- /// </summary>
- /// <param name="filePath">filePath to entry</param>
- /// <returns></returns>
- public void getFileMetadata(string options)
- {
- string[] optStings = getOptionStrings(options);
- string filePath = optStings[0];
- string callbackId = optStings[1];
-
- if (filePath != null)
- {
- try
- {
- FileMetadata metaData = new FileMetadata(filePath);
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, metaData), callbackId);
- }
- catch (IsolatedStorageException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId);
- }
- }
- }
- }
-
- /// <summary>
- /// Look up the parent DirectoryEntry containing this Entry.
- /// If this Entry is the root of IsolatedStorage, its parent is itself.
- /// </summary>
- /// <param name="options"></param>
- public void getParent(string options)
- {
- string[] optStings = getOptionStrings(options);
- string filePath = optStings[0];
- string callbackId = optStings[1];
-
- if (filePath != null)
- {
- try
- {
- if (string.IsNullOrEmpty(filePath))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId);
- return;
- }
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- FileEntry entry;
-
- if (isoFile.FileExists(filePath) || isoFile.DirectoryExists(filePath))
- {
-
-
- string path = this.GetParentDirectory(filePath);
- entry = FileEntry.GetEntry(path);
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry),callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
- }
-
- }
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
- }
- }
- }
- }
-
- public void remove(string options)
- {
- string[] args = getOptionStrings(options);
- string filePath = args[0];
- string callbackId = args[1];
-
- if (filePath != null)
- {
- try
- {
- if (filePath == "/" || filePath == "" || filePath == @"\")
- {
- throw new Exception("Cannot delete root file system") ;
- }
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (isoFile.FileExists(filePath))
- {
- isoFile.DeleteFile(filePath);
- }
- else
- {
- if (isoFile.DirectoryExists(filePath))
- {
- isoFile.DeleteDirectory(filePath);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
- return;
- }
- }
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK),callbackId);
- }
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
- }
- }
- }
- }
-
- public void removeRecursively(string options)
- {
- string[] args = getOptionStrings(options);
- string filePath = args[0];
- string callbackId = args[1];
-
- if (filePath != null)
- {
- if (string.IsNullOrEmpty(filePath))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId);
- }
- else
- {
- if (removeDirRecursively(filePath, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId);
- }
- }
- }
- }
-
- public void readEntries(string options)
- {
- string[] args = getOptionStrings(options);
- string filePath = args[0];
- string callbackId = args[1];
-
- if (filePath != null)
- {
- try
- {
- if (string.IsNullOrEmpty(filePath))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION),callbackId);
- return;
- }
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (isoFile.DirectoryExists(filePath))
- {
- string path = File.AddSlashToDirectory(filePath);
- List<FileEntry> entries = new List<FileEntry>();
- string[] files = isoFile.GetFileNames(path + "*");
- string[] dirs = isoFile.GetDirectoryNames(path + "*");
- foreach (string file in files)
- {
- entries.Add(FileEntry.GetEntry(path + file));
- }
- foreach (string dir in dirs)
- {
- entries.Add(FileEntry.GetEntry(path + dir + "/"));
- }
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entries),callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
- }
- }
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
- }
- }
- }
- }
-
- public void requestFileSystem(string options)
- {
- // TODO: try/catch
- string[] optVals = getOptionStrings(options);
- //FileOptions fileOptions = new FileOptions();
- int fileSystemType = int.Parse(optVals[0]);
- double size = double.Parse(optVals[1]);
- string callbackId = optVals[2];
-
-
- IsolatedStorageFile.GetUserStoreForApplication();
-
- if (size > (10 * 1024 * 1024)) // 10 MB, compier will clean this up!
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId);
- return;
- }
-
- try
- {
- if (size != 0)
- {
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- long availableSize = isoFile.AvailableFreeSpace;
- if (size > availableSize)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, QUOTA_EXCEEDED_ERR), callbackId);
- return;
- }
- }
- }
-
- if (fileSystemType == PERSISTENT)
- {
- // TODO: this should be in it's own folder to prevent overwriting of the app assets, which are also in ISO
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("persistent", FileEntry.GetEntry("/"))), callbackId);
- }
- else if (fileSystemType == TEMPORARY)
- {
- using (IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (!isoStorage.FileExists(TMP_DIRECTORY_NAME))
- {
- isoStorage.CreateDirectory(TMP_DIRECTORY_NAME);
- }
- }
-
- string tmpFolder = "/" + TMP_DIRECTORY_NAME + "/";
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("temporary", FileEntry.GetEntry(tmpFolder))), callbackId);
- }
- else if (fileSystemType == RESOURCE)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("resource")), callbackId);
- }
- else if (fileSystemType == APPLICATION)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileSystemInfo("application")), callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
- }
-
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
- }
- }
- }
-
- public void resolveLocalFileSystemURI(string options)
- {
-
- string[] optVals = getOptionStrings(options);
- string uri = optVals[0].Split('?')[0];
- string callbackId = optVals[1];
-
- if (uri != null)
- {
- // a single '/' is valid, however, '/someDir' is not, but '/tmp//somedir' and '///someDir' are valid
- if (uri.StartsWith("/") && uri.IndexOf("//") < 0 && uri != "/")
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
- return;
- }
- try
- {
- // fix encoded spaces
- string path = Uri.UnescapeDataString(uri);
-
- FileEntry uriEntry = FileEntry.GetEntry(path);
- if (uriEntry != null)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, uriEntry), callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
- }
- }
- }
- }
-
- public void copyTo(string options)
- {
- TransferTo(options, false);
- }
-
- public void moveTo(string options)
- {
- TransferTo(options, true);
- }
-
- public void getFile(string options)
- {
- GetFileOrDirectory(options, false);
- }
-
- public void getDirectory(string options)
- {
- GetFileOrDirectory(options, true);
- }
-
- #region internal functionality
-
- /// <summary>
- /// Retrieves the parent directory name of the specified path,
- /// </summary>
- /// <param name="path">Path</param>
- /// <returns>Parent directory name</returns>
- private string GetParentDirectory(string path)
- {
- if (String.IsNullOrEmpty(path) || path == "/")
- {
- return "/";
- }
-
- if (path.EndsWith(@"/") || path.EndsWith(@"\"))
- {
- return this.GetParentDirectory(Path.GetDirectoryName(path));
- }
-
- string result = Path.GetDirectoryName(path);
- if (result == null)
- {
- result = "/";
- }
-
- return result;
- }
-
- private bool removeDirRecursively(string fullPath,string callbackId)
- {
- try
- {
- if (fullPath == "/")
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
- return false;
- }
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- if (isoFile.DirectoryExists(fullPath))
- {
- string tempPath = File.AddSlashToDirectory(fullPath);
- string[] files = isoFile.GetFileNames(tempPath + "*");
- if (files.Length > 0)
- {
- foreach (string file in files)
- {
- isoFile.DeleteFile(tempPath + file);
- }
- }
- string[] dirs = isoFile.GetDirectoryNames(tempPath + "*");
- if (dirs.Length > 0)
- {
- foreach (string dir in dirs)
- {
- if (!removeDirRecursively(tempPath + dir, callbackId))
- {
- return false;
- }
- }
- }
- isoFile.DeleteDirectory(fullPath);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR),callbackId);
- }
- }
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR),callbackId);
- return false;
- }
- }
- return true;
- }
-
- private bool CanonicalCompare(string pathA, string pathB)
- {
- string a = pathA.Replace("//", "/");
- string b = pathB.Replace("//", "/");
-
- return a.Equals(b, StringComparison.OrdinalIgnoreCase);
- }
-
- /*
- * copyTo:["fullPath","parent", "newName"],
- * moveTo:["fullPath","parent", "newName"],
- */
- private void TransferTo(string options, bool move)
- {
- // TODO: try/catch
- string[] optStrings = getOptionStrings(options);
- string fullPath = optStrings[0];
- string parent = optStrings[1];
- string newFileName = optStrings[2];
- string callbackId = optStrings[3];
-
- char[] invalids = Path.GetInvalidPathChars();
-
- if (newFileName.IndexOfAny(invalids) > -1 || newFileName.IndexOf(":") > -1 )
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
- return;
- }
-
- try
- {
- if ((parent == null) || (string.IsNullOrEmpty(parent)) || (string.IsNullOrEmpty(fullPath)))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
-
- string parentPath = File.AddSlashToDirectory(parent);
- string currentPath = fullPath;
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- bool isFileExist = isoFile.FileExists(currentPath);
- bool isDirectoryExist = isoFile.DirectoryExists(currentPath);
- bool isParentExist = isoFile.DirectoryExists(parentPath);
-
- if ( ( !isFileExist && !isDirectoryExist ) || !isParentExist )
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
- string newName;
- string newPath;
- if (isFileExist)
- {
- newName = (string.IsNullOrEmpty(newFileName))
- ? Path.GetFileName(currentPath)
- : newFileName;
-
- newPath = Path.Combine(parentPath, newName);
-
- // sanity check ..
- // cannot copy file onto itself
- if (CanonicalCompare(newPath,currentPath)) //(parent + newFileName))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId);
- return;
- }
- else if (isoFile.DirectoryExists(newPath))
- {
- // there is already a folder with the same name, operation is not allowed
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId);
- return;
- }
- else if (isoFile.FileExists(newPath))
- { // remove destination file if exists, in other case there will be exception
- isoFile.DeleteFile(newPath);
- }
-
- if (move)
- {
- isoFile.MoveFile(currentPath, newPath);
- }
- else
- {
- isoFile.CopyFile(currentPath, newPath, true);
- }
- }
- else
- {
- newName = (string.IsNullOrEmpty(newFileName))
- ? currentPath
- : newFileName;
-
- newPath = Path.Combine(parentPath, newName);
-
- if (move)
- {
- // remove destination directory if exists, in other case there will be exception
- // target directory should be empty
- if (!newPath.Equals(currentPath) && isoFile.DirectoryExists(newPath))
- {
- isoFile.DeleteDirectory(newPath);
- }
-
- isoFile.MoveDirectory(currentPath, newPath);
- }
- else
- {
- CopyDirectory(currentPath, newPath, isoFile);
- }
- }
- FileEntry entry = FileEntry.GetEntry(newPath);
- if (entry != null)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
- }
-
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex, callbackId))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
- }
- }
- }
-
- private bool HandleException(Exception ex, string cbId="")
- {
- bool handled = false;
- string callbackId = String.IsNullOrEmpty(cbId) ? this.CurrentCommandCallbackId : cbId;
- if (ex is SecurityException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, SECURITY_ERR), callbackId);
- handled = true;
- }
- else if (ex is FileNotFoundException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- handled = true;
- }
- else if (ex is ArgumentException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
- handled = true;
- }
- else if (ex is IsolatedStorageException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, INVALID_MODIFICATION_ERR), callbackId);
- handled = true;
- }
- else if (ex is DirectoryNotFoundException)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- handled = true;
- }
- return handled;
- }
-
- private void CopyDirectory(string sourceDir, string destDir, IsolatedStorageFile isoFile)
- {
- string path = File.AddSlashToDirectory(sourceDir);
-
- bool bExists = isoFile.DirectoryExists(destDir);
-
- if (!bExists)
- {
- isoFile.CreateDirectory(destDir);
- }
-
- destDir = File.AddSlashToDirectory(destDir);
-
- string[] files = isoFile.GetFileNames(path + "*");
-
- if (files.Length > 0)
- {
- foreach (string file in files)
- {
- isoFile.CopyFile(path + file, destDir + file,true);
- }
- }
- string[] dirs = isoFile.GetDirectoryNames(path + "*");
- if (dirs.Length > 0)
- {
- foreach (string dir in dirs)
- {
- CopyDirectory(path + dir, destDir + dir, isoFile);
- }
- }
- }
-
- private void GetFileOrDirectory(string options, bool getDirectory)
- {
- FileOptions fOptions = new FileOptions();
- string[] args = getOptionStrings(options);
-
- fOptions.FullPath = args[0];
- fOptions.Path = args[1];
-
- string callbackId = args[3];
-
- try
- {
- fOptions.CreatingOpt = JSON.JsonHelper.Deserialize<CreatingOptions>(args[2]);
- }
- catch (Exception)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId);
- return;
- }
-
- try
- {
- if ((string.IsNullOrEmpty(fOptions.Path)) || (string.IsNullOrEmpty(fOptions.FullPath)))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
-
- string path;
-
- if (fOptions.Path.Split(':').Length > 2)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
- return;
- }
-
- try
- {
- path = Path.Combine(fOptions.FullPath + "/", fOptions.Path);
- }
- catch (Exception)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ENCODING_ERR), callbackId);
- return;
- }
-
- using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
- {
- bool isFile = isoFile.FileExists(path);
- bool isDirectory = isoFile.DirectoryExists(path);
- bool create = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Create;
- bool exclusive = (fOptions.CreatingOpt == null) ? false : fOptions.CreatingOpt.Exclusive;
- if (create)
- {
- if (exclusive && (isoFile.FileExists(path) || isoFile.DirectoryExists(path)))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, PATH_EXISTS_ERR), callbackId);
- return;
- }
-
- // need to make sure the parent exists
- // it is an error to create a directory whose immediate parent does not yet exist
- // see issue: https://issues.apache.org/jira/browse/CB-339
- string[] pathParts = path.Split('/');
- string builtPath = pathParts[0];
- for (int n = 1; n < pathParts.Length - 1; n++)
- {
- builtPath += "/" + pathParts[n];
- if (!isoFile.DirectoryExists(builtPath))
- {
- Debug.WriteLine(String.Format("Error :: Parent folder \"{0}\" does not exist, when attempting to create \"{1}\"",builtPath,path));
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- return;
- }
- }
-
- if ((getDirectory) && (!isDirectory))
- {
- isoFile.CreateDirectory(path);
- }
- else
- {
- if ((!getDirectory) && (!isFile))
- {
-
- IsolatedStorageFileStream fileStream = isoFile.CreateFile(path);
- fileStream.Close();
- }
- }
- }
- else // (not create)
- {
- if ((!isFile) && (!isDirectory))
- {
- if (path.IndexOf("//www") == 0)
- {
- Uri fileUri = new Uri(path.Remove(0,2), UriKind.Relative);
- StreamResourceInfo streamInfo = Application.GetResourceStream(fileUri);
- if (streamInfo != null)
- {
- FileEntry _entry = FileEntry.GetEntry(fileUri.OriginalString,true);
-
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, _entry), callbackId);
-
- //using (BinaryReader br = new BinaryReader(streamInfo.Stream))
- //{
- // byte[] data = br.ReadBytes((int)streamInfo.Stream.Length);
-
- //}
-
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
-
-
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
- return;
- }
- if (((getDirectory) && (!isDirectory)) || ((!getDirectory) && (!isFile)))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, TYPE_MISMATCH_ERR), callbackId);
- return;
- }
- }
- FileEntry entry = FileEntry.GetEntry(path);
- if (entry != null)
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
- }
- else
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR), callbackId);
- }
- }
- }
- catch (Exception ex)
- {
- if (!this.HandleException(ex))
- {
- DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NO_MODIFICATION_ALLOWED_ERR), callbackId);
- }
- }
- }
-
- private static string AddSlashToDirectory(string dirPath)
- {
- if (dirPath.EndsWith("/"))
- {
- return dirPath;
- }
- else
- {
- return dirPath + "/";
- }
- }
-
- /// <summary>
- /// Returns file content in a form of base64 string
- /// </summary>
- /// <param name="stream">File stream</param>
- /// <returns>Base64 representation of the file</returns>
- private string GetFileContent(Stream stream)
- {
- int streamLength = (int)stream.Length;
- byte[] fileData = new byte[streamLength + 1];
- stream.Read(fileData, 0, streamLength);
- stream.Close();
- return Convert.ToBase64String(fileData);
- }
-
- #endregion
-
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/DirectoryEntry.js
----------------------------------------------------------------------
diff --git a/www/DirectoryEntry.js b/www/DirectoryEntry.js
deleted file mode 100644
index 8b98283..0000000
--- a/www/DirectoryEntry.js
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var argscheck = require('cordova/argscheck'),
- utils = require('cordova/utils'),
- exec = require('cordova/exec'),
- Entry = require('./Entry'),
- FileError = require('./FileError'),
- DirectoryReader = require('./DirectoryReader');
-
-/**
- * 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)
- */
-var DirectoryEntry = function(name, fullPath, fileSystem, nativeURL) {
- DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL);
-};
-
-utils.extend(DirectoryEntry, Entry);
-
-/**
- * Creates a new DirectoryReader to read entries from this directory
- */
-DirectoryEntry.prototype.createReader = function() {
- return new DirectoryReader(this.toInternalURL());
-};
-
-/**
- * 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 exclusively 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) {
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
- var fs = this.filesystem;
- var win = successCallback && function(result) {
- var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getDirectory", [this.toInternalURL(), path, options]);
-};
-
-/**
- * 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) {
- argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(successCallback, fail, "File", "removeRecursively", [this.toInternalURL()]);
-};
-
-/**
- * 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 exclusively 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) {
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
- var fs = this.filesystem;
- var win = successCallback && function(result) {
- var FileEntry = require('./FileEntry');
- var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getFile", [this.toInternalURL(), path, options]);
-};
-
-module.exports = DirectoryEntry;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/DirectoryReader.js
----------------------------------------------------------------------
diff --git a/www/DirectoryReader.js b/www/DirectoryReader.js
deleted file mode 100644
index 2894c9a..0000000
--- a/www/DirectoryReader.js
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var exec = require('cordova/exec'),
- FileError = require('./FileError') ;
-
-/**
- * An interface that lists the files and directories in a directory.
- */
-function DirectoryReader(localURL) {
- this.localURL = localURL || null;
- this.hasReadEntries = false;
-}
-
-/**
- * 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) {
- // If we've already read and passed on this directory's entries, return an empty list.
- if (this.hasReadEntries) {
- successCallback([]);
- return;
- }
- var reader = this;
- 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 (require('./DirectoryEntry'))();
- }
- else if (result[i].isFile) {
- entry = new (require('./FileEntry'))();
- }
- entry.isDirectory = result[i].isDirectory;
- entry.isFile = result[i].isFile;
- entry.name = result[i].name;
- entry.fullPath = result[i].fullPath;
- entry.filesystem = new (require('./FileSystem'))(result[i].filesystemName);
- entry.nativeURL = result[i].nativeURL;
- retVal.push(entry);
- }
- reader.hasReadEntries = true;
- successCallback(retVal);
- };
- var fail = typeof errorCallback !== 'function' ? null : function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "readEntries", [this.localURL]);
-};
-
-module.exports = DirectoryReader;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/Entry.js
----------------------------------------------------------------------
diff --git a/www/Entry.js b/www/Entry.js
deleted file mode 100644
index d143d32..0000000
--- a/www/Entry.js
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var argscheck = require('cordova/argscheck'),
- exec = require('cordova/exec'),
- FileError = require('./FileError'),
- Metadata = require('./Metadata');
-
-/**
- * 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)
- * @param fileSystem
- * {FileSystem} the filesystem on which this entry resides
- * (readonly)
- * @param nativeURL
- * {DOMString} an alternate URL which can be used by native
- * webview controls, for example media players.
- * (optional, readonly)
- */
-function Entry(isFile, isDirectory, name, fullPath, fileSystem, nativeURL) {
- this.isFile = !!isFile;
- this.isDirectory = !!isDirectory;
- this.name = name || '';
- this.fullPath = fullPath || '';
- this.filesystem = fileSystem || null;
- this.nativeURL = nativeURL || 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) {
- argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);
- var success = successCallback && function(entryMetadata) {
- var metadata = new Metadata(entryMetadata);
- successCallback(metadata);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(success, fail, "File", "getMetadata", [this.toInternalURL()]);
-};
-
-/**
- * Set the metadata of the entry.
- *
- * @param successCallback
- * {Function} is called with a Metadata object
- * @param errorCallback
- * {Function} is called with a FileError
- * @param metadataObject
- * {Object} keys and values to set
- */
-Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
- argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);
- exec(successCallback, errorCallback, "File", "setMetadata", [this.toInternalURL(), metadataObject]);
-};
-
-/**
- * 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) {
- argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- var srcURL = this.toInternalURL(),
- // entry name
- name = newName || this.name,
- success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var fs = entry.filesystemName ? new FileSystem(entry.filesystemName, {name:"", fullPath:"/"}) : this.filesystem;
- var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('org.apache.cordova.file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- // copy
- exec(success, fail, "File", "moveTo", [srcURL, parent.toInternalURL(), name]);
-};
-
-/**
- * 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) {
- argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- var srcURL = this.toInternalURL(),
- // entry name
- name = newName || this.name,
- // success callback
- success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var fs = entry.filesystemName ? new FileSystem(entry.filesystemName, {name:"", fullPath:"/"}) : this.filesystem;
- var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('org.apache.cordova.file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- // copy
- exec(success, fail, "File", "copyTo", [srcURL, parent.toInternalURL(), name]);
-};
-
-/**
- * Return a URL that can be passed across the bridge to identify this entry.
- */
-Entry.prototype.toInternalURL = function() {
- if (this.filesystem && this.filesystem.__format__) {
- return this.filesystem.__format__(this.fullPath);
- }
-};
-
-/**
- * Return a URL that can be used to identify this entry.
- * Use a URL that can be used to as the src attribute of a <video> or
- * <audio> tag. If that is not possible, construct a cdvfile:// URL.
- */
-Entry.prototype.toURL = function() {
- if (this.nativeURL) {
- return this.nativeURL;
- }
- // fullPath attribute may contain the full URL in the case that
- // toInternalURL fails.
- return this.toInternalURL() || "file://localhost" + this.fullPath;
-};
-
-/**
- * Backwards-compatibility: In v1.0.0 - 1.0.2, .toURL would only return a
- * cdvfile:// URL, and this method was necessary to obtain URLs usable by the
- * webview.
- * See CB-6051, CB-6106, CB-6117, CB-6152, CB-6199, CB-6201, CB-6243, CB-6249,
- * and CB-6300.
- */
-Entry.prototype.toNativeURL = function() {
- console.log("DEPRECATED: Update your code to use 'toURL'");
- return this.toURL();
-};
-
-/**
- * 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'");
- return this.toURL();
-};
-
-/**
- * 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) {
- argscheck.checkArgs('FF', 'Entry.remove', arguments);
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(successCallback, fail, "File", "remove", [this.toInternalURL()]);
-};
-
-/**
- * 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) {
- argscheck.checkArgs('FF', 'Entry.getParent', arguments);
- var fs = this.filesystem;
- var win = successCallback && function(result) {
- var DirectoryEntry = require('./DirectoryEntry');
- var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL);
- successCallback(entry);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getParent", [this.toInternalURL()]);
-};
-
-module.exports = Entry;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/File.js
----------------------------------------------------------------------
diff --git a/www/File.js b/www/File.js
deleted file mode 100644
index d080315..0000000
--- a/www/File.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * Constructor.
- * name {DOMString} name of the file, without path information
- * fullPath {DOMString} the full path of the file, including the name
- * type {DOMString} mime type
- * lastModifiedDate {Date} last modified date
- * size {Number} size of the file in bytes
- */
-
-var File = function(name, localURL, type, lastModifiedDate, size){
- this.name = name || '';
- this.localURL = localURL || null;
- this.type = type || null;
- this.lastModifiedDate = lastModifiedDate || null;
- this.size = size || 0;
-
- // These store the absolute start and end for slicing the file.
- this.start = 0;
- this.end = this.size;
-};
-
-/**
- * Returns a "slice" of the file. Since Cordova Files don't contain the actual
- * content, this really returns a File with adjusted start and end.
- * Slices of slices are supported.
- * start {Number} The index at which to start the slice (inclusive).
- * end {Number} The index at which to end the slice (exclusive).
- */
-File.prototype.slice = function(start, end) {
- var size = this.end - this.start;
- var newStart = 0;
- var newEnd = size;
- if (arguments.length) {
- if (start < 0) {
- newStart = Math.max(size + start, 0);
- } else {
- newStart = Math.min(size, start);
- }
- }
-
- if (arguments.length >= 2) {
- if (end < 0) {
- newEnd = Math.max(size + end, 0);
- } else {
- newEnd = Math.min(end, size);
- }
- }
-
- var newFile = new File(this.name, this.localURL, this.type, this.lastModifiedDate, this.size);
- newFile.start = this.start + newStart;
- newFile.end = this.start + newEnd;
- return newFile;
-};
-
-
-module.exports = File;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileEntry.js
----------------------------------------------------------------------
diff --git a/www/FileEntry.js b/www/FileEntry.js
deleted file mode 100644
index 59a9dc3..0000000
--- a/www/FileEntry.js
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var utils = require('cordova/utils'),
- exec = require('cordova/exec'),
- Entry = require('./Entry'),
- FileWriter = require('./FileWriter'),
- File = require('./File'),
- FileError = require('./FileError');
-
-/**
- * An interface representing a file on the file system.
- *
- * {boolean} isFile always true (readonly)
- * {boolean} isDirectory always false (readonly)
- * {DOMString} name of the file, excluding the path leading to it (readonly)
- * {DOMString} fullPath the absolute full path to the file (readonly)
- * {FileSystem} filesystem on which the file resides (readonly)
- */
-var FileEntry = function(name, fullPath, fileSystem, nativeURL) {
- FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]);
-};
-
-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.localURL === null || writer.localURL === "") {
- errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR));
- } else {
- successCallback && 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 localURL = this.toInternalURL();
- var win = successCallback && function(f) {
- var file = new File(f.name, localURL, f.type, f.lastModifiedDate, f.size);
- successCallback(file);
- };
- var fail = errorCallback && function(code) {
- errorCallback(new FileError(code));
- };
- exec(win, fail, "File", "getFileMetadata", [localURL]);
-};
-
-
-module.exports = FileEntry;
[2/8] CB-6521: Remove development branch
Posted by ia...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileError.js
----------------------------------------------------------------------
diff --git a/www/FileError.js b/www/FileError.js
deleted file mode 100644
index 6507921..0000000
--- a/www/FileError.js
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * FileError
- */
-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;
-
-module.exports = FileError;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileReader.js
----------------------------------------------------------------------
diff --git a/www/FileReader.js b/www/FileReader.js
deleted file mode 100644
index c0d5849..0000000
--- a/www/FileReader.js
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var exec = require('cordova/exec'),
- modulemapper = require('cordova/modulemapper'),
- utils = require('cordova/utils'),
- File = require('./File'),
- FileError = require('./FileError'),
- ProgressEvent = require('./ProgressEvent'),
- origFileReader = modulemapper.getOriginalSymbol(this, 'FileReader');
-
-/**
- * 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
- */
-var FileReader = function() {
- this._readyState = 0;
- this._error = null;
- this._result = null;
- this._localURL = '';
- this._realReader = origFileReader ? new origFileReader() : {};
-};
-
-// States
-FileReader.EMPTY = 0;
-FileReader.LOADING = 1;
-FileReader.DONE = 2;
-
-utils.defineGetter(FileReader.prototype, 'readyState', function() {
- return this._localURL ? this._readyState : this._realReader.readyState;
-});
-
-utils.defineGetter(FileReader.prototype, 'error', function() {
- return this._localURL ? this._error: this._realReader.error;
-});
-
-utils.defineGetter(FileReader.prototype, 'result', function() {
- return this._localURL ? this._result: this._realReader.result;
-});
-
-function defineEvent(eventName) {
- utils.defineGetterSetter(FileReader.prototype, eventName, function() {
- return this._realReader[eventName] || null;
- }, function(value) {
- this._realReader[eventName] = value;
- });
-}
-defineEvent('onloadstart'); // When the read starts.
-defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total)
-defineEvent('onload'); // When the read has successfully completed.
-defineEvent('onerror'); // When the read has failed (see errors).
-defineEvent('onloadend'); // When the request has completed (either in success or failure).
-defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method.
-
-function initRead(reader, file) {
- // Already loading something
- if (reader.readyState == FileReader.LOADING) {
- throw new FileError(FileError.INVALID_STATE_ERR);
- }
-
- reader._result = null;
- reader._error = null;
- reader._readyState = FileReader.LOADING;
-
- if (typeof file.localURL == 'string') {
- reader._localURL = file.localURL;
- } else {
- reader._localURL = '';
- return true;
- }
-
- reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader}));
-}
-
-/**
- * Abort reading file.
- */
-FileReader.prototype.abort = function() {
- if (origFileReader && !this._localURL) {
- return this._realReader.abort();
- }
- 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) {
- if (initRead(this, file)) {
- return this._realReader.readAsText(file, encoding);
- }
-
- // Default encoding is UTF-8
- var enc = encoding ? encoding : "UTF-8";
- var me = this;
- var execArgs = [this._localURL, enc, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- 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
- 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}));
- }
- }, "File", "readAsText", execArgs);
-};
-
-
-/**
- * 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) {
- if (initRead(this, file)) {
- return this._realReader.readAsDataURL(file);
- }
-
- var me = this;
- var execArgs = [this._localURL, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- 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
- 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}));
- }
- }, "File", "readAsDataURL", execArgs);
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsBinaryString = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsBinaryString(file);
- }
-
- var me = this;
- var execArgs = [this._localURL, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- 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
- 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}));
- }
- }, "File", "readAsBinaryString", execArgs);
-};
-
-/**
- * Read file and return data as a binary data.
- *
- * @param file {File} File object containing file properties
- */
-FileReader.prototype.readAsArrayBuffer = function(file) {
- if (initRead(this, file)) {
- return this._realReader.readAsArrayBuffer(file);
- }
-
- var me = this;
- var execArgs = [this._localURL, file.start, file.end];
-
- // Read file
- exec(
- // Success callback
- function(r) {
- // If DONE (cancelled), then don't do anything
- if (me._readyState === FileReader.DONE) {
- return;
- }
-
- // DONE state
- me._readyState = FileReader.DONE;
-
- 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
- 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}));
- }
- }, "File", "readAsArrayBuffer", execArgs);
-};
-
-module.exports = FileReader;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileSystem.js
----------------------------------------------------------------------
diff --git a/www/FileSystem.js b/www/FileSystem.js
deleted file mode 100644
index 7ac4671..0000000
--- a/www/FileSystem.js
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var DirectoryEntry = require('./DirectoryEntry');
-
-/**
- * An interface representing a file system
- *
- * @constructor
- * {DOMString} name the unique name of the file system (readonly)
- * {DirectoryEntry} root directory of the file system (readonly)
- */
-var FileSystem = function(name, root) {
- this.name = name || null;
- if (root) {
- this.root = new DirectoryEntry(root.name, root.fullPath, this);
- } else {
- this.root = new DirectoryEntry(this.name, '/', this);
- }
-};
-
-FileSystem.prototype.__format__ = function(fullPath) {
- return fullPath;
-};
-
-FileSystem.prototype.toJSON = function() {
- return "<FileSystem: " + this.name + ">";
-};
-
-module.exports = FileSystem;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileUploadOptions.js
----------------------------------------------------------------------
diff --git a/www/FileUploadOptions.js b/www/FileUploadOptions.js
deleted file mode 100644
index b2977de..0000000
--- a/www/FileUploadOptions.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * 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.
- * @param headers {Object} Keys are header names, values are header values. Multiple
- * headers of the same name are not supported.
- */
-var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) {
- this.fileKey = fileKey || null;
- this.fileName = fileName || null;
- this.mimeType = mimeType || null;
- this.params = params || null;
- this.headers = headers || null;
- this.httpMethod = httpMethod || null;
-};
-
-module.exports = FileUploadOptions;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileUploadResult.js
----------------------------------------------------------------------
diff --git a/www/FileUploadResult.js b/www/FileUploadResult.js
deleted file mode 100644
index 4f2e33e..0000000
--- a/www/FileUploadResult.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * FileUploadResult
- * @constructor
- */
-module.exports = function FileUploadResult(size, code, content) {
- this.bytesSent = size;
- this.responseCode = code;
- this.response = content;
- };
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/FileWriter.js
----------------------------------------------------------------------
diff --git a/www/FileWriter.js b/www/FileWriter.js
deleted file mode 100644
index 786e994..0000000
--- a/www/FileWriter.js
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var exec = require('cordova/exec'),
- FileError = require('./FileError'),
- ProgressEvent = require('./ProgressEvent');
-
-/**
- * This class writes to the mobile device file system.
- *
- * For Android:
- * The root directory is the root of the file system.
- * To write to the SD card, the file name is "sdcard/my_file.txt"
- *
- * @constructor
- * @param file {File} File object containing file properties
- * @param append if true write to the end of the file, otherwise overwrite the file
- */
-var FileWriter = function(file) {
- this.fileName = "";
- this.length = 0;
- if (file) {
- this.localURL = file.localURL || 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 data text or blob to be written
- */
-FileWriter.prototype.write = function(data) {
-
- var that=this;
- var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');
- var isBinary;
-
- // Check to see if the incoming data is a blob
- if (data instanceof File || (supportsBinary && data instanceof Blob)) {
- var fileReader = new FileReader();
- fileReader.onload = function() {
- // Call this method again, with the arraybuffer as argument
- FileWriter.prototype.write.call(that, this.result);
- };
- if (supportsBinary) {
- fileReader.readAsArrayBuffer(data);
- } else {
- fileReader.readAsText(data);
- }
- return;
- }
-
- // Mark data type for safer transport over the binary bridge
- isBinary = supportsBinary && (data instanceof ArrayBuffer);
- if (isBinary && ['windowsphone', 'windows8'].indexOf(cordova.platformId) >= 0) {
- // create a plain array, using the keys from the Uint8Array view so that we can serialize it
- data = Array.apply(null, new Uint8Array(data));
- }
-
- // 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
- exec(
- // Success callback
- 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
- 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}));
- }
- }, "File", "write", [this.localURL, data, this.position, isBinary]);
-};
-
-/**
- * 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 than 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
- exec(
- // Success callback
- 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
- 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}));
- }
- }, "File", "truncate", [this.localURL, size]);
-};
-
-module.exports = FileWriter;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/Flags.js
----------------------------------------------------------------------
diff --git a/www/Flags.js b/www/Flags.js
deleted file mode 100644
index a9ae6da..0000000
--- a/www/Flags.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * Supplies arguments to methods that lookup or create files and directories.
- *
- * @param create
- * {boolean} file or directory if it doesn't exist
- * @param exclusive
- * {boolean} used with create; if true the command will fail if
- * target path exists
- */
-function Flags(create, exclusive) {
- this.create = create || false;
- this.exclusive = exclusive || false;
-}
-
-module.exports = Flags;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/LocalFileSystem.js
----------------------------------------------------------------------
diff --git a/www/LocalFileSystem.js b/www/LocalFileSystem.js
deleted file mode 100644
index 1e8f2ee..0000000
--- a/www/LocalFileSystem.js
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-exports.TEMPORARY = 0;
-exports.PERSISTENT = 1;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/Metadata.js
----------------------------------------------------------------------
diff --git a/www/Metadata.js b/www/Metadata.js
deleted file mode 100644
index f95c44c..0000000
--- a/www/Metadata.js
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-/**
- * Information about the state of the file or directory
- *
- * {Date} modificationTime (readonly)
- */
-var Metadata = function(metadata) {
- if (typeof metadata == "object") {
- this.modificationTime = new Date(metadata.modificationTime);
- this.size = metadata.size || 0;
- } else if (typeof metadata == "undefined") {
- this.modificationTime = null;
- this.size = 0;
- } else {
- /* Backwards compatiblity with platforms that only return a timestamp */
- this.modificationTime = new Date(metadata);
- }
-};
-
-module.exports = Metadata;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/ProgressEvent.js
----------------------------------------------------------------------
diff --git a/www/ProgressEvent.js b/www/ProgressEvent.js
deleted file mode 100644
index f176f80..0000000
--- a/www/ProgressEvent.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-// If ProgressEvent exists in global context, use it already, otherwise use our own polyfill
-// Feature test: See if we can instantiate a native ProgressEvent;
-// if so, use that approach,
-// otherwise fill-in with our own implementation.
-//
-// NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview.
-var ProgressEvent = (function() {
- /*
- var createEvent = function(data) {
- var event = document.createEvent('Events');
- event.initEvent('ProgressEvent', false, false);
- if (data) {
- for (var i in data) {
- if (data.hasOwnProperty(i)) {
- event[i] = data[i];
- }
- }
- if (data.target) {
- // TODO: cannot call <some_custom_object>.dispatchEvent
- // need to first figure out how to implement EventTarget
- }
- }
- return event;
- };
- try {
- var ev = createEvent({type:"abort",target:document});
- return function ProgressEvent(type, data) {
- data.type = type;
- return createEvent(data);
- };
- } catch(e){
- */
- 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;
- };
- //}
-})();
-
-module.exports = ProgressEvent;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/android/FileSystem.js
----------------------------------------------------------------------
diff --git a/www/android/FileSystem.js b/www/android/FileSystem.js
deleted file mode 100644
index fde9c7a..0000000
--- a/www/android/FileSystem.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-FILESYSTEM_PROTOCOL = "cdvfile";
-
-module.exports = {
- __format__: function(fullPath) {
- if (this.name === 'content') {
- return 'content:/' + fullPath;
- }
- var path = ('/'+this.name+(fullPath[0]==='/'?'':'/')+encodeURI(fullPath)).replace('//','/');
- return FILESYSTEM_PROTOCOL + '://localhost' + path;
- }
-};
-
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/DirectoryEntry.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/DirectoryEntry.js b/www/blackberry10/DirectoryEntry.js
deleted file mode 100644
index 64ded02..0000000
--- a/www/blackberry10/DirectoryEntry.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var argscheck = require('cordova/argscheck'),
- utils = require('cordova/utils'),
- Entry = require('./BB10Entry'),
- FileError = require('./FileError'),
- DirectoryReader = require('./BB10DirectoryReader'),
- fileUtils = require('./BB10Utils'),
- DirectoryEntry = function (name, fullPath, fileSystem) {
- DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem);
- };
-
-if (!window.requestAnimationFrame) {
- window.requestAnimationFrame = function (callback) { callback(); };
-}
-
-utils.extend(DirectoryEntry, Entry);
-
-DirectoryEntry.prototype.createReader = function () {
- return new DirectoryReader(this.fullPath);
-};
-
-DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {
- var currentPath = this.nativeEntry.fullPath,
- that = this,
- fullPath;
-
- if (path.indexOf("/") === 0) {
- fullPath = path;
- } else {
- fullPath = currentPath + "/" + path;
- }
-
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments);
-
- if (fileUtils.isOutsideSandbox(fullPath)) {
- cordova.exec(function () {
- window.requestAnimationFrame(function () {
- window.webkitRequestFileSystem(window.PERSISTENT, that.filesystem._size, function (fs) {
- fs.root.getDirectory(fullPath, options, function (entry) {
- successCallback(fileUtils.createEntry(entry));
- }, errorCallback);
- }, errorCallback);
- });
- }, errorCallback, "org.apache.cordova.file", "setSandbox", [false]);
- } else {
- cordova.exec(function () {
- window.requestAnimationFrame(function () {
- window.webkitRequestFileSystem(fileUtils.getFileSystemName(that.filesystem) === "persistent" ? window.PERSISTENT : window.TEMPORARY, that.filesystem._size, function (fs) {
- fs.root.getDirectory(fullPath, options, function (entry) {
- successCallback(fileUtils.createEntry(entry));
- }, errorCallback);
- }, errorCallback);
- });
- }, errorCallback, "org.apache.cordova.file", "setSandbox", [true]);
- }
-};
-
-DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments);
- this.nativeEntry.removeRecursively(successCallback, errorCallback);
-};
-
-DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {
- var currentPath = this.nativeEntry.fullPath,
- that = this,
- fullPath;
-
- if (path.indexOf("/") === 0) {
- fullPath = path;
- } else {
- fullPath = currentPath + "/" + path;
- }
-
- argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments);
-
- if (fileUtils.isOutsideSandbox(fullPath)) {
- cordova.exec(function () {
- window.requestAnimationFrame(function () {
- window.webkitRequestFileSystem(window.PERSISTENT, that.filesystem._size, function (fs) {
- fs.root.getFile(fullPath, options, function (entry) {
- successCallback(fileUtils.createEntry(entry));
- }, errorCallback);
- }, errorCallback);
- });
- }, errorCallback, "org.apache.cordova.file", "setSandbox", [false]);
- } else {
- cordova.exec(function () {
- window.requestAnimationFrame(function () {
- window.webkitRequestFileSystem(fileUtils.getFileSystemName(that.filesystem) === "persistent" ? window.PERSISTENT: window.TEMPORARY, that.filesystem._size, function (fs) {
- fs.root.getFile(fullPath, options, function (entry) {
- successCallback(fileUtils.createEntry(entry));
- }, errorCallback);
- }, errorCallback);
- });
- }, errorCallback, "org.apache.cordova.file", "setSandbox", [true]);
- }
-};
-
-module.exports = DirectoryEntry;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/DirectoryReader.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/DirectoryReader.js b/www/blackberry10/DirectoryReader.js
deleted file mode 100644
index 6aa3d73..0000000
--- a/www/blackberry10/DirectoryReader.js
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var FileError = require('./FileError'),
- fileUtils = require('./BB10Utils');
-
-function DirectoryReader(path) {
- this.path = path;
- this.nativeReader = null;
-}
-
-DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) {
- var self = this,
- win = typeof successCallback !== 'function' ? null : function(result) {
- var retVal = [];
- for (var i=0; i<result.length; i++) {
- retVal.push(fileUtils.createEntry(result[i]));
- }
- successCallback(retVal);
- },
- fail = typeof errorCallback !== 'function' ? null : function(code) {
- errorCallback(new FileError(code));
- };
- if (this.nativeReader) {
- this.nativeReader.readEntries(win, fail);
- } else {
- resolveLocalFileSystemURI("filesystem:local:///persistent/" + this.path, function (entry) {
- self.nativeReader = entry.nativeEntry.createReader()
- self.nativeReader.readEntries(win, fail);
- }, function () {
- fail(FileError.NOT_FOUND_ERR);
- });
- }
-};
-
-module.exports = DirectoryReader;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/Entry.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/Entry.js b/www/blackberry10/Entry.js
deleted file mode 100644
index 7554e06..0000000
--- a/www/blackberry10/Entry.js
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var argscheck = require('cordova/argscheck'),
- FileError = require('./FileError'),
- Metadata = require('./Metadata'),
- fileUtils = require('./BB10Utils');
-
-function Entry(isFile, isDirectory, name, fullPath, fileSystem) {
- var strippedPath;
- if (fullPath && fullPath.charAt(fullPath.length - 1) === '/') {
- strippedPath = fullPath.slice(0, -1);
- }
- this.isFile = !!isFile;
- this.isDirectory = !!isDirectory;
- this.name = name || '';
- this.fullPath = typeof strippedPath !== "undefined" ? strippedPath : (fullPath || '');
- this.filesystem = fileSystem || null;
-}
-
-Entry.prototype.getMetadata = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.getMetadata', arguments);
- var success = function(lastModified) {
- var metadata = new Metadata(lastModified);
- if (typeof successCallback === 'function') {
- successCallback(metadata);
- }
- };
- this.nativeEntry.getMetadata(success, errorCallback);
-};
-
-Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) {
- argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments);
- errorCallback("Not supported by platform");
-};
-
-Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) {
- argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments);
- var srcPath = this.fullPath,
- name = newName || this.name,
- success = function(entry) {
- if (entry) {
- if (typeof successCallback === 'function') {
- successCallback(fileUtils.createEntry(entry));
- }
- }
- else {
- if (typeof errorCallback === 'function') {
- errorCallback(new FileError(FileError.NOT_FOUND_ERR));
- }
- }
- };
- this.nativeEntry.moveTo(parent.nativeEntry, newName, success, errorCallback);
-};
-
-
-Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) {
- argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments);
- var srcPath = this.fullPath,
- name = newName || this.name,
- success = function(entry) {
- if (entry) {
- if (typeof successCallback === 'function') {
- successCallback(fileUtils.createEntry(entry));
- }
- }
- else {
- if (typeof errorCallback === 'function') {
- errorCallback(new FileError(FileError.NOT_FOUND_ERR));
- }
- }
- };
- this.nativeEntry.copyTo(parent.nativeEntry, newName, success, errorCallback);
-};
-
-Entry.prototype.toURL = function() {
- return "file://" + this.nativeEntry.fullPath;
-};
-
-Entry.prototype.toURI = function(mimeType) {
- console.log("DEPRECATED: Update your code to use 'toURL'");
- return this.toURL();
-};
-
-Entry.prototype.remove = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.remove', arguments);
- this.nativeEntry.remove(successCallback, errorCallback);
-};
-
-Entry.prototype.getParent = function(successCallback, errorCallback) {
- argscheck.checkArgs('FF', 'Entry.getParent', arguments);
- var win = successCallback && function(result) {
- successCallback(fileUtils.createEntry(result));
- };
- this.nativeEntry.getParent(win, errorCallback);
-};
-
-module.exports = Entry;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/File.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/File.js b/www/blackberry10/File.js
deleted file mode 100644
index 7ba9734..0000000
--- a/www/blackberry10/File.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var fileUtils = require('./BB10Utils');
-
-/**
- * Constructor.
- * name {DOMString} name of the file, without path information
- * fullPath {DOMString} the full path of the file, including the name
- * type {DOMString} mime type
- * lastModifiedDate {Date} last modified date
- * size {Number} size of the file in bytes
- */
-
-var File = function(name, fullPath, type, lastModifiedDate, size){
- this.name = name || '';
- this.fullPath = fullPath || null;
- this.type = type || null;
- this.lastModifiedDate = lastModifiedDate || null;
- this.size = size || 0;
-
- // These store the absolute start and end for slicing the file.
- this.start = 0;
- this.end = this.size;
-};
-
-/**
- * Returns a "slice" of the file.
- * Slices of slices are supported.
- * start {Number} The index at which to start the slice (inclusive).
- * end {Number} The index at which to end the slice (exclusive).
- */
-File.prototype.slice = function(start, end) {
- return fileUtils.createFile(this.nativeFile.slice(start, end));
-};
-
-
-module.exports = File;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/FileEntry.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/FileEntry.js b/www/blackberry10/FileEntry.js
deleted file mode 100644
index b358d71..0000000
--- a/www/blackberry10/FileEntry.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var utils = require('cordova/utils'),
- Entry = require('./BB10Entry'),
- FileWriter = require('./BB10FileWriter'),
- File = require('./BB10File'),
- fileUtils = require('./BB10Utils'),
- FileError = require('./FileError'),
- FileEntry = function (name, fullPath, fileSystem) {
- FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem]);
- };
-
-utils.extend(FileEntry, Entry);
-
-FileEntry.prototype.createWriter = function(successCallback, errorCallback) {
- this.file(function (file) {
- successCallback(new FileWriter(file));
- }, errorCallback);
-};
-
-FileEntry.prototype.file = function(successCallback, errorCallback) {
- var fullPath = this.fullPath,
- success = function (file) {
- file.fullPath = fullPath;
- successCallback(fileUtils.createFile(file));
- };
- this.nativeEntry.file(success, errorCallback);
-};
-
-module.exports = FileEntry;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/FileReader.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/FileReader.js b/www/blackberry10/FileReader.js
deleted file mode 100644
index a3943ba..0000000
--- a/www/blackberry10/FileReader.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var origFileReader = window.FileReader,
- fileUtils = require('./BB10Utils'),
- utils = require('cordova/utils');
-
-var FileReader = function() {
- this.nativeReader = new origFileReader();
-};
-
-utils.defineGetter(FileReader.prototype, 'readyState', function() {
- return this.nativeReader.readyState;
-});
-
-utils.defineGetter(FileReader.prototype, 'error', function() {
- return this.nativeReader.error;
-});
-
-utils.defineGetter(FileReader.prototype, 'result', function() {
- return this.nativeReader.result;
-});
-
-function defineEvent(eventName) {
- utils.defineGetterSetter(FileReader.prototype, eventName, function() {
- return this.nativeReader[eventName] || null;
- }, function(value) {
- this.nativeReader[eventName] = value;
- });
-}
-
-defineEvent('onabort');
-defineEvent('onerror');
-defineEvent('onload');
-defineEvent('onloadend');
-defineEvent('onloadstart');
-defineEvent('onprogress');
-
-FileReader.prototype.abort = function() {
- return this.nativeReader.abort();
-};
-
-function read(method, context, file, encoding) {
- if (file.fullPath) {
- resolveLocalFileSystemURI(file.fullPath, function (entry) {
- entry.nativeEntry.file(function (nativeFile) {
- context.nativeReader[method].call(context.nativeReader, nativeFile, encoding);
- }, context.onerror);
- }, context.onerror);
- } else {
- context.nativeReader[method](file, encoding);
- }
-}
-
-FileReader.prototype.readAsText = function(file, encoding) {
- read("readAsText", this, file, encoding);
-};
-
-FileReader.prototype.readAsDataURL = function(file) {
- read("readAsDataURL", this, file);
-};
-
-FileReader.prototype.readAsBinaryString = function(file) {
- read("readAsBinaryString", this, file);
-};
-
-FileReader.prototype.readAsArrayBuffer = function(file) {
- read("readAsArrayBuffer", this, file);
-};
-
-window.FileReader = FileReader;
-module.exports = FileReader;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/FileSystem.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/FileSystem.js b/www/blackberry10/FileSystem.js
deleted file mode 100644
index d1432d6..0000000
--- a/www/blackberry10/FileSystem.js
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-module.exports = function(name, root) {
- this.name = name || null;
- if (root) {
- this.root = root;
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/FileWriter.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/FileWriter.js b/www/blackberry10/FileWriter.js
deleted file mode 100644
index d50efc5..0000000
--- a/www/blackberry10/FileWriter.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var FileError = require('./FileError'),
- ProgressEvent = require('./ProgressEvent'),
- fileUtils = require('./BB10Utils'),
- utils = require('cordova/utils');
-
-function FileWriter (file) {
- var that = this;
- this.file = file;
- this.events = {};
- this.pending = [];
- resolveLocalFileSystemURI(file.fullPath, function (entry) {
- entry.nativeEntry.createWriter(function (writer) {
- var i,
- event;
- that.nativeWriter = writer;
- for (event in that.events) {
- if (that.events.hasOwnProperty(event)) {
- that.nativeWriter[event] = that.events[event];
- }
- }
- for (i = 0; i < that.pending.length; i++) {
- that.pending[i]();
- }
- });
- });
- this.events = {};
- this.pending = [];
-}
-
-utils.defineGetter(FileWriter.prototype, 'error', function() {
- return this.nativeWriter ? this.nativeWriter.error : null;
-});
-
-utils.defineGetter(FileWriter.prototype, 'fileName', function() {
- return this.nativeWriter ? this.nativeWriter.fileName : this.file.name;
-});
-
-utils.defineGetter(FileWriter.prototype, 'length', function() {
- return this.nativeWriter ? this.nativeWriter.length : this.file.size;
-});
-
-utils.defineGetter(FileWriter.prototype, 'position', function() {
- return this.nativeWriter ? this.nativeWriter.position : 0;
-});
-
-utils.defineGetter(FileWriter.prototype, 'readyState', function() {
- return this.nativeWriter ? this.nativeWriter.readyState : 0;
-});
-
-function defineEvent(eventName) {
- utils.defineGetterSetter(FileWriter.prototype, eventName, function() {
- return this.nativeWriter ? this.nativeWriter[eventName] || null : this.events[eventName] || null;
- }, function(value) {
- if (this.nativeWriter) {
- this.nativeWriter[eventName] = value;
- }
- else {
- this.events[eventName] = value;
- }
- });
-}
-
-defineEvent('onabort');
-defineEvent('onerror');
-defineEvent('onprogress');
-defineEvent('onwrite');
-defineEvent('onwriteend');
-defineEvent('onwritestart');
-
-FileWriter.prototype.abort = function() {
- this.nativeWriter.abort();
-};
-
-FileWriter.prototype.write = function(text) {
- var that = this,
- op = function () {
- that.nativeWriter.write(new Blob([text]));
- };
- this.nativeWriter ? op() : this.pending.push(op);
-
-};
-
-FileWriter.prototype.seek = function(offset) {
- var that = this,
- op = function () {
- that.nativeWriter.seek(offset);
- };
- this.nativeWriter ? op() : this.pending.push(op);
-};
-
-FileWriter.prototype.truncate = function(size) {
- var that = this,
- op = function () {
- that.nativeWriter.truncate(size);
- };
- this.nativeWriter ? op() : this.pending.push(op);
-};
-
-module.exports = FileWriter;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/fileUtils.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/fileUtils.js b/www/blackberry10/fileUtils.js
deleted file mode 100644
index 740669c..0000000
--- a/www/blackberry10/fileUtils.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-function convertPath(url) {
- return decodeURI(url).substring(11).replace(/\/$/, '');
-}
-
-module.exports = {
- createEntry: function (entry) {
- var cordovaEntry;
- if (entry.isFile) {
- cordovaEntry = new window.FileEntry(entry.name, entry.fullPath, entry.filesystem);
- } else {
- cordovaEntry = new window.DirectoryEntry(entry.name, entry.fullPath, entry.filesystem);
- }
- cordovaEntry.nativeEntry = entry;
- return cordovaEntry;
- },
-
- createFile: function (file) {
- var cordovaFile = new File(file.name, file.fullPath, file.type, file.lastModifiedDate, file.size);
- cordovaFile.nativeFile = file;
- cordovaFile.fullPath = file.fullPath;
- return cordovaFile;
- },
-
- getFileSystemName: function (fs) {
- return ((fs.name.indexOf('Persistent') != -1) || (fs.name === "persistent")) ? 'persistent' : 'temporary';
- },
-
- isOutsideSandbox: function (path) {
- return (path.indexOf("accounts/1000") !== -1);
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/requestFileSystem.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/requestFileSystem.js b/www/blackberry10/requestFileSystem.js
deleted file mode 100644
index 9180801..0000000
--- a/www/blackberry10/requestFileSystem.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var fileUtils = require('./BB10Utils'),
- FileError = require('./FileError'),
- FileSystem = require('./BB10FileSystem');
-
-if (!window.requestAnimationFrame) {
- window.requestAnimationFrame = function (callback) { callback(); };
-}
-
-module.exports = function (type, size, success, fail) {
- var cordovaFs,
- cordovaFsRoot;
- if (size >= 1000000000000000) {
- if (typeof fail === "function") {
- fail(new FileError(FileError.QUOTA_EXCEEDED_ERR));
- }
- } else if (type !== 1 && type !== 0) {
- if (typeof fail === "function") {
- fail(new FileError(FileError.SYNTAX_ERR));
- }
- } else {
- cordova.exec(function () {
- window.requestAnimationFrame(function () {
- window.webkitRequestFileSystem(type, size, function (fs) {
- cordovaFsRoot = fileUtils.createEntry(fs.root);
- cordovaFs = new FileSystem(fileUtils.getFileSystemName(fs), cordovaFsRoot);
- cordovaFsRoot.filesystem = cordovaFs;
- cordovaFs._size = size;
- success(cordovaFs);
- }, function (error) {
- if (typeof fail === "function") {
- fail(new FileError(error));
- }
- });
- });
- }, fail, "org.apache.cordova.file", "setSandbox", [true]);
-
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/resolveLocalFileSystemURI.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/resolveLocalFileSystemURI.js b/www/blackberry10/resolveLocalFileSystemURI.js
deleted file mode 100644
index 6decdda..0000000
--- a/www/blackberry10/resolveLocalFileSystemURI.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-module.exports = function () {
- console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.");
- window.resolveLocalFileSystemURL.apply(this, arguments);
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/blackberry10/resolveLocalFileSystemURL.js
----------------------------------------------------------------------
diff --git a/www/blackberry10/resolveLocalFileSystemURL.js b/www/blackberry10/resolveLocalFileSystemURL.js
deleted file mode 100644
index db64615..0000000
--- a/www/blackberry10/resolveLocalFileSystemURL.js
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var fileUtils = require('./BB10Utils'),
- FileError = require('./FileError');
-
-if (!window.requestAnimationFrame) {
- window.requestAnimationFrame = function (callback) { callback(); };
-}
-
-module.exports = function (uri, success, fail) {
-
- var decodedURI = decodeURI(uri).replace(/filesystem:/, '').replace(/file:\/\//, ''),
- failNotFound = function () {
- if (fail) {
- fail(FileError.NOT_FOUND_ERR);
- }
- },
- resolveURI = function () {
- window.requestAnimationFrame(function () {
- window.webkitRequestFileSystem(
- window.PERSISTENT,
- 50*1024*1024,
- function (fs) {
- var op = decodedURI.slice(-1) === '/' ? 'getDirectory' : 'getFile';
- fs.root[op](
- decodedURI,
- { create: false },
- function (entry) {
- success(fileUtils.createEntry(entry));
- },
- failNotFound
- );
- },
- failNotFound
- );
- });
- };
-
- if (decodedURI.substring(0, 8) === 'local://') {
- cordova.exec(
- function (path) {
- decodedURI = path;
- resolveURI();
- },
- failNotFound,
- 'org.apache.cordova.file',
- 'resolveLocalPath',
- [decodedURI]
- );
- } else {
- cordova.exec(
- resolveURI,
- failNotFound,
- 'org.apache.cordova.file',
- 'setSandbox',
- [!fileUtils.isOutsideSandbox(decodedURI)]
- );
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/ios/FileSystem.js
----------------------------------------------------------------------
diff --git a/www/ios/FileSystem.js b/www/ios/FileSystem.js
deleted file mode 100644
index b11d58f..0000000
--- a/www/ios/FileSystem.js
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-FILESYSTEM_PROTOCOL = "cdvfile";
-
-module.exports = {
- __format__: function(fullPath) {
- var path = ('/'+this.name+(fullPath[0]==='/'?'':'/')+encodeURI(fullPath)).replace('//','/');
- return FILESYSTEM_PROTOCOL + '://localhost' + path;
- }
-};
-
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/requestFileSystem.js
----------------------------------------------------------------------
diff --git a/www/requestFileSystem.js b/www/requestFileSystem.js
deleted file mode 100644
index 7a1cc8f..0000000
--- a/www/requestFileSystem.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var argscheck = require('cordova/argscheck'),
- FileError = require('./FileError'),
- FileSystem = require('./FileSystem'),
- exec = require('cordova/exec');
-
-/**
- * Request a file system in which to store application data.
- * @param type local file system type
- * @param size indicates how much storage space, in bytes, the application expects to need
- * @param successCallback invoked with a FileSystem object
- * @param errorCallback invoked if error occurs retrieving file system
- */
-var requestFileSystem = function(type, size, successCallback, errorCallback) {
- argscheck.checkArgs('nnFF', 'requestFileSystem', arguments);
- var fail = function(code) {
- errorCallback && errorCallback(new FileError(code));
- };
-
- if (type < 0) {
- fail(FileError.SYNTAX_ERR);
- } else {
- // if successful, return a FileSystem object
- var success = function(file_system) {
- if (file_system) {
- if (successCallback) {
- // 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);
- }
- };
- exec(success, fail, "File", "requestFileSystem", [type, size]);
- }
-};
-
-module.exports = requestFileSystem;
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/resolveLocalFileSystemURI.js
----------------------------------------------------------------------
diff --git a/www/resolveLocalFileSystemURI.js b/www/resolveLocalFileSystemURI.js
deleted file mode 100644
index f2fd105..0000000
--- a/www/resolveLocalFileSystemURI.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var argscheck = require('cordova/argscheck'),
- DirectoryEntry = require('./DirectoryEntry'),
- FileEntry = require('./FileEntry'),
- FileError = require('./FileError'),
- exec = require('cordova/exec');
-
-/**
- * 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
- */
-module.exports.resolveLocalFileSystemURL = function(uri, successCallback, errorCallback) {
- argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments);
- // error callback
- var fail = function(error) {
- errorCallback && errorCallback(new FileError(error));
- };
- // sanity check for 'not:valid:filename'
- if(!uri || uri.split(":").length > 2) {
- setTimeout( function() {
- fail(FileError.ENCODING_ERR);
- },0);
- return;
- }
- // if successful, return either a file or directory entry
- var success = function(entry) {
- if (entry) {
- if (successCallback) {
- // create appropriate Entry object
- var fsName = entry.filesystemName || (entry.filesystem == window.PERSISTENT ? 'persistent' : 'temporary');
- var fs = new FileSystem(fsName, {name:"", fullPath:"/"});
- var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL);
- successCallback(result);
- }
- }
- else {
- // no Entry object returned
- fail(FileError.NOT_FOUND_ERR);
- }
- };
-
- exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]);
-};
-module.exports.resolveLocalFileSystemURI = function() {
- console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead.");
- module.exports.resolveLocalFileSystemURL.apply(this, arguments);
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/ubuntu/DirectoryEntry.js
----------------------------------------------------------------------
diff --git a/www/ubuntu/DirectoryEntry.js b/www/ubuntu/DirectoryEntry.js
deleted file mode 100644
index 80949f0..0000000
--- a/www/ubuntu/DirectoryEntry.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-module.exports = {
- createReader: function() {
- return new DirectoryReader(this.fullPath);
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/ubuntu/Entry.js
----------------------------------------------------------------------
diff --git a/www/ubuntu/Entry.js b/www/ubuntu/Entry.js
deleted file mode 100644
index bb8d43c..0000000
--- a/www/ubuntu/Entry.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-module.exports = {
- toURL:function() {
- // TODO: refactor path in a cross-platform way so we can eliminate
- // these kinds of platform-specific hacks.
- return "file://localhost" + this.fullPath;
- },
- toURI: function() {
- console.log("DEPRECATED: Update your code to use 'toURL'");
- return "file://localhost" + this.fullPath;
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/www/ubuntu/FileWriter.js
----------------------------------------------------------------------
diff --git a/www/ubuntu/FileWriter.js b/www/ubuntu/FileWriter.js
deleted file mode 100644
index a75506b..0000000
--- a/www/ubuntu/FileWriter.js
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var exec = require('cordova/exec'),
- FileError = require('./FileError'),
- ProgressEvent = require('./ProgressEvent');
-
-function write(data) {
- var that=this;
- var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined');
- var isBinary;
-
- // Check to see if the incoming data is a blob
- if (data instanceof File || (supportsBinary && data instanceof Blob)) {
- var fileReader = new FileReader();
- fileReader.onload = function() {
- // Call this method again, with the arraybuffer as argument
- FileWriter.prototype.write.call(that, this.result);
- };
- if (supportsBinary) {
- fileReader.readAsArrayBuffer(data);
- } else {
- fileReader.readAsText(data);
- }
- return;
- }
-
- // Mark data type for safer transport over the binary bridge
- isBinary = supportsBinary && (data instanceof ArrayBuffer);
-
- // 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}));
- }
-
- if (data instanceof ArrayBuffer || data.buffer instanceof ArrayBuffer) {
- data = new Uint8Array(data);
- var binary = "";
- for (var i = 0; i < data.byteLength; i++) {
- binary += String.fromCharCode(data[i]);
- }
- data = binary;
- }
-
- var prefix = "file://localhost";
- var path = this.localURL;
- if (path.substr(0, prefix.length) == prefix) {
- path = path.substr(prefix.length);
- }
- // Write file
- exec(
- // Success callback
- 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
- 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}));
- }
- }, "File", "write", [path, data, this.position, isBinary]);
-};
-
-module.exports = {
- write: write
-};
-
-require("cordova/exec/proxy").add("FileWriter", module.exports);
[7/8] CB-6521: Remove development branch
Posted by ia...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/FileUtils.java
----------------------------------------------------------------------
diff --git a/src/android/FileUtils.java b/src/android/FileUtils.java
deleted file mode 100644
index a7e86fa..0000000
--- a/src/android/FileUtils.java
+++ /dev/null
@@ -1,986 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-package org.apache.cordova.file;
-
-import android.app.Activity;
-import android.content.Context;
-import android.net.Uri;
-import android.os.Environment;
-import android.util.Base64;
-import android.util.Log;
-
-import org.apache.cordova.CallbackContext;
-import org.apache.cordova.CordovaInterface;
-import org.apache.cordova.CordovaPlugin;
-import org.apache.cordova.CordovaWebView;
-import org.apache.cordova.PluginResult;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-
-/**
- * This class provides file and directory services to JavaScript.
- */
-public class FileUtils extends CordovaPlugin {
- private static final String LOG_TAG = "FileUtils";
-
- public static int NOT_FOUND_ERR = 1;
- public static int SECURITY_ERR = 2;
- public static int ABORT_ERR = 3;
-
- public static int NOT_READABLE_ERR = 4;
- public static int ENCODING_ERR = 5;
- public static int NO_MODIFICATION_ALLOWED_ERR = 6;
- public static int INVALID_STATE_ERR = 7;
- public static int SYNTAX_ERR = 8;
- public static int INVALID_MODIFICATION_ERR = 9;
- public static int QUOTA_EXCEEDED_ERR = 10;
- public static int TYPE_MISMATCH_ERR = 11;
- public static int PATH_EXISTS_ERR = 12;
-
- public static int UNKNOWN_ERR = 1000;
-
- private boolean configured = false;
-
- // This field exists only to support getEntry, below, which has been deprecated
- private static FileUtils filePlugin;
-
- private interface FileOp {
- void run( ) throws Exception;
- }
-
- private ArrayList<Filesystem> filesystems;
-
- public void registerFilesystem(Filesystem fs) {
- if (fs != null && filesystemForName(fs.name)== null) {
- this.filesystems.add(fs);
- }
- }
-
- private Filesystem filesystemForName(String name) {
- for (Filesystem fs:filesystems) {
- if (fs != null && fs.name != null && fs.name.equals(name)) {
- return fs;
- }
- }
- return null;
- }
-
- protected String[] getExtraFileSystemsPreference(Activity activity) {
- String fileSystemsStr = activity.getIntent().getStringExtra("androidextrafilesystems");
- if (fileSystemsStr == null) {
- fileSystemsStr = "files,files-external,documents,sdcard,cache,cache-external,root";
- }
- return fileSystemsStr.split(",");
- }
-
- protected void registerExtraFileSystems(String[] filesystems, HashMap<String, String> availableFileSystems) {
- HashSet<String> installedFileSystems = new HashSet<String>();
-
- /* Register filesystems in order */
- for (String fsName : filesystems) {
- if (!installedFileSystems.contains(fsName)) {
- String fsRoot = availableFileSystems.get(fsName);
- if (fsRoot != null) {
- File newRoot = new File(fsRoot);
- if (newRoot.mkdirs() || newRoot.isDirectory()) {
- registerFilesystem(new LocalFilesystem(fsName, cordova, fsRoot));
- installedFileSystems.add(fsName);
- } else {
- Log.d(LOG_TAG, "Unable to create root dir for fileystem \"" + fsName + "\", skipping");
- }
- } else {
- Log.d(LOG_TAG, "Unrecognized extra filesystem identifier: " + fsName);
- }
- }
- }
- }
-
- protected HashMap<String, String> getAvailableFileSystems(Activity activity) {
- Context context = activity.getApplicationContext();
- HashMap<String, String> availableFileSystems = new HashMap<String,String>();
-
- availableFileSystems.put("files", context.getFilesDir().getAbsolutePath());
- availableFileSystems.put("files-external", context.getExternalFilesDir(null).getAbsolutePath());
- availableFileSystems.put("documents", new File(context.getFilesDir(), "Documents").getAbsolutePath());
- availableFileSystems.put("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath());
- availableFileSystems.put("cache", context.getCacheDir().getAbsolutePath());
- availableFileSystems.put("cache-external", context.getExternalCacheDir().getAbsolutePath());
- availableFileSystems.put("root", "/");
-
- return availableFileSystems;
- }
-
- @Override
- public void initialize(CordovaInterface cordova, CordovaWebView webView) {
- super.initialize(cordova, webView);
- this.filesystems = new ArrayList<Filesystem>();
-
- String tempRoot = null;
- String persistentRoot = null;
-
- Activity activity = cordova.getActivity();
- String packageName = activity.getPackageName();
-
- String location = activity.getIntent().getStringExtra("androidpersistentfilelocation");
- if (location == null) {
- location = "compatibility";
- }
- tempRoot = activity.getCacheDir().getAbsolutePath();
- if ("internal".equalsIgnoreCase(location)) {
- persistentRoot = activity.getFilesDir().getAbsolutePath() + "/files/";
- this.configured = true;
- } else if ("compatibility".equalsIgnoreCase(location)) {
- /*
- * Fall-back to compatibility mode -- this is the logic implemented in
- * earlier versions of this plugin, and should be maintained here so
- * that apps which were originally deployed with older versions of the
- * plugin can continue to provide access to files stored under those
- * versions.
- */
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- persistentRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
- tempRoot = Environment.getExternalStorageDirectory().getAbsolutePath() +
- "/Android/data/" + packageName + "/cache/";
- } else {
- persistentRoot = "/data/data/" + packageName;
- }
- this.configured = true;
- }
-
- if (this.configured) {
- // Create the directories if they don't exist.
- new File(tempRoot).mkdirs();
- new File(persistentRoot).mkdirs();
-
- // Register initial filesystems
- // Note: The temporary and persistent filesystems need to be the first two
- // registered, so that they will match window.TEMPORARY and window.PERSISTENT,
- // per spec.
- this.registerFilesystem(new LocalFilesystem("temporary", cordova, tempRoot));
- this.registerFilesystem(new LocalFilesystem("persistent", cordova, persistentRoot));
- this.registerFilesystem(new ContentFilesystem("content", cordova, webView));
-
- registerExtraFileSystems(getExtraFileSystemsPreference(activity), getAvailableFileSystems(activity));
-
- // Initialize static plugin reference for deprecated getEntry method
- if (filePlugin == null) {
- FileUtils.filePlugin = this;
- }
- } else {
- Log.e(LOG_TAG, "File plugin configuration error: Please set AndroidPersistentFileLocation in config.xml to one of \"internal\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
- activity.finish();
- }
- }
-
- public static FileUtils getFilePlugin() {
- return filePlugin;
- }
-
- private Filesystem filesystemForURL(LocalFilesystemURL localURL) {
- if (localURL == null) return null;
- return filesystemForName(localURL.filesystemName);
- }
-
- @Override
- public Uri remapUri(Uri uri) {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(uri);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- return null;
- }
- String path = fs.filesystemPathForURL(inputURL);
- if (path != null) {
- return Uri.parse("file:///" + fs.filesystemPathForURL(inputURL));
- }
- return null;
- } catch (IllegalArgumentException e) {
- return null;
- }
- }
-
- /**
- * Executes the request and returns whether the action was valid.
- *
- * @param action The action to execute.
- * @param args JSONArray of arguments for the plugin.
- * @param callbackContext The callback context used when calling back into JavaScript.
- * @return True if the action was valid, false otherwise.
- */
- public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
- if (!configured) {
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "File plugin is not configured. Please see the README.md file for details on how to update config.xml"));
- return true;
- }
- if (action.equals("testSaveLocationExists")) {
- threadhelper( new FileOp( ){
- public void run() {
- boolean b = DirectoryManager.testSaveLocationExists();
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
- }
- },callbackContext);
- }
- else if (action.equals("getFreeDiskSpace")) {
- threadhelper( new FileOp( ){
- public void run() {
- long l = DirectoryManager.getFreeDiskSpace(false);
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, l));
- }
- },callbackContext);
- }
- else if (action.equals("testFileExists")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() {
- boolean b = DirectoryManager.testFileExists(fname);
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
- }
- }, callbackContext);
- }
- else if (action.equals("testDirectoryExists")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() {
- boolean b = DirectoryManager.testFileExists(fname);
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
- }
- }, callbackContext);
- }
- else if (action.equals("readAsText")) {
- final String encoding = args.getString(1);
- final int start = args.getInt(2);
- final int end = args.getInt(3);
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws MalformedURLException {
- readFileAs(fname, start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
- }
- }, callbackContext);
- }
- else if (action.equals("readAsDataURL")) {
- final int start = args.getInt(1);
- final int end = args.getInt(2);
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws MalformedURLException {
- readFileAs(fname, start, end, callbackContext, null, -1);
- }
- }, callbackContext);
- }
- else if (action.equals("readAsArrayBuffer")) {
- final int start = args.getInt(1);
- final int end = args.getInt(2);
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws MalformedURLException {
- readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
- }
- },callbackContext);
- }
- else if (action.equals("readAsBinaryString")) {
- final int start = args.getInt(1);
- final int end = args.getInt(2);
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws MalformedURLException {
- readFileAs(fname, start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
- }
- }, callbackContext);
- }
- else if (action.equals("write")) {
- final String fname=args.getString(0);
- final String data=args.getString(1);
- final int offset=args.getInt(2);
- final Boolean isBinary=args.getBoolean(3);
- threadhelper( new FileOp( ){
- public void run() throws FileNotFoundException, IOException, NoModificationAllowedException {
- long fileSize = write(fname, data, offset, isBinary);
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
- }
- }, callbackContext);
- }
- else if (action.equals("truncate")) {
- final String fname=args.getString(0);
- final int offset=args.getInt(1);
- threadhelper( new FileOp( ){
- public void run( ) throws FileNotFoundException, IOException, NoModificationAllowedException {
- long fileSize = truncateFile(fname, offset);
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileSize));
- }
- }, callbackContext);
- }
- else if (action.equals("requestFileSystem")) {
- final int fstype=args.getInt(0);
- final long size = args.optLong(1);
- threadhelper( new FileOp( ){
- public void run() throws IOException, JSONException {
- if (size != 0 && size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR));
- } else {
- JSONObject obj = requestFileSystem(fstype);
- callbackContext.success(obj);
- }
- }
- }, callbackContext);
- }
- else if (action.equals("resolveLocalFileSystemURI")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws IOException, JSONException {
- JSONObject obj = resolveLocalFileSystemURI(fname);
- callbackContext.success(obj);
- }
- },callbackContext);
- }
- else if (action.equals("getMetadata") || action.equals("getFileMetadata")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws FileNotFoundException, JSONException, MalformedURLException {
- JSONObject obj = getFileMetadata(fname);
- callbackContext.success(obj);
- }
- }, callbackContext);
- }
- else if (action.equals("getParent")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws JSONException, IOException {
- JSONObject obj = getParent(fname);
- callbackContext.success(obj);
- }
- },callbackContext);
- }
- else if (action.equals("getDirectory")) {
- final String dirname=args.getString(0);
- final String path=args.getString(1);
- threadhelper( new FileOp( ){
- public void run() throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
- JSONObject obj = getFile(dirname, path, args.optJSONObject(2), true);
- callbackContext.success(obj);
- }
- },callbackContext);
- }
- else if (action.equals("getFile")) {
- final String dirname=args.getString(0);
- final String path=args.getString(1);
- threadhelper( new FileOp( ){
- public void run() throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
- JSONObject obj = getFile(dirname, path, args.optJSONObject(2), false);
- callbackContext.success(obj);
- }
- },callbackContext);
- }
- else if (action.equals("remove")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws NoModificationAllowedException, InvalidModificationException, MalformedURLException {
- boolean success = remove(fname);
- if (success) {
- callbackContext.success();
- } else {
- callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- }
- }
- },callbackContext);
- }
- else if (action.equals("removeRecursively")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws FileExistsException, MalformedURLException, NoModificationAllowedException {
- boolean success = removeRecursively(fname);
- if (success) {
- callbackContext.success();
- } else {
- callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- }
- }
- },callbackContext);
- }
- else if (action.equals("moveTo")) {
- final String fname=args.getString(0);
- final String newParent=args.getString(1);
- final String newName=args.getString(2);
- threadhelper( new FileOp( ){
- public void run() throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
- JSONObject entry = transferTo(fname, newParent, newName, true);
- callbackContext.success(entry);
- }
- },callbackContext);
- }
- else if (action.equals("copyTo")) {
- final String fname=args.getString(0);
- final String newParent=args.getString(1);
- final String newName=args.getString(2);
- threadhelper( new FileOp( ){
- public void run() throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
- JSONObject entry = transferTo(fname, newParent, newName, false);
- callbackContext.success(entry);
- }
- },callbackContext);
- }
- else if (action.equals("readEntries")) {
- final String fname=args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws FileNotFoundException, JSONException, MalformedURLException {
- JSONArray entries = readEntries(fname);
- callbackContext.success(entries);
- }
- },callbackContext);
- }
- else if (action.equals("_getLocalFilesystemPath")) {
- // Internal method for testing: Get the on-disk location of a local filesystem url.
- // [Currently used for testing file-transfer]
- final String localURLstr = args.getString(0);
- threadhelper( new FileOp( ){
- public void run() throws FileNotFoundException, JSONException, MalformedURLException {
- String fname = filesystemPathForURL(localURLstr);
- callbackContext.success(fname);
- }
- },callbackContext);
- }
- else {
- return false;
- }
- return true;
- }
-
- /*
- * These two native-only methods can be used by other plugins to translate between
- * device file system paths and URLs. By design, there is no direct JavaScript
- * interface to these methods.
- */
-
- public String filesystemPathForURL(String localURLstr) throws MalformedURLException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(localURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.filesystemPathForURL(inputURL);
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
- public LocalFilesystemURL filesystemURLforLocalPath(String localPath) {
- LocalFilesystemURL localURL = null;
- int shortestFullPath = 0;
-
- // Try all installed filesystems. Return the best matching URL
- // (determined by the shortest resulting URL)
- for (Filesystem fs: filesystems) {
- if (fs != null) {
- LocalFilesystemURL url = fs.URLforFilesystemPath(localPath);
- if (url != null) {
- // A shorter fullPath implies that the filesystem is a better
- // match for the local path than the previous best.
- if (localURL == null || (url.fullPath.length() < shortestFullPath)) {
- localURL = url;
- shortestFullPath = url.fullPath.length();
- }
- }
- }
- }
- return localURL;
- }
-
-
- /* helper to execute functions async and handle the result codes
- *
- */
- private void threadhelper(final FileOp f, final CallbackContext callbackContext){
- cordova.getThreadPool().execute(new Runnable() {
- public void run() {
- try {
- f.run();
- } catch ( Exception e) {
- e.printStackTrace();
- if( e instanceof EncodingException){
- callbackContext.error(FileUtils.ENCODING_ERR);
- } else if(e instanceof FileNotFoundException) {
- callbackContext.error(FileUtils.NOT_FOUND_ERR);
- } else if(e instanceof FileExistsException) {
- callbackContext.error(FileUtils.PATH_EXISTS_ERR);
- } else if(e instanceof NoModificationAllowedException ) {
- callbackContext.error(FileUtils.NO_MODIFICATION_ALLOWED_ERR);
- } else if(e instanceof InvalidModificationException ) {
- callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
- } else if(e instanceof MalformedURLException ) {
- callbackContext.error(FileUtils.ENCODING_ERR);
- } else if(e instanceof IOException ) {
- callbackContext.error(FileUtils.INVALID_MODIFICATION_ERR);
- } else if(e instanceof EncodingException ) {
- callbackContext.error(FileUtils.ENCODING_ERR);
- } else if(e instanceof TypeMismatchException ) {
- callbackContext.error(FileUtils.TYPE_MISMATCH_ERR);
- } else {
- callbackContext.error(FileUtils.UNKNOWN_ERR);
- }
- }
- }
- });
- }
-
- /**
- * Allows the user to look up the Entry for a file or directory referred to by a local URI.
- *
- * @param url of the file/directory to look up
- * @return a JSONObject representing a Entry from the filesystem
- * @throws MalformedURLException if the url is not valid
- * @throws FileNotFoundException if the file does not exist
- * @throws IOException if the user can't read the file
- * @throws JSONException
- */
- private JSONObject resolveLocalFileSystemURI(String url) throws IOException, JSONException {
- LocalFilesystemURL inputURL;
- if (url == null) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
-
- /* Backwards-compatibility: Check for file:// urls */
- if (url.startsWith("file:/")) {
- if (!url.startsWith("file://")) {
- url = "file:///" + url.substring(6);
- }
- String decoded = URLDecoder.decode(url, "UTF-8");
- /* This looks like a file url. Get the path, and see if any handlers recognize it. */
- String path;
- int questionMark = decoded.indexOf("?");
- int pathEnd;
- if (questionMark < 0) {
- pathEnd = decoded.length();
- } else {
- pathEnd = questionMark;
- }
-
- int thirdSlash = decoded.indexOf("/", 7);
- if (thirdSlash < 0 || thirdSlash > pathEnd) {
- path = "";
- } else {
- path = decoded.substring(thirdSlash, pathEnd);
- }
- inputURL = this.filesystemURLforLocalPath(path);
- } else {
- inputURL = new LocalFilesystemURL(url);
- }
-
- try {
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.getEntryForLocalURL(inputURL);
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
- /**
- * Read the list of files from this directory.
- *
- * @param fileName the directory to read from
- * @return a JSONArray containing JSONObjects that represent Entry objects.
- * @throws FileNotFoundException if the directory is not found.
- * @throws JSONException
- * @throws MalformedURLException
- */
- private JSONArray readEntries(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(baseURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.readEntriesAtLocalURL(inputURL);
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
- /**
- * A setup method that handles the move/copy of files/directories
- *
- * @param fileName to be copied/moved
- * @param newParent is the location where the file will be copied/moved to
- * @param newName for the file directory to be called, if null use existing file name
- * @param move if false do a copy, if true do a move
- * @return a Entry object
- * @throws NoModificationAllowedException
- * @throws IOException
- * @throws InvalidModificationException
- * @throws EncodingException
- * @throws JSONException
- * @throws FileExistsException
- */
- private JSONObject transferTo(String srcURLstr, String destURLstr, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
- if (srcURLstr == null || destURLstr == null) {
- // either no source or no destination provided
- throw new FileNotFoundException();
- }
-
- LocalFilesystemURL srcURL = new LocalFilesystemURL(srcURLstr);
- LocalFilesystemURL destURL = new LocalFilesystemURL(destURLstr);
-
- Filesystem srcFs = this.filesystemForURL(srcURL);
- Filesystem destFs = this.filesystemForURL(destURL);
-
- // Check for invalid file name
- if (newName != null && newName.contains(":")) {
- throw new EncodingException("Bad file name");
- }
-
- return destFs.copyFileToURL(destURL, newName, srcFs, srcURL, move);
- }
-
- /**
- * Deletes a directory and all of its contents, if any. In the event of an error
- * [e.g. trying to delete a directory that contains a file that cannot be removed],
- * some of the contents of the directory may be deleted.
- * It is an error to attempt to delete the root directory of a filesystem.
- *
- * @param filePath the directory to be removed
- * @return a boolean representing success of failure
- * @throws FileExistsException
- * @throws NoModificationAllowedException
- * @throws MalformedURLException
- */
- private boolean removeRecursively(String baseURLstr) throws FileExistsException, NoModificationAllowedException, MalformedURLException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(baseURLstr);
- // You can't delete the root directory.
- if ("".equals(inputURL.fullPath) || "/".equals(inputURL.fullPath)) {
- throw new NoModificationAllowedException("You can't delete the root directory");
- }
-
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.recursiveRemoveFileAtLocalURL(inputURL);
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
-
- /**
- * Deletes 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 the root directory of a filesystem.
- *
- * @param filePath file or directory to be removed
- * @return a boolean representing success of failure
- * @throws NoModificationAllowedException
- * @throws InvalidModificationException
- * @throws MalformedURLException
- */
- private boolean remove(String baseURLstr) throws NoModificationAllowedException, InvalidModificationException, MalformedURLException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(baseURLstr);
- // You can't delete the root directory.
- if ("".equals(inputURL.fullPath) || "/".equals(inputURL.fullPath)) {
-
- throw new NoModificationAllowedException("You can't delete the root directory");
- }
-
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.removeFileAtLocalURL(inputURL);
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
- /**
- * Creates or looks up a file.
- *
- * @param baseURLstr base directory
- * @param path file/directory to lookup or create
- * @param options specify whether to create or not
- * @param directory if true look up directory, if false look up file
- * @return a Entry object
- * @throws FileExistsException
- * @throws IOException
- * @throws TypeMismatchException
- * @throws EncodingException
- * @throws JSONException
- */
- private JSONObject getFile(String baseURLstr, String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(baseURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.getFileForLocalURL(inputURL, path, options, directory);
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
-
- }
-
- /**
- * Look up the parent DirectoryEntry containing this Entry.
- * If this Entry is the root of its filesystem, its parent is itself.
- *
- * @param filePath
- * @return
- * @throws JSONException
- * @throws IOException
- */
- private JSONObject getParent(String baseURLstr) throws JSONException, IOException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(baseURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.getParentForLocalURL(inputURL);
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
- /**
- * Returns a File that represents the current state of the file that this FileEntry represents.
- *
- * @param filePath to entry
- * @return returns a JSONObject represent a W3C File object
- * @throws FileNotFoundException
- * @throws JSONException
- * @throws MalformedURLException
- */
- private JSONObject getFileMetadata(String baseURLstr) throws FileNotFoundException, JSONException, MalformedURLException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(baseURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
- return fs.getFileMetadataForLocalURL(inputURL);
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-
- /**
- * Requests a filesystem in which to store application data.
- *
- * @param type of file system requested
- * @return a JSONObject representing the file system
- * @throws IOException
- * @throws JSONException
- */
- private JSONObject requestFileSystem(int type) throws IOException, JSONException {
- JSONObject fs = new JSONObject();
- Filesystem rootFs = null;
- try {
- rootFs = this.filesystems.get(type);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Pass null through
- }
- if (rootFs == null) {
- throw new IOException("No filesystem of type requested");
- }
- fs.put("name", rootFs.name);
- fs.put("root", Filesystem.makeEntryForPath("/", rootFs.name, true));
- return fs;
- }
-
- /**
- * Returns a JSON object representing the given File. Internal APIs should be modified
- * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
- *
- * @param file the File to convert
- * @return a JSON representation of the given File
- * @throws JSONException
- */
- public JSONObject getEntryForFile(File file) throws JSONException {
- JSONObject entry;
-
- for (Filesystem fs : filesystems) {
- entry = fs.makeEntryForFile(file);
- if (entry != null) {
- return entry;
- }
- }
- return null;
- }
-
- /**
- * Returns a JSON object representing the given File. Deprecated, as this is only used by
- * FileTransfer, and because it is a static method that should really be an instance method,
- * since it depends on the actual filesystem roots in use. Internal APIs should be modified
- * to use URLs instead of raw FS paths wherever possible, when interfacing with this plugin.
- *
- * @param file the File to convert
- * @return a JSON representation of the given File
- * @throws JSONException
- */
- @Deprecated
- public static JSONObject getEntry(File file) throws JSONException {
- if (getFilePlugin() != null) {
- return getFilePlugin().getEntryForFile(file);
- }
- return null;
- }
-
- /**
- * Read the contents of a file.
- * This is done in a background thread; the result is sent to the callback.
- *
- * @param filename The name of the file.
- * @param start Start position in the file.
- * @param end End position to stop at (exclusive).
- * @param callbackContext The context through which to send the result.
- * @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
- * @param resultType The desired type of data to send to the callback.
- * @return Contents of file.
- * @throws MalformedURLException
- */
- public void readFileAs(final String srcURLstr, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) throws MalformedURLException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(srcURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
-
- fs.readFileAtURL(inputURL, start, end, new Filesystem.ReadFileCallback() {
- public void handleData(InputStream inputStream, String contentType) {
- try {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- final int BUFFER_SIZE = 8192;
- byte[] buffer = new byte[BUFFER_SIZE];
-
- for (;;) {
- int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
-
- if (bytesRead <= 0) {
- break;
- }
- os.write(buffer, 0, bytesRead);
- }
-
- PluginResult result;
- switch (resultType) {
- case PluginResult.MESSAGE_TYPE_STRING:
- result = new PluginResult(PluginResult.Status.OK, os.toString(encoding));
- break;
- case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
- result = new PluginResult(PluginResult.Status.OK, os.toByteArray());
- break;
- case PluginResult.MESSAGE_TYPE_BINARYSTRING:
- result = new PluginResult(PluginResult.Status.OK, os.toByteArray(), true);
- break;
- default: // Base64.
- byte[] base64 = Base64.encode(os.toByteArray(), Base64.NO_WRAP);
- String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
- result = new PluginResult(PluginResult.Status.OK, s);
- }
-
- callbackContext.sendPluginResult(result);
- } catch (IOException e) {
- Log.d(LOG_TAG, e.getLocalizedMessage());
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
- }
- }
- });
-
-
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- } catch (FileNotFoundException e) {
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
- } catch (IOException e) {
- Log.d(LOG_TAG, e.getLocalizedMessage());
- callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
- }
- }
-
-
- /**
- * Write contents of file.
- *
- * @param filename The name of the file.
- * @param data The contents of the file.
- * @param offset The position to begin writing the file.
- * @param isBinary True if the file contents are base64-encoded binary data
- * @throws FileNotFoundException, IOException
- * @throws NoModificationAllowedException
- */
- /**/
- public long write(String srcURLstr, String data, int offset, boolean isBinary) throws FileNotFoundException, IOException, NoModificationAllowedException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(srcURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
-
- long x = fs.writeToFileAtURL(inputURL, data, offset, isBinary); Log.d("TEST",srcURLstr + ": "+x); return x;
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
-
- }
-
- /**
- * Truncate the file to size
- *
- * @param filename
- * @param size
- * @throws FileNotFoundException, IOException
- * @throws NoModificationAllowedException
- */
- private long truncateFile(String srcURLstr, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
- try {
- LocalFilesystemURL inputURL = new LocalFilesystemURL(srcURLstr);
- Filesystem fs = this.filesystemForURL(inputURL);
- if (fs == null) {
- throw new MalformedURLException("No installed handlers for this URL");
- }
-
- return fs.truncateFileAtURL(inputURL, size);
- } catch (IllegalArgumentException e) {
- throw new MalformedURLException("Unrecognized filesystem URL");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/Filesystem.java
----------------------------------------------------------------------
diff --git a/src/android/Filesystem.java b/src/android/Filesystem.java
deleted file mode 100644
index 954c098..0000000
--- a/src/android/Filesystem.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-package org.apache.cordova.file;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-public abstract class Filesystem {
-
- public String name;
-
- public interface ReadFileCallback {
- public void handleData(InputStream inputStream, String contentType) throws IOException;
- }
-
- public static JSONObject makeEntryForPath(String path, String fsName, Boolean isDir)
- throws JSONException {
- return makeEntryForPath(path, fsName, isDir, null);
- }
-
- public static JSONObject makeEntryForPath(String path, String fsName, Boolean isDir, String nativeURL)
- throws JSONException {
- JSONObject entry = new JSONObject();
-
- int end = path.endsWith("/") ? 1 : 0;
- String[] parts = path.substring(0,path.length()-end).split("/");
- String fileName = parts[parts.length-1];
- entry.put("isFile", !isDir);
- entry.put("isDirectory", isDir);
- entry.put("name", fileName);
- entry.put("fullPath", path);
- // The file system can't be specified, as it would lead to an infinite loop,
- // but the filesystem name can be.
- entry.put("filesystemName", fsName);
- // Backwards compatibility
- entry.put("filesystem", "temporary".equals(fsName) ? 0 : 1);
-
- if (nativeURL != null) {
- entry.put("nativeURL", nativeURL);
- }
- return entry;
-
- }
-
- public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Boolean isDir) throws JSONException {
- return makeEntryForURL(inputURL, isDir, null);
- }
-
- public static JSONObject makeEntryForURL(LocalFilesystemURL inputURL, Boolean isDir, String nativeURL) throws JSONException {
- return makeEntryForPath(inputURL.fullPath, inputURL.filesystemName, isDir, nativeURL);
- }
-
- abstract JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException;
-
- abstract JSONObject getFileForLocalURL(LocalFilesystemURL inputURL, String path,
- JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException;
-
- abstract boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException;
-
- abstract boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException, NoModificationAllowedException;
-
- abstract JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;
-
- abstract JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException;
-
- public JSONObject getParentForLocalURL(LocalFilesystemURL inputURL) throws IOException {
- LocalFilesystemURL newURL = new LocalFilesystemURL(inputURL.URL);
-
- if (!("".equals(inputURL.fullPath) || "/".equals(inputURL.fullPath))) {
- int end = inputURL.fullPath.endsWith("/") ? 1 : 0;
- int lastPathStartsAt = inputURL.fullPath.lastIndexOf('/', inputURL.fullPath.length()-end)+1;
- newURL.fullPath = newURL.fullPath.substring(0,lastPathStartsAt);
- }
- return getEntryForLocalURL(newURL);
- }
-
- protected LocalFilesystemURL makeDestinationURL(String newName, LocalFilesystemURL srcURL, LocalFilesystemURL destURL) {
- // I know this looks weird but it is to work around a JSON bug.
- if ("null".equals(newName) || "".equals(newName)) {
- newName = srcURL.URL.getLastPathSegment();;
- }
-
- String newDest = destURL.URL.toString();
- if (newDest.endsWith("/")) {
- newDest = newDest + newName;
- } else {
- newDest = newDest + "/" + newName;
- }
- return new LocalFilesystemURL(newDest);
- }
-
- /* Read a source URL (possibly from a different filesystem, srcFs,) and copy it to
- * the destination URL on this filesystem, optionally with a new filename.
- * If move is true, then this method should either perform an atomic move operation
- * or remove the source file when finished.
- */
- JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
- Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
- // This is "the hard way" -- transfer data between arbitrary filesystem urls/
- // Gets an input stream from src, and writes its contents to an output stream
- // from dest.
-
- // First, check to see that we can do it
- if (!move || srcFs.canRemoveFileAtLocalURL(srcURL)) {
- final LocalFilesystemURL destination = makeDestinationURL(newName, srcURL, destURL);
- srcFs.readFileAtURL(srcURL, 0, -1, new ReadFileCallback() {
- public void handleData(InputStream inputStream, String contentType) throws IOException {
- if (inputStream != null) {
- //write data to file
- OutputStream os = getOutputStreamForURL(destination);
- final int BUFFER_SIZE = 8192;
- byte[] buffer = new byte[BUFFER_SIZE];
-
- for (;;) {
- int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE);
-
- if (bytesRead <= 0) {
- break;
- }
- os.write(buffer, 0, bytesRead);
- }
- os.close();
- } else {
- throw new IOException("Cannot read file at source URL");
- }
- }
- });
- if (move) {
- // Delete original
- srcFs.removeFileAtLocalURL(srcURL);
- }
- return makeEntryForURL(destination, false);
- } else {
- throw new NoModificationAllowedException("Cannot move file at source URL");
- }
- }
-
- abstract OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws IOException;
-
- abstract void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
- ReadFileCallback readFileCallback) throws IOException;
-
- abstract long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset,
- boolean isBinary) throws NoModificationAllowedException, IOException;
-
- abstract long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
- throws IOException, NoModificationAllowedException;
-
- // This method should return null if filesystem urls cannot be mapped to paths
- abstract String filesystemPathForURL(LocalFilesystemURL url);
-
- abstract LocalFilesystemURL URLforFilesystemPath(String path);
-
- abstract boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL);
-
- protected class LimitedInputStream extends FilterInputStream {
- long numBytesToRead;
- public LimitedInputStream(InputStream in, long numBytesToRead) {
- super(in);
- this.numBytesToRead = numBytesToRead;
- }
- @Override
- public int read() throws IOException {
- if (numBytesToRead <= 0) {
- return -1;
- }
- numBytesToRead--;
- return in.read();
- }
- @Override
- public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
- if (numBytesToRead <= 0) {
- return -1;
- }
- int bytesToRead = byteCount;
- if (byteCount > numBytesToRead) {
- bytesToRead = (int)numBytesToRead; // Cast okay; long is less than int here.
- }
- int numBytesRead = in.read(buffer, byteOffset, bytesToRead);
- numBytesToRead -= numBytesRead;
- return numBytesRead;
- }
- }
-
- /* Create a FileEntry or DirectoryEntry given an actual file on device.
- * Return null if the file does not exist within this filesystem.
- */
- public JSONObject makeEntryForFile(File file) throws JSONException {
- return null;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/InvalidModificationException.java
----------------------------------------------------------------------
diff --git a/src/android/InvalidModificationException.java b/src/android/InvalidModificationException.java
deleted file mode 100644
index 8f6bec5..0000000
--- a/src/android/InvalidModificationException.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-
-package org.apache.cordova.file;
-
-@SuppressWarnings("serial")
-public class InvalidModificationException extends Exception {
-
- public InvalidModificationException(String message) {
- super(message);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/LocalFilesystem.java
----------------------------------------------------------------------
diff --git a/src/android/LocalFilesystem.java b/src/android/LocalFilesystem.java
deleted file mode 100644
index c0e14e4..0000000
--- a/src/android/LocalFilesystem.java
+++ /dev/null
@@ -1,644 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-package org.apache.cordova.file;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.RandomAccessFile;
-import java.nio.channels.FileChannel;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import org.apache.cordova.CordovaInterface;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.util.Base64;
-import android.net.Uri;
-
-public class LocalFilesystem extends Filesystem {
-
- private String fsRoot;
- private CordovaInterface cordova;
-
- public LocalFilesystem(String name, CordovaInterface cordova, String fsRoot) {
- this.name = name;
- this.fsRoot = fsRoot;
- this.cordova = cordova;
- }
-
- public String filesystemPathForFullPath(String fullPath) {
- String path = new File(this.fsRoot, fullPath).toString();
- int questionMark = path.indexOf("?");
- if (questionMark >= 0) {
- path = path.substring(0, questionMark);
- }
- if (path.length() > 1 && path.endsWith("/")) {
- path = path.substring(0, path.length()-1);
- }
- return path;
- }
-
- @Override
- public String filesystemPathForURL(LocalFilesystemURL url) {
- return filesystemPathForFullPath(url.fullPath);
- }
-
- private String fullPathForFilesystemPath(String absolutePath) {
- if (absolutePath != null && absolutePath.startsWith(this.fsRoot)) {
- return absolutePath.substring(this.fsRoot.length());
- }
- return null;
- }
-
- protected LocalFilesystemURL URLforFullPath(String fullPath) {
- if (fullPath != null) {
- if (fullPath.startsWith("/")) {
- return new LocalFilesystemURL(LocalFilesystemURL.FILESYSTEM_PROTOCOL + "://localhost/"+this.name+fullPath);
- }
- return new LocalFilesystemURL(LocalFilesystemURL.FILESYSTEM_PROTOCOL + "://localhost/"+this.name+"/"+fullPath);
- }
- return null;
-
- }
-
- @Override
- public LocalFilesystemURL URLforFilesystemPath(String path) {
- return this.URLforFullPath(this.fullPathForFilesystemPath(path));
- }
-
- protected String normalizePath(String rawPath) {
- // If this is an absolute path, trim the leading "/" and replace it later
- boolean isAbsolutePath = rawPath.startsWith("/");
- if (isAbsolutePath) {
- rawPath = rawPath.substring(1);
- }
- ArrayList<String> components = new ArrayList<String>(Arrays.asList(rawPath.split("/")));
- for (int index = 0; index < components.size(); ++index) {
- if (components.get(index).equals("..")) {
- components.remove(index);
- if (index > 0) {
- components.remove(index-1);
- --index;
- }
- }
- }
- StringBuilder normalizedPath = new StringBuilder();
- for(String component: components) {
- normalizedPath.append("/");
- normalizedPath.append(component);
- }
- if (isAbsolutePath) {
- return normalizedPath.toString();
- } else {
- return normalizedPath.toString().substring(1);
- }
-
-
- }
-
-
- @Override
- public JSONObject makeEntryForFile(File file) throws JSONException {
- String path = this.fullPathForFilesystemPath(file.getAbsolutePath());
- if (path != null) {
- return makeEntryForPath(path, this.name, file.isDirectory(), Uri.fromFile(file).toString());
- }
- return null;
- }
-
- @Override
- public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
- File fp = new File(filesystemPathForURL(inputURL));
-
- if (!fp.exists()) {
- throw new FileNotFoundException();
- }
- if (!fp.canRead()) {
- throw new IOException();
- }
- try {
- JSONObject entry = new JSONObject();
- entry.put("isFile", fp.isFile());
- entry.put("isDirectory", fp.isDirectory());
- entry.put("name", fp.getName());
- entry.put("fullPath", inputURL.fullPath);
- // The file system can't be specified, as it would lead to an infinite loop.
- // But we can specify the name of the FS, and the rest can be reconstructed
- // in JS.
- entry.put("filesystemName", inputURL.filesystemName);
- // Backwards compatibility
- entry.put("filesystem", "temporary".equals(name) ? 0 : 1);
- entry.put("nativeURL", Uri.fromFile(fp).toString());
- return entry;
- } catch (JSONException e) {
- throw new IOException();
- }
- }
-
- @Override
- public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
- String path, JSONObject options, boolean directory) throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
- boolean create = false;
- boolean exclusive = false;
-
- if (options != null) {
- create = options.optBoolean("create");
- if (create) {
- exclusive = options.optBoolean("exclusive");
- }
- }
-
- // Check for a ":" character in the file to line up with BB and iOS
- if (path.contains(":")) {
- throw new EncodingException("This path has an invalid \":\" in it.");
- }
-
- LocalFilesystemURL requestedURL;
-
- // Check whether the supplied path is absolute or relative
- if (path.startsWith("/")) {
- requestedURL = URLforFilesystemPath(path);
- } else {
- requestedURL = URLforFullPath(normalizePath(inputURL.fullPath + "/" + path));
- }
-
- File fp = new File(this.filesystemPathForURL(requestedURL));
-
- if (create) {
- if (exclusive && fp.exists()) {
- throw new FileExistsException("create/exclusive fails");
- }
- if (directory) {
- fp.mkdir();
- } else {
- fp.createNewFile();
- }
- if (!fp.exists()) {
- throw new FileExistsException("create fails");
- }
- }
- else {
- if (!fp.exists()) {
- throw new FileNotFoundException("path does not exist");
- }
- if (directory) {
- if (fp.isFile()) {
- throw new TypeMismatchException("path doesn't exist or is file");
- }
- } else {
- if (fp.isDirectory()) {
- throw new TypeMismatchException("path doesn't exist or is directory");
- }
- }
- }
-
- // Return the directory
- return makeEntryForPath(requestedURL.fullPath, requestedURL.filesystemName, directory, Uri.fromFile(fp).toString());
- }
-
- @Override
- public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException {
-
- File fp = new File(filesystemPathForURL(inputURL));
-
- // You can't delete a directory that is not empty
- if (fp.isDirectory() && fp.list().length > 0) {
- throw new InvalidModificationException("You can't delete a directory that is not empty.");
- }
-
- return fp.delete();
- }
-
- @Override
- public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws FileExistsException {
- File directory = new File(filesystemPathForURL(inputURL));
- return removeDirRecursively(directory);
- }
-
- protected boolean removeDirRecursively(File directory) throws FileExistsException {
- if (directory.isDirectory()) {
- for (File file : directory.listFiles()) {
- removeDirRecursively(file);
- }
- }
-
- if (!directory.delete()) {
- throw new FileExistsException("could not delete: " + directory.getName());
- } else {
- return true;
- }
- }
-
- @Override
- public JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
- File fp = new File(filesystemPathForURL(inputURL));
-
- if (!fp.exists()) {
- // The directory we are listing doesn't exist so we should fail.
- throw new FileNotFoundException();
- }
-
- JSONArray entries = new JSONArray();
-
- if (fp.isDirectory()) {
- File[] files = fp.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].canRead()) {
- try {
- entries.put(makeEntryForPath(fullPathForFilesystemPath(files[i].getAbsolutePath()), inputURL.filesystemName, files[i].isDirectory(), Uri.fromFile(files[i]).toString()));
- } catch (JSONException e) {
- }
- }
- }
- }
-
- return entries;
- }
-
- @Override
- public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
- File file = new File(filesystemPathForURL(inputURL));
-
- if (!file.exists()) {
- throw new FileNotFoundException("File at " + inputURL.URL + " does not exist.");
- }
-
- JSONObject metadata = new JSONObject();
- try {
- // Ensure that directories report a size of 0
- metadata.put("size", file.isDirectory() ? 0 : file.length());
- metadata.put("type", FileHelper.getMimeType(file.getAbsolutePath(), cordova));
- metadata.put("name", file.getName());
- metadata.put("fullPath", inputURL.fullPath);
- metadata.put("lastModifiedDate", file.lastModified());
- } catch (JSONException e) {
- return null;
- }
- return metadata;
- }
-
- /**
- * Check to see if the user attempted to copy an entry into its parent without changing its name,
- * or attempted to copy a directory into a directory that it contains directly or indirectly.
- *
- * @param srcDir
- * @param destinationDir
- * @return
- */
- private boolean isCopyOnItself(String src, String dest) {
-
- // This weird test is to determine if we are copying or moving a directory into itself.
- // Copy /sdcard/myDir to /sdcard/myDir-backup is okay but
- // Copy /sdcard/myDir to /sdcard/myDir/backup should throw an INVALID_MODIFICATION_ERR
- if (dest.startsWith(src) && dest.indexOf(File.separator, src.length() - 1) != -1) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Copy a file
- *
- * @param srcFile file to be copied
- * @param destFile destination to be copied to
- * @return a FileEntry object
- * @throws IOException
- * @throws InvalidModificationException
- * @throws JSONException
- */
- private JSONObject copyFile(File srcFile, File destFile) throws IOException, InvalidModificationException, JSONException {
- // Renaming a file to an existing directory should fail
- if (destFile.exists() && destFile.isDirectory()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- copyAction(srcFile, destFile);
-
- return makeEntryForFile(destFile);
- }
-
- /**
- * Moved this code into it's own method so moveTo could use it when the move is across file systems
- */
- private void copyAction(File srcFile, File destFile)
- throws FileNotFoundException, IOException {
- FileInputStream istream = new FileInputStream(srcFile);
- FileOutputStream ostream = new FileOutputStream(destFile);
- FileChannel input = istream.getChannel();
- FileChannel output = ostream.getChannel();
-
- try {
- input.transferTo(0, input.size(), output);
- } finally {
- istream.close();
- ostream.close();
- input.close();
- output.close();
- }
- }
-
- /**
- * Copy a directory
- *
- * @param srcDir directory to be copied
- * @param destinationDir destination to be copied to
- * @return a DirectoryEntry object
- * @throws JSONException
- * @throws IOException
- * @throws NoModificationAllowedException
- * @throws InvalidModificationException
- */
- private JSONObject copyDirectory(File srcDir, File destinationDir) throws JSONException, IOException, NoModificationAllowedException, InvalidModificationException {
- // Renaming a file to an existing directory should fail
- if (destinationDir.exists() && destinationDir.isFile()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- // Check to make sure we are not copying the directory into itself
- if (isCopyOnItself(srcDir.getAbsolutePath(), destinationDir.getAbsolutePath())) {
- throw new InvalidModificationException("Can't copy itself into itself");
- }
-
- // See if the destination directory exists. If not create it.
- if (!destinationDir.exists()) {
- if (!destinationDir.mkdir()) {
- // If we can't create the directory then fail
- throw new NoModificationAllowedException("Couldn't create the destination directory");
- }
- }
-
-
- for (File file : srcDir.listFiles()) {
- File destination = new File(destinationDir.getAbsoluteFile() + File.separator + file.getName());
- if (file.isDirectory()) {
- copyDirectory(file, destination);
- } else {
- copyFile(file, destination);
- }
- }
-
- return makeEntryForFile(destinationDir);
- }
-
- /**
- * Move a file
- *
- * @param srcFile file to be copied
- * @param destFile destination to be copied to
- * @return a FileEntry object
- * @throws IOException
- * @throws InvalidModificationException
- * @throws JSONException
- */
- private JSONObject moveFile(File srcFile, File destFile) throws IOException, JSONException, InvalidModificationException {
- // Renaming a file to an existing directory should fail
- if (destFile.exists() && destFile.isDirectory()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- // Try to rename the file
- if (!srcFile.renameTo(destFile)) {
- // Trying to rename the file failed. Possibly because we moved across file system on the device.
- // Now we have to do things the hard way
- // 1) Copy all the old file
- // 2) delete the src file
- copyAction(srcFile, destFile);
- if (destFile.exists()) {
- srcFile.delete();
- } else {
- throw new IOException("moved failed");
- }
- }
-
- return makeEntryForFile(destFile);
- }
-
- /**
- * Move a directory
- *
- * @param srcDir directory to be copied
- * @param destinationDir destination to be copied to
- * @return a DirectoryEntry object
- * @throws JSONException
- * @throws IOException
- * @throws InvalidModificationException
- * @throws NoModificationAllowedException
- * @throws FileExistsException
- */
- private JSONObject moveDirectory(File srcDir, File destinationDir) throws IOException, JSONException, InvalidModificationException, NoModificationAllowedException, FileExistsException {
- // Renaming a file to an existing directory should fail
- if (destinationDir.exists() && destinationDir.isFile()) {
- throw new InvalidModificationException("Can't rename a file to a directory");
- }
-
- // Check to make sure we are not copying the directory into itself
- if (isCopyOnItself(srcDir.getAbsolutePath(), destinationDir.getAbsolutePath())) {
- throw new InvalidModificationException("Can't move itself into itself");
- }
-
- // If the destination directory already exists and is empty then delete it. This is according to spec.
- if (destinationDir.exists()) {
- if (destinationDir.list().length > 0) {
- throw new InvalidModificationException("directory is not empty");
- }
- }
-
- // Try to rename the directory
- if (!srcDir.renameTo(destinationDir)) {
- // Trying to rename the directory failed. Possibly because we moved across file system on the device.
- // Now we have to do things the hard way
- // 1) Copy all the old files
- // 2) delete the src directory
- copyDirectory(srcDir, destinationDir);
- if (destinationDir.exists()) {
- removeDirRecursively(srcDir);
- } else {
- throw new IOException("moved failed");
- }
- }
-
- return makeEntryForFile(destinationDir);
- }
-
- @Override
- public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
- Filesystem srcFs, LocalFilesystemURL srcURL, boolean move) throws IOException, InvalidModificationException, JSONException, NoModificationAllowedException, FileExistsException {
-
- // Check to see if the destination directory exists
- String newParent = this.filesystemPathForURL(destURL);
- File destinationDir = new File(newParent);
- if (!destinationDir.exists()) {
- // The destination does not exist so we should fail.
- throw new FileNotFoundException("The source does not exist");
- }
-
- if (LocalFilesystem.class.isInstance(srcFs)) {
- /* Same FS, we can shortcut with NSFileManager operations */
-
- // Figure out where we should be copying to
- final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL);
-
- String srcFilesystemPath = srcFs.filesystemPathForURL(srcURL);
- File sourceFile = new File(srcFilesystemPath);
- String destFilesystemPath = this.filesystemPathForURL(destinationURL);
- File destinationFile = new File(destFilesystemPath);
-
- if (!sourceFile.exists()) {
- // The file/directory we are copying doesn't exist so we should fail.
- throw new FileNotFoundException("The source does not exist");
- }
-
- // Check to see if source and destination are the same file
- if (sourceFile.getAbsolutePath().equals(destinationFile.getAbsolutePath())) {
- throw new InvalidModificationException("Can't copy a file onto itself");
- }
-
- if (sourceFile.isDirectory()) {
- if (move) {
- return moveDirectory(sourceFile, destinationFile);
- } else {
- return copyDirectory(sourceFile, destinationFile);
- }
- } else {
- if (move) {
- return moveFile(sourceFile, destinationFile);
- } else {
- return copyFile(sourceFile, destinationFile);
- }
- }
-
- } else {
- // Need to copy the hard way
- return super.copyFileToURL(destURL, newName, srcFs, srcURL, move);
- }
- }
-
- @Override
- public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
- ReadFileCallback readFileCallback) throws IOException {
-
- File file = new File(this.filesystemPathForURL(inputURL));
- String contentType = FileHelper.getMimeTypeForExtension(file.getAbsolutePath());
-
- if (end < 0) {
- end = file.length();
- }
- long numBytesToRead = end - start;
-
- InputStream rawInputStream = new FileInputStream(file);
- try {
- if (start > 0) {
- rawInputStream.skip(start);
- }
- LimitedInputStream inputStream = new LimitedInputStream(rawInputStream, numBytesToRead);
- readFileCallback.handleData(inputStream, contentType);
- } finally {
- rawInputStream.close();
- }
- }
-
- @Override
- public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
- int offset, boolean isBinary) throws IOException, NoModificationAllowedException {
-
- boolean append = false;
- if (offset > 0) {
- this.truncateFileAtURL(inputURL, offset);
- append = true;
- }
-
- byte[] rawData;
- if (isBinary) {
- rawData = Base64.decode(data, Base64.DEFAULT);
- } else {
- rawData = data.getBytes();
- }
- ByteArrayInputStream in = new ByteArrayInputStream(rawData);
- try
- {
- byte buff[] = new byte[rawData.length];
- FileOutputStream out = new FileOutputStream(this.filesystemPathForURL(inputURL), append);
- try {
- in.read(buff, 0, buff.length);
- out.write(buff, 0, rawData.length);
- out.flush();
- } finally {
- // Always close the output
- out.close();
- }
- }
- catch (NullPointerException e)
- {
- // This is a bug in the Android implementation of the Java Stack
- NoModificationAllowedException realException = new NoModificationAllowedException(inputURL.toString());
- throw realException;
- }
-
- return rawData.length;
- }
-
- @Override
- public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
- File file = new File(filesystemPathForURL(inputURL));
-
- if (!file.exists()) {
- throw new FileNotFoundException("File at " + inputURL.URL + " does not exist.");
- }
-
- RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
- try {
- if (raf.length() >= size) {
- FileChannel channel = raf.getChannel();
- channel.truncate(size);
- return size;
- }
-
- return raf.length();
- } finally {
- raf.close();
- }
-
-
- }
-
- @Override
- public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
- String path = filesystemPathForURL(inputURL);
- File file = new File(path);
- return file.exists();
- }
-
- @Override
- OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
- String path = filesystemPathForURL(inputURL);
- File file = new File(path);
- FileOutputStream os = new FileOutputStream(file);
- return os;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/LocalFilesystemURL.java
----------------------------------------------------------------------
diff --git a/src/android/LocalFilesystemURL.java b/src/android/LocalFilesystemURL.java
deleted file mode 100644
index 2bf40c3..0000000
--- a/src/android/LocalFilesystemURL.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-package org.apache.cordova.file;
-
-import java.util.List;
-
-import android.net.Uri;
-
-public class LocalFilesystemURL {
-
- public static final String FILESYSTEM_PROTOCOL = "cdvfile";
-
- Uri URL;
- String filesystemName;
- String fullPath;
-
- public LocalFilesystemURL(Uri URL) {
- this.URL = URL;
- this.filesystemName = this.filesystemNameForLocalURL(URL);
- this.fullPath = this.fullPathForLocalURL(URL);
- }
-
- private String fullPathForLocalURL(Uri URL) {
- if (FILESYSTEM_PROTOCOL.equals(URL.getScheme()) && "localhost".equals(URL.getHost())) {
- String path = URL.getPath();
- if (URL.getQuery() != null) {
- path = path + "?" + URL.getQuery();
- }
- return path.substring(path.indexOf('/', 1));
- } else if ("content".equals(URL.getScheme())) {
- String path = '/' + URL.getHost() + URL.getPath();
- // Re-encode path component to handle Android 4.4+ Content URLs
- return Uri.encode(path,"/");
- }
- return null;
- }
-
- private String filesystemNameForLocalURL(Uri URL) {
- if (FILESYSTEM_PROTOCOL.equals(URL.getScheme()) && "localhost".equals(URL.getHost())) {
- List<String> pathComponents = URL.getPathSegments();
- if (pathComponents != null && pathComponents.size() > 0) {
- return pathComponents.get(0);
- }
- return null;
- } else if ("content".equals(URL.getScheme())) {
- return "content";
- }
- return null;
- }
-
- public LocalFilesystemURL(String strURL) {
- this(Uri.parse(strURL));
- }
-
- public String toString() {
- return "cdvfile://localhost/" + this.filesystemName + this.fullPath;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/NoModificationAllowedException.java
----------------------------------------------------------------------
diff --git a/src/android/NoModificationAllowedException.java b/src/android/NoModificationAllowedException.java
deleted file mode 100644
index 627eafb..0000000
--- a/src/android/NoModificationAllowedException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-package org.apache.cordova.file;
-
-@SuppressWarnings("serial")
-public class NoModificationAllowedException extends Exception {
-
- public NoModificationAllowedException(String message) {
- super(message);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/TypeMismatchException.java
----------------------------------------------------------------------
diff --git a/src/android/TypeMismatchException.java b/src/android/TypeMismatchException.java
deleted file mode 100644
index 1315f9a..0000000
--- a/src/android/TypeMismatchException.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-
-package org.apache.cordova.file;
-
-@SuppressWarnings("serial")
-public class TypeMismatchException extends Exception {
-
- public TypeMismatchException(String message) {
- super(message);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/blackberry10/index.js
----------------------------------------------------------------------
diff --git a/src/blackberry10/index.js b/src/blackberry10/index.js
deleted file mode 100644
index 1e480b5..0000000
--- a/src/blackberry10/index.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-module.exports = {
- setSandbox : function (success, fail, args, env) {
- require("lib/webview").setSandbox(JSON.parse(decodeURIComponent(args[0])));
- new PluginResult(args, env).ok();
- },
-
- isSandboxed : function (success, fail, args, env) {
- new PluginResult(args, env).ok(require("lib/webview").getSandbox() === "1");
- },
-
- resolveLocalPath : function (success, fail, args, env) {
- var homeDir = window.qnx.webplatform.getApplication().getEnv("HOME").replace("/data", "/app/native/"),
- path = homeDir + JSON.parse(decodeURIComponent(args[0])).substring(9);
- require("lib/webview").setSandbox(false);
- new PluginResult(args, env).ok(path);
- }
-};
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ios/CDVAssetLibraryFilesystem.h
----------------------------------------------------------------------
diff --git a/src/ios/CDVAssetLibraryFilesystem.h b/src/ios/CDVAssetLibraryFilesystem.h
deleted file mode 100644
index e09e225..0000000
--- a/src/ios/CDVAssetLibraryFilesystem.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-#import "CDVFile.h"
-
-extern NSString* const kCDVAssetsLibraryPrefix;
-extern NSString* const kCDVAssetsLibraryScheme;
-
-@interface CDVAssetLibraryFilesystem : NSObject<CDVFileSystem> {
-}
-
-- (id) initWithName:(NSString *)name;
-
-@end
[6/8] CB-6521: Remove development branch
Posted by ia...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ios/CDVAssetLibraryFilesystem.m
----------------------------------------------------------------------
diff --git a/src/ios/CDVAssetLibraryFilesystem.m b/src/ios/CDVAssetLibraryFilesystem.m
deleted file mode 100644
index d71d801..0000000
--- a/src/ios/CDVAssetLibraryFilesystem.m
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-#import "CDVFile.h"
-#import "CDVAssetLibraryFilesystem.h"
-#import <Cordova/CDV.h>
-#import <AssetsLibrary/ALAsset.h>
-#import <AssetsLibrary/ALAssetRepresentation.h>
-#import <AssetsLibrary/ALAssetsLibrary.h>
-#import <MobileCoreServices/MobileCoreServices.h>
-
-NSString* const kCDVAssetsLibraryPrefix = @"assets-library://";
-NSString* const kCDVAssetsLibraryScheme = @"assets-library";
-
-@implementation CDVAssetLibraryFilesystem
-@synthesize name=_name;
-
-
-/*
- The CDVAssetLibraryFilesystem works with resources which are identified
- by iOS as
- asset-library://<path>
- and represents them internally as URLs of the form
- cdvfile://localhost/assets-library/<path>
- */
-
-- (NSURL *)assetLibraryURLForLocalURL:(CDVFilesystemURL *)url
-{
- if ([url.url.scheme isEqualToString:kCDVFilesystemURLPrefix]) {
- NSString *path = [[url.url absoluteString] substringFromIndex:[@"cdvfile://localhost/assets-library" length]];
- return [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@", path]];
- }
- return url.url;
-}
-
-- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
-{
- NSDictionary* entry = [self makeEntryForLocalURL:url];
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
-}
-
-- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
- return [self makeEntryForPath:url.fullPath fileSystemName:self.name isDirectory:NO];
-}
-
-- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir
-{
- NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
- NSString* lastPart = [fullPath lastPathComponent];
- if (isDir && ![fullPath hasSuffix:@"/"]) {
- fullPath = [fullPath stringByAppendingString:@"/"];
- }
- [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
- [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
- [dirEntry setObject:fullPath forKey:@"fullPath"];
- [dirEntry setObject:lastPart forKey:@"name"];
- [dirEntry setObject: [NSNumber numberWithInt:([fsName isEqualToString:@"temporary"] ? 0 : 1)] forKey: @"filesystem"];
- [dirEntry setObject:fsName forKey: @"filesystemName"];
-
- return dirEntry;
-}
-
-/* helper function to get the mimeType from the file extension
- * IN:
- * NSString* fullPath - filename (may include path)
- * OUT:
- * NSString* the mime type as type/subtype. nil if not able to determine
- */
-+ (NSString*)getMimeTypeFromPath:(NSString*)fullPath
-{
- NSString* mimeType = nil;
-
- if (fullPath) {
- CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
- if (typeId) {
- mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
- if (!mimeType) {
- // special case for m4a
- if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
- mimeType = @"audio/mp4";
- } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
- mimeType = @"audio/wav";
- }
- }
- CFRelease(typeId);
- }
- }
- return mimeType;
-}
-
-- (id)initWithName:(NSString *)name
-{
- if (self) {
- _name = name;
- }
- return self;
-}
-
-- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
-{
- // return unsupported result for assets-library URLs
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"getFile not supported for assets-library URLs."];
-}
-
-- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
-{
- // we don't (yet?) support getting the parent of an asset
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_READABLE_ERR];
-}
-
-- (void)getMetadataForURL:(CDVFilesystemURL *)url callback:(void (^)(CDVPluginResult *))callback
-{
- __block CDVPluginResult* result = nil;
-
- // In this case, we need to use an asynchronous method to retrieve the file.
- // Because of this, we can't just assign to `result` and send it at the end of the method.
- // Instead, we return after calling the asynchronous method and send `result` in each of the blocks.
- ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
- if (asset) {
- // We have the asset! Retrieve the metadata and send it off.
- NSDate* date = [asset valueForProperty:ALAssetPropertyDate];
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:[date timeIntervalSince1970] * 1000];
- callback(result);
- } else {
- // We couldn't find the asset. Send the appropriate error.
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
- callback(result);
- }
- };
- // TODO(maxw): Consider making this a class variable since it's the same every time.
- ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
- // Retrieving the asset failed for some reason. Send the appropriate error.
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]];
- callback(result);
- };
-
- ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
- [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:url] resultBlock:resultBlock failureBlock:failureBlock];
- return;
-}
-
-- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
-{
- // setMetadata doesn't make sense for asset library files
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
-}
-
-- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
-{
- // return error for assets-library URLs
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
-}
-
-- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
-{
- // return error for assets-library URLs
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"removeRecursively not supported for assets-library URLs."];
-}
-
-- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
-{
- // return unsupported result for assets-library URLs
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"readEntries not supported for assets-library URLs."];
-}
-
-- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
-{
- // assets-library files can't be truncated
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
-}
-
-- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
-{
- // text can't be written into assets-library files
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
-}
-
-- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
-{
- // Copying to an assets library file is not doable, since we can't write it.
- CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
- callback(result);
-}
-
-- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
-{
- NSString *path = nil;
- if ([[url.url scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
- path = [url.url path];
- } else {
- path = url.fullPath;
- }
- if ([path hasSuffix:@"/"]) {
- path = [path substringToIndex:([path length]-1)];
- }
- return path;
-}
-
-- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
-{
- ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
- if (asset) {
- // We have the asset! Get the data and send it off.
- ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
- Byte* buffer = (Byte*)malloc([assetRepresentation size]);
- NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:0.0 length:[assetRepresentation size] error:nil];
- NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];
- NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);
-
- callback(data, MIMEType, NO_ERROR);
- } else {
- callback(nil, nil, NOT_FOUND_ERR);
- }
- };
-
- ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
- // Retrieving the asset failed for some reason. Send the appropriate error.
- NSLog(@"Error: %@", error);
- callback(nil, nil, SECURITY_ERR);
- };
-
- ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
- [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
-}
-
-- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
-{
- // In this case, we need to use an asynchronous method to retrieve the file.
- // Because of this, we can't just assign to `result` and send it at the end of the method.
- // Instead, we return after calling the asynchronous method and send `result` in each of the blocks.
- ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
- if (asset) {
- // We have the asset! Populate the dictionary and send it off.
- NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
- ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
- [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[assetRepresentation size]] forKey:@"size"];
- [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
- NSString* filename = [assetRepresentation filename];
- [fileInfo setObject:filename forKey:@"name"];
- [fileInfo setObject:[CDVAssetLibraryFilesystem getMimeTypeFromPath:filename] forKey:@"type"];
- NSDate* creationDate = [asset valueForProperty:ALAssetPropertyDate];
- NSNumber* msDate = [NSNumber numberWithDouble:[creationDate timeIntervalSince1970] * 1000];
- [fileInfo setObject:msDate forKey:@"lastModifiedDate"];
-
- callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]);
- } else {
- // We couldn't find the asset. Send the appropriate error.
- callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]);
- }
- };
- ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
- // Retrieving the asset failed for some reason. Send the appropriate error.
- callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]);
- };
-
- ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
- [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
- return;
-}
-@end
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ios/CDVFile.h
----------------------------------------------------------------------
diff --git a/src/ios/CDVFile.h b/src/ios/CDVFile.h
deleted file mode 100644
index 63f744c..0000000
--- a/src/ios/CDVFile.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-#import <Foundation/Foundation.h>
-#import <Cordova/CDVPlugin.h>
-
-NSString* const kCDVAssetsLibraryPrefix;
-NSString* const kCDVFilesystemURLPrefix;
-
-enum CDVFileError {
- NO_ERROR = 0,
- NOT_FOUND_ERR = 1,
- SECURITY_ERR = 2,
- ABORT_ERR = 3,
- NOT_READABLE_ERR = 4,
- ENCODING_ERR = 5,
- NO_MODIFICATION_ALLOWED_ERR = 6,
- INVALID_STATE_ERR = 7,
- SYNTAX_ERR = 8,
- INVALID_MODIFICATION_ERR = 9,
- QUOTA_EXCEEDED_ERR = 10,
- TYPE_MISMATCH_ERR = 11,
- PATH_EXISTS_ERR = 12
-};
-typedef int CDVFileError;
-
-@interface CDVFilesystemURL : NSObject {
- NSURL *_url;
- NSString *_fileSystemName;
- NSString *_fullPath;
-}
-
-- (id) initWithString:(NSString*)strURL;
-- (id) initWithURL:(NSURL*)URL;
-+ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL;
-+ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL;
-
-- (NSString *)absoluteURL;
-
-@property (atomic) NSURL *url;
-@property (atomic) NSString *fileSystemName;
-@property (atomic) NSString *fullPath;
-
-@end
-
-@interface CDVFilesystemURLProtocol : NSURLProtocol
-@end
-
-@protocol CDVFileSystem
-- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url;
-- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options;
-- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI;
-- (void)getMetadataForURL:(CDVFilesystemURL *)url callback:(void (^)(CDVPluginResult *))callback;
-- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options;
-- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI;
-- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI;
-- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI;
-- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos;
-- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend;
-- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback;
-- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback;
-- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback;
-
-- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url;
-
-@property (nonatomic,strong) NSString *name;
-
-@optional
-- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURI;
-- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path;
-
-@end
-
-@interface CDVFile : CDVPlugin {
- NSString* rootDocsPath;
- NSString* appDocsPath;
- NSString* appLibraryPath;
- NSString* appTempPath;
-
- NSMutableArray* fileSystems_;
- BOOL userHasAllowed;
-}
-
-- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath;
-- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir;
-- (NSDictionary *)makeEntryForURL:(NSURL *)URL;
-- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath;
-
-- (NSObject<CDVFileSystem> *)filesystemForURL:(CDVFilesystemURL *)localURL;
-
-/* Native Registration API */
-- (void)registerFilesystem:(NSObject<CDVFileSystem> *)fs;
-- (NSObject<CDVFileSystem> *)fileSystemByName:(NSString *)fsName;
-
-/* Exec API */
-- (void)requestFileSystem:(CDVInvokedUrlCommand*)command;
-- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command;
-- (void)getDirectory:(CDVInvokedUrlCommand*)command;
-- (void)getFile:(CDVInvokedUrlCommand*)command;
-- (void)getParent:(CDVInvokedUrlCommand*)command;
-- (void)getMetadata:(CDVInvokedUrlCommand*)command;
-- (void)removeRecursively:(CDVInvokedUrlCommand*)command;
-- (void)remove:(CDVInvokedUrlCommand*)command;
-- (void)copyTo:(CDVInvokedUrlCommand*)command;
-- (void)moveTo:(CDVInvokedUrlCommand*)command;
-- (void)getFileMetadata:(CDVInvokedUrlCommand*)command;
-- (void)readEntries:(CDVInvokedUrlCommand*)command;
-- (void)readAsText:(CDVInvokedUrlCommand*)command;
-- (void)readAsDataURL:(CDVInvokedUrlCommand*)command;
-- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command;
-- (void)write:(CDVInvokedUrlCommand*)command;
-- (void)testFileExists:(CDVInvokedUrlCommand*)command;
-- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command;
-- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command;
-- (void)truncate:(CDVInvokedUrlCommand*)command;
-- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy;
-
-/* Compatibilty with older File API */
-- (NSString*)getMimeTypeFromPath:(NSString*)fullPath;
-- (NSDictionary *)getDirectoryEntry:(NSString *)target isDirectory:(BOOL)bDirRequest;
-
-/* Conversion between filesystem paths and URLs */
-- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)URL;
-
-/* Internal methods for testing */
-- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command;
-
-@property (nonatomic, strong) NSString* rootDocsPath;
-@property (nonatomic, strong) NSString* appDocsPath;
-@property (nonatomic, strong) NSString* appLibraryPath;
-@property (nonatomic, strong) NSString* appTempPath;
-@property (nonatomic, strong) NSString* persistentPath;
-@property (nonatomic, strong) NSString* temporaryPath;
-@property (nonatomic, strong) NSMutableArray* fileSystems;
-
-@property BOOL userHasAllowed;
-
-@end
-
-#define kW3FileTemporary @"temporary"
-#define kW3FilePersistent @"persistent"
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ios/CDVFile.m
----------------------------------------------------------------------
diff --git a/src/ios/CDVFile.m b/src/ios/CDVFile.m
deleted file mode 100644
index 8d0a3d8..0000000
--- a/src/ios/CDVFile.m
+++ /dev/null
@@ -1,1047 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-#import <Cordova/CDV.h>
-#import "CDVFile.h"
-#import "CDVLocalFilesystem.h"
-#import "CDVAssetLibraryFilesystem.h"
-
-CDVFile *filePlugin = nil;
-
-extern NSString * const NSURLIsExcludedFromBackupKey __attribute__((weak_import));
-
-#ifndef __IPHONE_5_1
- NSString* const NSURLIsExcludedFromBackupKey = @"NSURLIsExcludedFromBackupKey";
-#endif
-
-NSString* const kCDVFilesystemURLPrefix = @"cdvfile";
-
-@implementation CDVFilesystemURL
-@synthesize url=_url;
-@synthesize fileSystemName=_fileSystemName;
-@synthesize fullPath=_fullPath;
-
-- (id) initWithString:(NSString *)strURL
-{
- if ( self = [super init] ) {
- NSURL *decodedURL = [NSURL URLWithString:strURL];
- return [self initWithURL:decodedURL];
- }
- return nil;
-}
-
--(id) initWithURL:(NSURL *)URL
-{
- if ( self = [super init] ) {
- _url = URL;
- _fileSystemName = [self filesystemNameForLocalURI:URL];
- _fullPath = [self fullPathForLocalURI:URL];
- }
- return self;
-}
-
-/*
- * IN
- * NSString localURI
- * OUT
- * NSString FileSystem Name for this URI, or nil if it is not recognized.
- */
-- (NSString *)filesystemNameForLocalURI:(NSURL *)uri
-{
- if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) {
- NSArray *pathComponents = [uri pathComponents];
- if (pathComponents != nil && pathComponents.count > 1) {
- return [pathComponents objectAtIndex:1];
- }
- } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
- return @"assets-library";
- }
- return nil;
-}
-
-/*
- * IN
- * NSString localURI
- * OUT
- * NSString fullPath component suitable for an Entry object.
- * The incoming URI should be properly escaped. The returned fullPath is unescaped.
- */
-- (NSString *)fullPathForLocalURI:(NSURL *)uri
-{
- if ([[uri scheme] isEqualToString:kCDVFilesystemURLPrefix] && [[uri host] isEqualToString:@"localhost"]) {
- NSString *path = [uri path];
- if ([uri query]) {
- path = [NSString stringWithFormat:@"%@?%@", path, [uri query]];
- }
- NSRange slashRange = [path rangeOfString:@"/" options:0 range:NSMakeRange(1, path.length-1)];
- if (slashRange.location == NSNotFound) {
- return @"";
- }
- return [path substringFromIndex:slashRange.location];
- } else if ([[uri scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
- return [[uri absoluteString] substringFromIndex:[kCDVAssetsLibraryScheme length]+2];
- }
- return nil;
-}
-
-+ (CDVFilesystemURL *)fileSystemURLWithString:(NSString *)strURL
-{
- return [[CDVFilesystemURL alloc] initWithString:strURL];
-}
-
-+ (CDVFilesystemURL *)fileSystemURLWithURL:(NSURL *)URL
-{
- return [[CDVFilesystemURL alloc] initWithURL:URL];
-}
-
-- (NSString *)absoluteURL
-{
- return [NSString stringWithFormat:@"cdvfile://localhost/%@%@", self.fileSystemName, self.fullPath];
-}
-
-@end
-
-@implementation CDVFilesystemURLProtocol
-
-+ (BOOL)canInitWithRequest:(NSURLRequest*)request
-{
- NSURL* url = [request URL];
- return [[url scheme] isEqualToString:kCDVFilesystemURLPrefix];
-}
-
-+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest*)request
-{
- return request;
-}
-
-+ (BOOL)requestIsCacheEquivalent:(NSURLRequest*)requestA toRequest:(NSURLRequest*)requestB
-{
- return [[[requestA URL] resourceSpecifier] isEqualToString:[[requestB URL] resourceSpecifier]];
-}
-
-- (void)startLoading
-{
- CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithURL:[[self request] URL]];
- NSObject<CDVFileSystem> *fs = [filePlugin filesystemForURL:url];
- [fs readFileAtURL:url start:0 end:-1 callback:^void(NSData *data, NSString *mimetype, CDVFileError error) {
- NSMutableDictionary* responseHeaders = [[NSMutableDictionary alloc] init];
- responseHeaders[@"Cache-Control"] = @"no-cache";
-
- if (!error) {
- responseHeaders[@"Content-Type"] = mimetype;
- NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:200 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders];
- [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
- [[self client] URLProtocol:self didLoadData:data];
- [[self client] URLProtocolDidFinishLoading:self];
- } else {
- NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url.url statusCode:404 HTTPVersion:@"HTTP/1.1"headerFields:responseHeaders];
- [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
- [[self client] URLProtocolDidFinishLoading:self];
- }
- }];
-}
-
-- (void)stopLoading
-{}
-
-- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
- willCacheResponse:(NSCachedURLResponse*)cachedResponse {
- return nil;
-}
-
-@end
-
-
-@implementation CDVFile
-
-@synthesize rootDocsPath, appDocsPath, appLibraryPath, appTempPath, userHasAllowed, fileSystems=fileSystems_;
-
-- (void)registerFilesystem:(NSObject<CDVFileSystem> *)fs {
- [fileSystems_ addObject:fs];
-}
-
-- (NSObject<CDVFileSystem> *)fileSystemByName:(NSString *)fsName
-{
- if (self.fileSystems != nil) {
- for (NSObject<CDVFileSystem> *fs in self.fileSystems) {
- if ([fs.name isEqualToString:fsName]) {
- return fs;
- }
- }
- }
- return nil;
-
-}
-
-- (NSObject<CDVFileSystem> *)filesystemForURL:(CDVFilesystemURL *)localURL {
- if (localURL.fileSystemName == nil) return nil;
- @try {
- return [self fileSystemByName:localURL.fileSystemName];
- }
- @catch (NSException *e) {
- return nil;
- }
-}
-
-- (NSArray *)getExtraFileSystemsPreference:(UIViewController *)vc
-{
- NSString *filesystemsStr = nil;
- if([self.viewController isKindOfClass:[CDVViewController class]]) {
- CDVViewController *vc = (CDVViewController *)self.viewController;
- NSDictionary *settings = [vc settings];
- filesystemsStr = [settings[@"iosextrafilesystems"] lowercaseString];
- }
- if (!filesystemsStr) {
- filesystemsStr = @"library,library-nosync,documents,documents-nosync,cache,bundle,root";
- }
- return [filesystemsStr componentsSeparatedByString:@","];
-}
-
-- (void)makeNonSyncable:(NSString*)path {
- [[NSFileManager defaultManager] createDirectoryAtPath:path
- withIntermediateDirectories:YES
- attributes:nil
- error:nil];
- NSURL* url = [NSURL fileURLWithPath:path];
- [url setResourceValue: [NSNumber numberWithBool: YES]
- forKey: NSURLIsExcludedFromBackupKey error:nil];
-
-}
-
-- (void)registerExtraFileSystems:(NSArray *)filesystems fromAvailableSet:(NSDictionary *)availableFileSystems
-{
- NSMutableSet *installedFilesystems = [[NSMutableSet alloc] initWithCapacity:7];
-
- /* Build non-syncable directories as necessary */
- for (NSString *nonSyncFS in @[@"library-nosync", @"documents-nosync"]) {
- if ([filesystems containsObject:nonSyncFS]) {
- [self makeNonSyncable:availableFileSystems[nonSyncFS]];
- }
- }
-
- /* Register filesystems in order */
- for (NSString *fsName in filesystems) {
- if (![installedFilesystems containsObject:fsName]) {
- NSString *fsRoot = availableFileSystems[fsName];
- if (fsRoot) {
- [filePlugin registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:fsName root:fsRoot]];
- [installedFilesystems addObject:fsName];
- } else {
- NSLog(@"Unrecognized extra filesystem identifier: %@", fsName);
- }
- }
- }
-}
-
-- (NSDictionary *)getAvailableFileSystems
-{
- NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- return @{
- @"library": libPath,
- @"library-nosync": [libPath stringByAppendingPathComponent:@"NoCloud"],
- @"documents": docPath,
- @"documents-nosync": [docPath stringByAppendingPathComponent:@"NoCloud"],
- @"cache": [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0],
- @"bundle": [[NSBundle mainBundle] bundlePath],
- @"root": @"/"
- };
-}
-
-- (void)pluginInitialize
-{
- NSString *location = nil;
- if([self.viewController isKindOfClass:[CDVViewController class]]) {
- CDVViewController *vc = (CDVViewController *)self.viewController;
- NSMutableDictionary *settings = vc.settings;
- location = [[settings objectForKey:@"iospersistentfilelocation"] lowercaseString];
- }
- if (location == nil) {
- // Compatibilty by default (if the config preference is not set, or
- // if we're not embedded in a CDVViewController somehow.)
- location = @"compatibility";
- }
-
- NSError *error;
- if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appTempPath
- withIntermediateDirectories:YES
- attributes:nil
- error:&error]) {
- [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"temporary" root:self.appTempPath]];
- } else {
- NSLog(@"Unable to create temporary directory: %@", error);
- }
- if ([location isEqualToString:@"library"]) {
- if ([[NSFileManager defaultManager] createDirectoryAtPath:self.appLibraryPath
- withIntermediateDirectories:YES
- attributes:nil
- error:&error]) {
- [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.appLibraryPath]];
- } else {
- NSLog(@"Unable to create library directory: %@", error);
- }
- } else if ([location isEqualToString:@"compatibility"]) {
- /*
- * Fall-back to compatibility mode -- this is the logic implemented in
- * earlier versions of this plugin, and should be maintained here so
- * that apps which were originally deployed with older versions of the
- * plugin can continue to provide access to files stored under those
- * versions.
- */
- [self registerFilesystem:[[CDVLocalFilesystem alloc] initWithName:@"persistent" root:self.rootDocsPath]];
- } else {
- NSAssert(false,
- @"File plugin configuration error: Please set iosPersistentFileLocation in config.xml to one of \"library\" (for new applications) or \"compatibility\" (for compatibility with previous versions)");
- }
- [self registerFilesystem:[[CDVAssetLibraryFilesystem alloc] initWithName:@"assets-library"]];
-
- [self registerExtraFileSystems:[self getExtraFileSystemsPreference:self.viewController]
- fromAvailableSet:[self getAvailableFileSystems]];
-
-}
-
-
-- (id)initWithWebView:(UIWebView*)theWebView
-{
- self = (CDVFile*)[super initWithWebView:theWebView];
- if (self) {
- filePlugin = self;
- [NSURLProtocol registerClass:[CDVFilesystemURLProtocol class]];
-
- fileSystems_ = [[NSMutableArray alloc] initWithCapacity:3];
-
- // Get the Library directory path
- NSArray* paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
- self.appLibraryPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"files"];
-
- // Get the Temporary directory path
- self.appTempPath = [NSTemporaryDirectory()stringByStandardizingPath]; // remove trailing slash from NSTemporaryDirectory()
-
- // Get the Documents directory path
- paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- self.rootDocsPath = [paths objectAtIndex:0];
- self.appDocsPath = [self.rootDocsPath stringByAppendingPathComponent:@"files"];
-
- }
-
- return self;
-}
-
-- (CDVFilesystemURL *)fileSystemURLforLocalPath:(NSString *)localPath
-{
- CDVFilesystemURL *localURL = nil;
- NSUInteger shortestFullPath = 0;
-
- // Try all installed filesystems, in order. Return the most match url.
- for (id object in self.fileSystems) {
- if ([object respondsToSelector:@selector(URLforFilesystemPath:)]) {
- CDVFilesystemURL *url = [object URLforFilesystemPath:localPath];
- if (url){
- // A shorter fullPath would imply that the filesystem is a better match for the local path
- if (!localURL || ([[url fullPath] length] < shortestFullPath)) {
- localURL = url;
- shortestFullPath = [[url fullPath] length];
- }
- }
- }
- }
- return localURL;
-}
-
-- (NSNumber*)checkFreeDiskSpace:(NSString*)appPath
-{
- NSFileManager* fMgr = [[NSFileManager alloc] init];
-
- NSError* __autoreleasing pError = nil;
-
- NSDictionary* pDict = [fMgr attributesOfFileSystemForPath:appPath error:&pError];
- NSNumber* pNumAvail = (NSNumber*)[pDict objectForKey:NSFileSystemFreeSize];
-
- return pNumAvail;
-}
-
-/* Request the File System info
- *
- * IN:
- * arguments[0] - type (number as string)
- * TEMPORARY = 0, PERSISTENT = 1;
- * arguments[1] - size
- *
- * OUT:
- * Dictionary representing FileSystem object
- * name - the human readable directory name
- * root = DirectoryEntry object
- * bool isDirectory
- * bool isFile
- * string name
- * string fullPath
- * fileSystem = FileSystem object - !! ignored because creates circular reference !!
- */
-
-- (void)requestFileSystem:(CDVInvokedUrlCommand*)command
-{
- NSArray* arguments = command.arguments;
-
- // arguments
- NSString* strType = [arguments objectAtIndex:0];
- unsigned long long size = [[arguments objectAtIndex:1] longLongValue];
-
- int type = [strType intValue];
- CDVPluginResult* result = nil;
-
- if (type > self.fileSystems.count) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR];
- NSLog(@"No filesystem of type requested");
- } else {
- NSString* fullPath = @"/";
- // check for avail space for size request
- NSNumber* pNumAvail = [self checkFreeDiskSpace:fullPath];
- // NSLog(@"Free space: %@", [NSString stringWithFormat:@"%qu", [ pNumAvail unsignedLongLongValue ]]);
- if (pNumAvail && ([pNumAvail unsignedLongLongValue] < size)) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:QUOTA_EXCEEDED_ERR];
- } else {
- NSObject<CDVFileSystem> *rootFs = [self.fileSystems objectAtIndex:type];
- if (rootFs == nil) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:NOT_FOUND_ERR];
- NSLog(@"No filesystem of type requested");
- } else {
- NSMutableDictionary* fileSystem = [NSMutableDictionary dictionaryWithCapacity:2];
- [fileSystem setObject:rootFs.name forKey:@"name"];
- NSDictionary* dirEntry = [self makeEntryForPath:fullPath fileSystemName:rootFs.name isDirectory:YES];
- [fileSystem setObject:dirEntry forKey:@"root"];
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileSystem];
- }
- }
- }
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/* Creates and returns a dictionary representing an Entry Object
- *
- * IN:
- * NSString* fullPath of the entry
- * int fsType - FileSystem type
- * BOOL isDirectory - YES if this is a directory, NO if is a file
- * OUT:
- * NSDictionary* Entry object
- * bool as NSNumber isDirectory
- * bool as NSNumber isFile
- * NSString* name - last part of path
- * NSString* fullPath
- * NSString* filesystemName - FileSystem name -- actual filesystem will be created on the JS side if necessary, to avoid
- * creating circular reference (FileSystem contains DirectoryEntry which contains FileSystem.....!!)
- */
-- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir
-{
- NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
- NSString* lastPart = [fullPath lastPathComponent];
- if (isDir && ![fullPath hasSuffix:@"/"]) {
- fullPath = [fullPath stringByAppendingString:@"/"];
- }
- [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
- [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
- [dirEntry setObject:fullPath forKey:@"fullPath"];
- [dirEntry setObject:lastPart forKey:@"name"];
- [dirEntry setObject: [NSNumber numberWithInt:([fsName isEqualToString:@"temporary"] ? 0 : 1)] forKey: @"filesystem"];
- [dirEntry setObject:fsName forKey: @"filesystemName"];
- return dirEntry;
-}
-
-- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)localURL
-{
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURL];
- return [fs makeEntryForLocalURL:localURL];
-}
-
-- (NSDictionary *)makeEntryForURL:(NSURL *)URL
-{
- CDVFilesystemURL *fsURL = [CDVFilesystemURL fileSystemURLWithURL:URL];
- return [self makeEntryForLocalURL:fsURL];
-}
-
-/*
- * Given a URI determine the File System information associated with it and return an appropriate W3C entry object
- * IN
- * NSString* localURI: Should be an escaped local filesystem URI
- * OUT
- * Entry object
- * bool isDirectory
- * bool isFile
- * string name
- * string fullPath
- * fileSystem = FileSystem object - !! ignored because creates circular reference FileSystem contains DirectoryEntry which contains FileSystem.....!!
- */
-- (void)resolveLocalFileSystemURI:(CDVInvokedUrlCommand*)command
-{
- // arguments
- NSString* localURIstr = [command.arguments objectAtIndex:0];
- CDVPluginResult* result;
- CDVFilesystemURL* inputURI;
-
- /* Backwards-compatibility: Check for file:// urls */
- if ([localURIstr hasPrefix:@"file://"]) {
- /* This looks like a file url. Get the path, and see if any handlers recognize it. */
- NSURL *fileURL = [NSURL URLWithString:localURIstr];
- NSURL *resolvedFileURL = [fileURL URLByResolvingSymlinksInPath];
- NSString *path = [resolvedFileURL path];
- inputURI = [self fileSystemURLforLocalPath:path];
- } else {
- inputURI = [CDVFilesystemURL fileSystemURLWithString:localURIstr];
- }
- if (inputURI == nil || inputURI.fileSystemName == nil) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR];
- } else {
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:inputURI];
- if (fs == nil) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:ENCODING_ERR];
- } else {
- result = [fs entryForLocalURI:inputURI];
- }
- }
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-
-/* Part of DirectoryEntry interface, creates or returns the specified directory
- * IN:
- * NSString* localURI - local filesystem URI for this directory
- * NSString* path - directory to be created/returned; may be full path or relative path
- * NSDictionary* - Flags object
- * boolean as NSNumber create -
- * if create is true and directory does not exist, create dir and return directory entry
- * if create is true and exclusive is true and directory does exist, return error
- * if create is false and directory does not exist, return error
- * if create is false and the path represents a file, return error
- * boolean as NSNumber exclusive - used in conjunction with create
- * if exclusive is true and create is true - specifies failure if directory already exists
- *
- *
- */
-- (void)getDirectory:(CDVInvokedUrlCommand*)command
-{
- NSMutableArray* arguments = [NSMutableArray arrayWithArray:command.arguments];
- NSMutableDictionary* options = nil;
-
- if ([arguments count] >= 3) {
- options = [arguments objectAtIndex:2 withDefault:nil];
- }
- // add getDir to options and call getFile()
- if (options != nil) {
- options = [NSMutableDictionary dictionaryWithDictionary:options];
- } else {
- options = [NSMutableDictionary dictionaryWithCapacity:1];
- }
- [options setObject:[NSNumber numberWithInt:1] forKey:@"getDir"];
- if ([arguments count] >= 3) {
- [arguments replaceObjectAtIndex:2 withObject:options];
- } else {
- [arguments addObject:options];
- }
- CDVInvokedUrlCommand* subCommand =
- [[CDVInvokedUrlCommand alloc] initWithArguments:arguments
- callbackId:command.callbackId
- className:command.className
- methodName:command.methodName];
-
- [self getFile:subCommand];
-}
-
-/* Part of DirectoryEntry interface, creates or returns the specified file
- * IN:
- * NSString* baseURI - local filesytem URI for the base directory to search
- * NSString* requestedPath - file to be created/returned; may be absolute path or relative path
- * NSDictionary* options - Flags object
- * boolean as NSNumber create -
- * if create is true and file does not exist, create file and return File entry
- * if create is true and exclusive is true and file does exist, return error
- * if create is false and file does not exist, return error
- * if create is false and the path represents a directory, return error
- * boolean as NSNumber exclusive - used in conjunction with create
- * if exclusive is true and create is true - specifies failure if file already exists
- */
-- (void)getFile:(CDVInvokedUrlCommand*)command
-{
- NSString* baseURIstr = [command.arguments objectAtIndex:0];
- CDVFilesystemURL* baseURI = [CDVFilesystemURL fileSystemURLWithString:baseURIstr];
- NSString* requestedPath = [command.arguments objectAtIndex:1];
- NSDictionary* options = [command.arguments objectAtIndex:2 withDefault:nil];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:baseURI];
- CDVPluginResult* result = [fs getFileForURL:baseURI requestedPath:requestedPath options:options];
-
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/*
- * Look up the parent Entry containing this Entry.
- * If this Entry is the root of its filesystem, its parent is itself.
- * IN:
- * NSArray* arguments
- * 0 - NSString* localURI
- * NSMutableDictionary* options
- * empty
- */
-- (void)getParent:(CDVInvokedUrlCommand*)command
-{
- // arguments are URL encoded
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command.arguments objectAtIndex:0]];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- CDVPluginResult* result = [fs getParentForURL:localURI];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/*
- * get MetaData of entry
- * Currently MetaData only includes modificationTime.
- */
-- (void)getMetadata:(CDVInvokedUrlCommand*)command
-{
- // arguments
- NSString* localURIstr = [command.arguments objectAtIndex:0];
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:localURIstr];
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- [fs getMetadataForURL:localURI callback:^(CDVPluginResult* result) {
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
-
-}
-
-/*
- * set MetaData of entry
- * Currently we only support "com.apple.MobileBackup" (boolean)
- */
-- (void)setMetadata:(CDVInvokedUrlCommand*)command
-{
- // arguments
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command.arguments objectAtIndex:0]];
- NSDictionary* options = [command.arguments objectAtIndex:1 withDefault:nil];
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- CDVPluginResult* result = [fs setMetadataForURL:localURI withObject:options];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/* removes the directory or file entry
- * IN:
- * NSArray* arguments
- * 0 - NSString* localURI
- *
- * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir
- * returns INVALID_MODIFICATION_ERR if is non-empty dir or asset library file
- * returns NOT_FOUND_ERR if file or dir is not found
-*/
-- (void)remove:(CDVInvokedUrlCommand*)command
-{
- // arguments
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command.arguments objectAtIndex:0]];
- CDVPluginResult* result = nil;
-
- if ([localURI.fullPath isEqualToString:@""]) {
- // error if try to remove top level (documents or tmp) dir
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
- } else {
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- result = [fs removeFileAtURL:localURI];
- }
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/* recursively removes the directory
- * IN:
- * NSArray* arguments
- * 0 - NSString* localURI
- *
- * returns NO_MODIFICATION_ALLOWED_ERR if is top level directory or no permission to delete dir
- * returns NOT_FOUND_ERR if file or dir is not found
- */
-- (void)removeRecursively:(CDVInvokedUrlCommand*)command
-{
- // arguments
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command.arguments objectAtIndex:0]];
- CDVPluginResult* result = nil;
-
- if ([localURI.fullPath isEqualToString:@""]) {
- // error if try to remove top level (documents or tmp) dir
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
- } else {
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- result = [fs recursiveRemoveFileAtURL:localURI];
- }
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-- (void)copyTo:(CDVInvokedUrlCommand*)command
-{
- [self doCopyMove:command isCopy:YES];
-}
-
-- (void)moveTo:(CDVInvokedUrlCommand*)command
-{
- [self doCopyMove:command isCopy:NO];
-}
-
-/* Copy/move a file or directory to a new location
- * IN:
- * NSArray* arguments
- * 0 - NSString* URL of entry to copy
- * 1 - NSString* URL of the directory into which to copy/move the entry
- * 2 - Optionally, the new name of the entry, defaults to the current name
- * BOOL - bCopy YES if copy, NO if move
- */
-- (void)doCopyMove:(CDVInvokedUrlCommand*)command isCopy:(BOOL)bCopy
-{
- NSArray* arguments = command.arguments;
-
- // arguments
- NSString* srcURLstr = [arguments objectAtIndex:0];
- NSString* destURLstr = [arguments objectAtIndex:1];
-
- CDVPluginResult *result;
-
- if (!srcURLstr || !destURLstr) {
- // either no source or no destination provided
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- return;
- }
-
- CDVFilesystemURL* srcURL = [CDVFilesystemURL fileSystemURLWithString:srcURLstr];
- CDVFilesystemURL* destURL = [CDVFilesystemURL fileSystemURLWithString:destURLstr];
-
- NSObject<CDVFileSystem> *srcFs = [self filesystemForURL:srcURL];
- NSObject<CDVFileSystem> *destFs = [self filesystemForURL:destURL];
-
- // optional argument; use last component from srcFullPath if new name not provided
- NSString* newName = ([arguments count] > 2) ? [arguments objectAtIndex:2] : [srcURL.url lastPathComponent];
- if ([newName rangeOfString:@":"].location != NSNotFound) {
- // invalid chars in new name
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR];
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- return;
- }
-
- [destFs copyFileToURL:destURL withName:newName fromFileSystem:srcFs atURL:srcURL copy:bCopy callback:^(CDVPluginResult* result) {
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
-
-}
-
-- (void)getFileMetadata:(CDVInvokedUrlCommand*)command
-{
- // arguments
- NSString* localURIstr = [command.arguments objectAtIndex:0];
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:localURIstr];
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
-
- [fs getFileMetadataForURL:localURI callback:^(CDVPluginResult* result) {
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
-}
-
-- (void)readEntries:(CDVInvokedUrlCommand*)command
-{
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command.arguments objectAtIndex:0]];
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- CDVPluginResult *result = [fs readEntriesAtURL:localURI];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/* read and return file data
- * IN:
- * NSArray* arguments
- * 0 - NSString* fullPath
- * 1 - NSString* encoding
- * 2 - NSString* start
- * 3 - NSString* end
- */
-- (void)readAsText:(CDVInvokedUrlCommand*)command
-{
- // arguments
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command argumentAtIndex:0]];
- NSString* encoding = [command argumentAtIndex:1];
- NSInteger start = [[command argumentAtIndex:2] integerValue];
- NSInteger end = [[command argumentAtIndex:3] integerValue];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
-
- // TODO: implement
- if ([@"UTF-8" caseInsensitiveCompare : encoding] != NSOrderedSame) {
- NSLog(@"Only UTF-8 encodings are currently supported by readAsText");
- CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ENCODING_ERR];
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- return;
- }
-
- [self.commandDelegate runInBackground:^ {
- [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
- CDVPluginResult* result = nil;
- if (data != nil) {
- NSString* str = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSUTF8StringEncoding freeWhenDone:NO];
- // Check that UTF8 conversion did not fail.
- if (str != nil) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:str];
- result.associatedObject = data;
- } else {
- errorCode = ENCODING_ERR;
- }
- }
- if (result == nil) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
- }];
-}
-
-/* Read content of text file and return as base64 encoded data url.
- * IN:
- * NSArray* arguments
- * 0 - NSString* fullPath
- * 1 - NSString* start
- * 2 - NSString* end
- *
- * Determines the mime type from the file extension, returns ENCODING_ERR if mimetype can not be determined.
- */
-
-- (void)readAsDataURL:(CDVInvokedUrlCommand*)command
-{
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command argumentAtIndex:0]];
- NSInteger start = [[command argumentAtIndex:1] integerValue];
- NSInteger end = [[command argumentAtIndex:2] integerValue];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
-
- [self.commandDelegate runInBackground:^ {
- [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
- CDVPluginResult* result = nil;
- if (data != nil) {
- // TODO: Would be faster to base64 encode directly to the final string.
- NSString* output = [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, [data base64EncodedString]];
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:output];
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
- }];
-}
-
-/* Read content of text file and return as an arraybuffer
- * IN:
- * NSArray* arguments
- * 0 - NSString* fullPath
- * 1 - NSString* start
- * 2 - NSString* end
- */
-
-- (void)readAsArrayBuffer:(CDVInvokedUrlCommand*)command
-{
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command argumentAtIndex:0]];
- NSInteger start = [[command argumentAtIndex:1] integerValue];
- NSInteger end = [[command argumentAtIndex:2] integerValue];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
-
- [self.commandDelegate runInBackground:^ {
- [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
- CDVPluginResult* result = nil;
- if (data != nil) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArrayBuffer:data];
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
- }];
-}
-
-- (void)readAsBinaryString:(CDVInvokedUrlCommand*)command
-{
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command argumentAtIndex:0]];
- NSInteger start = [[command argumentAtIndex:1] integerValue];
- NSInteger end = [[command argumentAtIndex:2] integerValue];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
-
- [self.commandDelegate runInBackground:^ {
- [fs readFileAtURL:localURI start:start end:end callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
- CDVPluginResult* result = nil;
- if (data != nil) {
- NSString* payload = [[NSString alloc] initWithBytesNoCopy:(void*)[data bytes] length:[data length] encoding:NSASCIIStringEncoding freeWhenDone:NO];
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload];
- result.associatedObject = data;
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
- }];
- }];
-}
-
-
-- (void)truncate:(CDVInvokedUrlCommand*)command
-{
- // arguments
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:[command argumentAtIndex:0]];
- unsigned long long pos = (unsigned long long)[[command.arguments objectAtIndex:1] longLongValue];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
- CDVPluginResult *result = [fs truncateFileAtURL:localURI atPosition:pos];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-/* write
- * IN:
- * NSArray* arguments
- * 0 - NSString* localURI of file to write to
- * 1 - NSString* or NSData* data to write
- * 2 - NSNumber* position to begin writing
- */
-- (void)write:(CDVInvokedUrlCommand*)command
-{
- NSString* callbackId = command.callbackId;
- NSArray* arguments = command.arguments;
-
- // arguments
- NSString* localURIstr = [arguments objectAtIndex:0];
- CDVFilesystemURL* localURI = [CDVFilesystemURL fileSystemURLWithString:localURIstr];
- id argData = [arguments objectAtIndex:1];
- unsigned long long pos = (unsigned long long)[[arguments objectAtIndex:2] longLongValue];
-
- NSObject<CDVFileSystem> *fs = [self filesystemForURL:localURI];
-
-
- [fs truncateFileAtURL:localURI atPosition:pos];
- CDVPluginResult *result;
- if ([argData isKindOfClass:[NSString class]]) {
- NSData *encData = [argData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
- result = [fs writeToFileAtURL:localURI withData:encData append:YES];
- } else if ([argData isKindOfClass:[NSData class]]) {
- result = [fs writeToFileAtURL:localURI withData:argData append:YES];
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid parameter type"];
- }
- [self.commandDelegate sendPluginResult:result callbackId:callbackId];
-
-}
-
-#pragma mark Methods for converting between URLs and paths
-
-- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)localURL
-{
- for (NSObject<CDVFileSystem> *fs in self.fileSystems) {
- if ([fs.name isEqualToString:localURL.fileSystemName]) {
- if ([fs respondsToSelector:@selector(filesystemPathForURL:)]) {
- return [fs filesystemPathForURL:localURL];
- }
- }
- }
- return nil;
-}
-
-#pragma mark Undocumented Filesystem API
-
-- (void)testFileExists:(CDVInvokedUrlCommand*)command
-{
- // arguments
- NSString* argPath = [command.arguments objectAtIndex:0];
-
- // Get the file manager
- NSFileManager* fMgr = [NSFileManager defaultManager];
- NSString* appFile = argPath; // [ self getFullPath: argPath];
-
- BOOL bExists = [fMgr fileExistsAtPath:appFile];
- CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(bExists ? 1 : 0)];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-- (void)testDirectoryExists:(CDVInvokedUrlCommand*)command
-{
- // arguments
- NSString* argPath = [command.arguments objectAtIndex:0];
-
- // Get the file manager
- NSFileManager* fMgr = [[NSFileManager alloc] init];
- NSString* appFile = argPath; // [self getFullPath: argPath];
- BOOL bIsDir = NO;
- BOOL bExists = [fMgr fileExistsAtPath:appFile isDirectory:&bIsDir];
-
- CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:((bExists && bIsDir) ? 1 : 0)];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-// Returns number of bytes available via callback
-- (void)getFreeDiskSpace:(CDVInvokedUrlCommand*)command
-{
- // no arguments
-
- NSNumber* pNumAvail = [self checkFreeDiskSpace:self.appDocsPath];
-
- NSString* strFreeSpace = [NSString stringWithFormat:@"%qu", [pNumAvail unsignedLongLongValue]];
- // NSLog(@"Free space is %@", strFreeSpace );
-
- CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:strFreeSpace];
-
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-#pragma mark Compatibility with older File API
-
-- (NSString*)getMimeTypeFromPath:(NSString*)fullPath
-{
- return [CDVLocalFilesystem getMimeTypeFromPath:fullPath];
-}
-
-- (NSDictionary *)getDirectoryEntry:(NSString *)localPath isDirectory:(BOOL)bDirRequest
-{
- CDVFilesystemURL *localURL = [self fileSystemURLforLocalPath:localPath];
- return [self makeEntryForPath:localURL.fullPath fileSystemName:localURL.fileSystemName isDirectory:bDirRequest];
-}
-
-#pragma mark Internal methods for testing
-// Internal methods for testing: Get the on-disk location of a local filesystem url.
-// [Currently used for testing file-transfer]
-
-- (void)_getLocalFilesystemPath:(CDVInvokedUrlCommand*)command
-{
- NSString* localURLstr = [command.arguments objectAtIndex:0];
- CDVFilesystemURL* localURL = [CDVFilesystemURL fileSystemURLWithString:localURLstr];
-
- NSString* fsPath = [self filesystemPathForURL:localURL];
- CDVPluginResult* result;
- if (fsPath) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:fsPath];
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Cannot resolve URL to a file"];
- }
- [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
-}
-
-@end
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ios/CDVLocalFilesystem.h
----------------------------------------------------------------------
diff --git a/src/ios/CDVLocalFilesystem.h b/src/ios/CDVLocalFilesystem.h
deleted file mode 100644
index a0186c8..0000000
--- a/src/ios/CDVLocalFilesystem.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-#import "CDVFile.h"
-
-@interface CDVLocalFilesystem : NSObject<CDVFileSystem> {
- NSString *_name;
- NSString *_fsRoot;
-}
-
-- (id) initWithName:(NSString *)name root:(NSString *)fsRoot;
-+ (NSString*)getMimeTypeFromPath:(NSString*)fullPath;
-
-@property (nonatomic,strong) NSString *fsRoot;
-
-@end
[4/8] CB-6521: Remove development branch
Posted by ia...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/windows8/FileProxy.js
----------------------------------------------------------------------
diff --git a/src/windows8/FileProxy.js b/src/windows8/FileProxy.js
deleted file mode 100644
index 48d3139..0000000
--- a/src/windows8/FileProxy.js
+++ /dev/null
@@ -1,887 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
-*/
-
-var cordova = require('cordova');
-var Entry = require('./Entry'),
- File = require('./File'),
- FileEntry = require('./FileEntry'),
- FileError = require('./FileError'),
- DirectoryEntry = require('./DirectoryEntry'),
- Flags = require('./Flags'),
- FileSystem = require('./FileSystem'),
- LocalFileSystem = require('./LocalFileSystem');
-
-module.exports = {
-
- getFileMetadata:function(win,fail,args) {
- var fullPath = args[0];
-
- Windows.Storage.StorageFile.getFileFromPathAsync(fullPath).done(
- function (storageFile) {
- storageFile.getBasicPropertiesAsync().then(
- function (basicProperties) {
- win(new File(storageFile.name, storageFile.path, storageFile.fileType, basicProperties.dateModified, basicProperties.size));
- }, function () {
- fail && fail(FileError.NOT_READABLE_ERR);
- }
- );
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- },
-
- getMetadata:function(success,fail,args) {
- var fullPath = args[0];
-
- var dealFile = function (sFile) {
- Windows.Storage.StorageFile.getFileFromPathAsync(fullPath).then(
- function (storageFile) {
- return storageFile.getBasicPropertiesAsync();
- },
- function () {
- fail && fail(FileError.NOT_READABLE_ERR);
- }
- // get the basic properties of the file.
- ).then(
- function (basicProperties) {
- success(basicProperties.dateModified);
- },
- function () {
- fail && fail(FileError.NOT_READABLE_ERR);
- }
- );
- };
-
- var dealFolder = function (sFolder) {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(fullPath).then(
- function (storageFolder) {
- return storageFolder.getBasicPropertiesAsync();
- },
- function () {
- fail && fail(FileError.NOT_READABLE_ERR);
- }
- // get the basic properties of the folder.
- ).then(
- function (basicProperties) {
- success(basicProperties.dateModified);
- },
- function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- };
-
- Windows.Storage.StorageFile.getFileFromPathAsync(fullPath).then(
- // the path is file.
- function (sFile) {
- dealFile(sFile);
- },
- // the path is folder
- function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(fullPath).then(
- function (sFolder) {
- dealFolder(sFolder);
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- }
- );
- },
-
- getParent:function(win,fail,args) { // ["fullPath"]
- var fullPath = args[0];
-
- var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder;
- var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder;
-
- if (fullPath == storageFolderPer.path) {
- win(new DirectoryEntry(storageFolderPer.name, storageFolderPer.path));
- return;
- } else if (fullPath == storageFolderTem.path) {
- 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 && fail(FileError.INVALID_STATE_ERR); }
- );
- },
-
- readAsText:function(win,fail,args) {
- var fileName = args[0],
- enc = args[1],
- startPos = args[2],
- endPos = args[3];
-
- var encoding = Windows.Storage.Streams.UnicodeEncoding.utf8;
- if (enc == 'Utf16LE' || enc == 'utf16LE') {
- encoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE;
- } else if (enc == 'Utf16BE' || enc == 'utf16BE') {
- encoding = Windows.Storage.Streams.UnicodeEncoding.utf16BE;
- }
-
- Windows.Storage.StorageFile.getFileFromPathAsync(fileName).then(function(file) {
- return file.openReadAsync();
- }).then(function (stream) {
- startPos = (startPos < 0) ? Math.max(stream.size + startPos, 0) : Math.min(stream.size, startPos);
- endPos = (endPos < 0) ? Math.max(endPos + stream.size, 0) : Math.min(stream.size, endPos);
- stream.seek(startPos);
-
- var readSize = endPos - startPos,
- buffer = new Windows.Storage.Streams.Buffer(readSize);
-
- return stream.readAsync(buffer, readSize, Windows.Storage.Streams.InputStreamOptions.none);
- }).done(function(buffer) {
- win(Windows.Security.Cryptography.CryptographicBuffer.convertBinaryToString(encoding, buffer));
- },function() {
- fail && fail(FileError.NOT_FOUND_ERR);
- });
- },
-
- readAsDataURL:function(win,fail,args) {
- var fileName = args[0];
-
-
- Windows.Storage.StorageFile.getFileFromPathAsync(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 && fail(FileError.NOT_FOUND_ERR);
- }
- );
- },
-
- getDirectory:function(win,fail,args) {
- var fullPath = args[0];
- var path = args[1];
- var options = args[2];
-
- var flag = "";
- if (options !== null) {
- flag = new Flags(options.create, options.exclusive);
- } else {
- flag = new Flags(false, false);
- }
-
- if (path !== null) {
- path = path.replace("/", "\\");
- }
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(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 && 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 && fail(FileError.INVALID_MODIFICATION_ERR);
- }
- );
- } else if (flag.create === false) {
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) {
- fail && fail(FileError.ENCODING_ERR);
- return;
- }
-
- storageFolder.getFolderAsync(path).done(
- function (storageFolder) {
- win(new DirectoryEntry(storageFolder.name, storageFolder.path));
- }, function () {
- // check if path actually points to a file
- storageFolder.getFileAsync(path).done(
- function () {
- fail && fail(FileError.TYPE_MISMATCH_ERR);
- }, function() {
- fail && fail(FileError.NOT_FOUND_ERR);
- });
- }
- );
- }
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- },
-
- remove:function(win,fail,args) {
- var fullPath = args[0];
-
- Windows.Storage.StorageFile.getFileFromPathAsync(fullPath).then(
- function (sFile) {
- Windows.Storage.StorageFile.getFileFromPathAsync(fullPath).done(function (storageFile) {
- storageFile.deleteAsync().done(win, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
-
- });
- });
- },
- function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(fullPath).then(
- function (sFolder) {
- var removeEntry = function () {
- var storageFolderTop = 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 && fail(FileError.NO_MODIFICATION_ALLOWED_ERR);
- return;
- }
- storageFolderTop = storageFolder;
- return storageFolder.createFileQuery().getFilesAsync();
- }, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
-
- }
- // check sub-files.
- ).then(function (fileList) {
- if (fileList) {
- if (fileList.length === 0) {
- return storageFolderTop.createFolderQuery().getFoldersAsync();
- } else {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- }
- }
- // check sub-folders.
- }).then(function (folderList) {
- if (folderList) {
- if (folderList.length === 0) {
- storageFolderTop.deleteAsync().done(win, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
-
- });
- } else {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- }
- }
-
- });
- };
- removeEntry();
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- }
- );
- },
-
- removeRecursively:function(successCallback,fail,args) {
- var fullPath = args[0];
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(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 && fail(FileError.NO_MODIFICATION_ALLOWED_ERR);
- return;
- }
-
- var removeFolders = function (path) {
- return new WinJS.Promise(function (complete) {
- var filePromiseArr = [];
- var storageFolderTop = null;
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(
- function (storageFolder) {
- var fileListPromise = storageFolder.createFileQuery().getFilesAsync();
-
- storageFolderTop = storageFolder;
- return fileListPromise;
- }
- // remove all the files directly under the folder.
- ).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 = storageFolderTop.createFolderQuery().getFoldersAsync();
- return folderListPromise;
- // remove empty folders.
- }).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 () {
- storageFolderTop.deleteAsync().then(complete);
- });
- } else {
- storageFolderTop.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(); }
- });
- });
- });
- },
-
- getFile:function(win,fail,args) {
- var fullPath = args[0];
- var path = args[1];
- var options = args[2];
-
- var flag = "";
- if (options !== null) {
- flag = new Flags(options.create, options.exclusive);
- } else {
- flag = new Flags(false, false);
- }
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(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 && 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 && fail(FileError.INVALID_MODIFICATION_ERR);
- }
- );
- } else if (flag.create === false) {
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) {
- fail && fail(FileError.ENCODING_ERR);
- return;
- }
- storageFolder.getFileAsync(path).done(
- function (storageFile) {
- win(new FileEntry(storageFile.name, storageFile.path));
- }, function () {
- // check if path actually points to a folder
- storageFolder.getFolderAsync(path).done(
- function () {
- fail && fail(FileError.TYPE_MISMATCH_ERR);
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- });
- }
- );
- }
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- },
-
- readEntries:function(win,fail,args) { // ["fullPath"]
- var path = args[0];
-
- var result = [];
-
- 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 DirectoryEntry(folderList[j].name, folderList[j].path));
- }
- }
- });
- WinJS.Promise.join(promiseArr).then(function () {
- win(result);
- });
-
- }, function () { fail && fail(FileError.NOT_FOUND_ERR); });
- },
-
- write:function(win,fail,args) {
- var fileName = args[0],
- data = args[1],
- position = args[2],
- isBinary = args[3];
-
- if (data instanceof ArrayBuffer) {
- data = Array.apply(null, new Uint8Array(data));
- }
-
- var writePromise = isBinary ? Windows.Storage.FileIO.writeBytesAsync : Windows.Storage.FileIO.writeTextAsync;
-
-
- fileName = fileName.split("/").join("\\");
-
-
- // split path to folder and file name
- var path = fileName.substring(0, fileName.lastIndexOf('\\')),
- file = fileName.split('\\').pop();
-
-
- Windows.Storage.StorageFolder.getFolderFromPathAsync(path).done(
- function(storageFolder) {
- storageFolder.createFileAsync(file, Windows.Storage.CreationCollisionOption.openIfExists).done(
- function(storageFile) {
- writePromise(storageFile, data).
- done(function () {
- win(data.length);
- }, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- });
- }, function() {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- }
- );
-
- }, function() {
- fail && fail(FileError.NOT_FOUND_ERR);
- });
- },
-
- truncate:function(win,fail,args) { // ["fileName","size"]
- var fileName = args[0];
- var size = args[1];
-
- Windows.Storage.StorageFile.getFileFromPathAsync(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 = "";
- var successCallBack = function (entry) {
- parentPath = entry.fullPath;
- storageFile.deleteAsync().then(function () {
- return 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 && fail(FileError.NO_MODIFICATION_ALLOWED_ERR);
- });
- });
- });
- };
- entry.getParent(successCallBack, null);
- }, function () { fail && fail(FileError.NOT_FOUND_ERR); });
- }
- });
- }, function () { fail && fail(FileError.NOT_FOUND_ERR); });
- },
-
- copyTo:function(success,fail,args) { // ["fullPath","parent", "newName"]
- var srcPath = args[0];
- var parentFullPath = args[1];
- var name = args[2];
-
- //name can't be invalid
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) {
- fail && fail(FileError.ENCODING_ERR);
- return;
- }
- // copy
- var copyFiles = "";
- Windows.Storage.StorageFile.getFileFromPathAsync(srcPath).then(
- function (sFile) {
- copyFiles = function (srcPath, parentPath) {
- var storageFileTop = null;
- Windows.Storage.StorageFile.getFileFromPathAsync(srcPath).then(function (storageFile) {
- storageFileTop = storageFile;
- return Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath);
- }, function () {
-
- fail && fail(FileError.NOT_FOUND_ERR);
- }).then(function (storageFolder) {
- storageFileTop.copyAsync(storageFolder, name, Windows.Storage.NameCollisionOption.failIfExists).then(function (storageFile) {
-
- success(new FileEntry(storageFile.name, storageFile.path));
- }, function () {
-
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- });
- }, function () {
-
- fail && fail(FileError.NOT_FOUND_ERR);
- });
- };
- var copyFinish = function (srcPath, parentPath) {
- copyFiles(srcPath, parentPath);
- };
- copyFinish(srcPath, parentFullPath);
- },
- function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(
- function (sFolder) {
- copyFiles = function (srcPath, parentPath) {
- var coreCopy = function (storageFolderTop, complete) {
- storageFolderTop.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);
- });
- });
- }
- });
- };
-
- return new WinJS.Promise(function (complete) {
- var storageFolderTop = null;
- var filePromiseArr = [];
- var fileListTop = null;
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(function (storageFolder) {
- storageFolderTop = storageFolder;
- return storageFolder.createFileQuery().getFilesAsync();
- }).then(function (fileList) {
- fileListTop = fileList;
- if (fileList) {
- return Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath);
- }
- }).then(function (targetStorageFolder) {
- for (var i = 0; i < fileListTop.length; i++) {
- filePromiseArr.push(fileListTop[i].copyAsync(targetStorageFolder));
- }
- WinJS.Promise.join(filePromiseArr).done(function () {
- coreCopy(storageFolderTop, complete);
- }, function() {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- });
- });
- });
- };
- var copyFinish = function (srcPath, parentPath) {
- 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 && fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- //can't copy into itself
- if (srcPath == parentPath) {
- fail && 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 && fail(FileError.NOT_FOUND_ERR); }
- );
- });
- }, function () { fail && fail(FileError.INVALID_MODIFICATION_ERR); });
- }, function () { fail && fail(FileError.INVALID_MODIFICATION_ERR); });
- };
- copyFinish(srcPath, parentFullPath);
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- }
- );
- },
-
- moveTo:function(success,fail,args) {
- var srcPath = args[0];
- var parentFullPath = args[1];
- var name = args[2];
-
-
- //name can't be invalid
- if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) {
- fail && fail(FileError.ENCODING_ERR);
- return;
- }
-
- var moveFiles = "";
- Windows.Storage.StorageFile.getFileFromPathAsync(srcPath).then(
- function (sFile) {
- moveFiles = function (srcPath, parentPath) {
- var storageFileTop = null;
- Windows.Storage.StorageFile.getFileFromPathAsync(srcPath).then(function (storageFile) {
- storageFileTop = storageFile;
- return Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath);
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }).then(function (storageFolder) {
- storageFileTop.moveAsync(storageFolder, name, Windows.Storage.NameCollisionOption.replaceExisting).then(function () {
- success(new FileEntry(name, storageFileTop.path));
- }, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- });
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- });
- };
- var moveFinish = function (srcPath, parentPath) {
- //can't copy onto itself
- if (srcPath == parentPath + "\\" + name) {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- moveFiles(srcPath, parentFullPath);
- };
- moveFinish(srcPath, parentFullPath);
- },
- function () {
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(
- function (sFolder) {
- moveFiles = function (srcPath, parentPath) {
- var coreMove = function (storageFolderTop, complete) {
- storageFolderTop.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);
- });
- });
- }
- });
- };
- return new WinJS.Promise(function (complete) {
- var storageFolderTop = null;
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(function (storageFolder) {
- storageFolderTop = storageFolder;
- return 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 () {
- coreMove(storageFolderTop, complete);
- }, function () { });
- });
- });
- });
- };
- var moveFinish = function (srcPath, parentPath) {
- var originFolderTop = null;
- Windows.Storage.StorageFolder.getFolderFromPathAsync(srcPath).then(function (originFolder) {
- originFolderTop = originFolder;
- return Windows.Storage.StorageFolder.getFolderFromPathAsync(parentPath);
- }, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- }).then(function (storageFolder) {
- return storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists);
- }, function () {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- }).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 && fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- //can't copy onto itself
- if (srcPath == newStorageFolder.path) {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- //can't copy into itself
- if (srcPath == parentPath) {
- fail && fail(FileError.INVALID_MODIFICATION_ERR);
- return;
- }
- moveFiles(srcPath, newStorageFolder.path).then(function () {
- var successCallback = function () {
- success(new DirectoryEntry(name, newStorageFolder.path));
- };
- var temp = new DirectoryEntry(originFolderTop.name, originFolderTop.path).removeRecursively(successCallback, fail);
-
- }, function () { console.log("error!"); });
- });
- });
- }, function () { fail && fail(FileError.INVALID_MODIFICATION_ERR); });
-
- };
- moveFinish(srcPath, parentFullPath);
- }, function () {
- fail && fail(FileError.NOT_FOUND_ERR);
- }
- );
- }
- );
- },
- tempFileSystem:null,
-
- persistentFileSystem:null,
-
- requestFileSystem:function(win,fail,args) {
- var type = args[0];
- var size = args[1];
-
- var filePath = "";
- var result = null;
- var fsTypeName = "";
-
- switch (type) {
- case LocalFileSystem.TEMPORARY:
- filePath = Windows.Storage.ApplicationData.current.temporaryFolder.path;
- fsTypeName = "temporary";
- break;
- case LocalFileSystem.PERSISTENT:
- filePath = Windows.Storage.ApplicationData.current.localFolder.path;
- fsTypeName = "persistent";
- break;
- }
-
- var MAX_SIZE = 10000000000;
- if (size > MAX_SIZE) {
- fail && fail(FileError.QUOTA_EXCEEDED_ERR);
- return;
- }
-
- var fileSystem = new FileSystem(fsTypeName, new DirectoryEntry(fsTypeName, filePath));
- result = fileSystem;
- win(result);
- },
-
- resolveLocalFileSystemURI:function(success,fail,args) {
- var uri = args[0];
-
- var path = uri;
-
- // 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 = Windows.Storage.ApplicationData.current.localFolder.path + "\\" + String(path).substr(8);
- } else {
- // method should not let read files outside of the [APP HASH]/Local or [APP HASH]/temp folders
- if (path.indexOf(Windows.Storage.ApplicationData.current.temporaryFolder.path) != 0 &&
- path.indexOf(Windows.Storage.ApplicationData.current.localFolder.path) != 0) {
- fail && fail(FileError.ENCODING_ERR);
- return;
- }
- }
-
- // refine path format to make sure it is correct
- path = path.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 && fail(FileError.NOT_FOUND_ERR);
- }
- );
- }
- );
- }
-
-
-};
-
-require("cordova/exec/proxy").add("File",module.exports);
[5/8] CB-6521: Remove development branch
Posted by ia...@apache.org.
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ios/CDVLocalFilesystem.m
----------------------------------------------------------------------
diff --git a/src/ios/CDVLocalFilesystem.m b/src/ios/CDVLocalFilesystem.m
deleted file mode 100644
index 3682ab1..0000000
--- a/src/ios/CDVLocalFilesystem.m
+++ /dev/null
@@ -1,729 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-
-#import "CDVFile.h"
-#import "CDVLocalFilesystem.h"
-#import <Cordova/CDV.h>
-#import <MobileCoreServices/MobileCoreServices.h>
-#import <sys/xattr.h>
-
-@implementation CDVLocalFilesystem
-@synthesize name=_name, fsRoot=_fsRoot;
-
-- (id) initWithName:(NSString *)name root:(NSString *)fsRoot
-{
- if (self) {
- _name = name;
- _fsRoot = fsRoot;
- }
- return self;
-}
-
-/*
- * IN
- * NSString localURI
- * OUT
- * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the
- * URI represents a non-existent path, or is unrecognized or otherwise malformed.
- */
-- (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
-{
- CDVPluginResult* result = nil;
- NSDictionary* entry = [self makeEntryForLocalURL:url];
- if (entry) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
- } else {
- // return NOT_FOUND_ERR
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
- }
- return result;
-}
-- (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
- NSString *path = [self filesystemPathForURL:url];
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- BOOL isDir = NO;
- // see if exists and is file or dir
- BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir];
- if (bExists) {
- return [self makeEntryForPath:url.fullPath fileSystemName:url.fileSystemName isDirectory:isDir];
- } else {
- return nil;
- }
-}
-- (NSDictionary*)makeEntryForPath:(NSString*)fullPath fileSystemName:(NSString *)fsName isDirectory:(BOOL)isDir
-{
- NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
- NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent];
- if (isDir && ![fullPath hasSuffix:@"/"]) {
- fullPath = [fullPath stringByAppendingString:@"/"];
- }
- [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
- [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
- [dirEntry setObject:fullPath forKey:@"fullPath"];
- [dirEntry setObject:lastPart forKey:@"name"];
- [dirEntry setObject: [NSNumber numberWithInt:([fsName isEqualToString:@"temporary"] ? 0 : 1)] forKey: @"filesystem"];
- [dirEntry setObject:fsName forKey: @"filesystemName"];
- dirEntry[@"nativeURL"] = [[NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]] absoluteString];
-
-
- return dirEntry;
-}
-
-- (NSString *)stripQueryParametersFromPath:(NSString *)fullPath
-{
- NSRange questionMark = [fullPath rangeOfString:@"?"];
- if (questionMark.location != NSNotFound) {
- return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)];
- }
- return fullPath;
-}
-
-- (NSString *)filesystemPathForFullPath:(NSString *)fullPath
-{
- NSString *path = nil;
- NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath];
- path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath];
- if ([path length] > 1 && [path hasSuffix:@"/"]) {
- path = [path substringToIndex:([path length]-1)];
- }
- return path;
-}
-/*
- * IN
- * NSString localURI
- * OUT
- * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
- * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
- * or if the URL is malformed.
- * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
- */
-- (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
-{
- return [self filesystemPathForFullPath:url.fullPath];
-}
-
-- (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath
-{
- if (fullPath) {
- if ([fullPath hasPrefix:@"/"]) {
- return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, fullPath]];
- }
- return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, fullPath]];
- }
- return nil;
-}
-
-- (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path
-{
- return [self URLforFullPath:[[self fullPathForFileSystemPath:path] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
-
-}
-
-- (NSString *)normalizePath:(NSString *)rawPath
-{
- // If this is an absolute path, the first path component will be '/'. Skip it if that's the case
- BOOL isAbsolutePath = [rawPath hasPrefix:@"/"];
- if (isAbsolutePath) {
- rawPath = [rawPath substringFromIndex:1];
- }
- NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]];
- for (int index = 0; index < [components count]; ++index) {
- if ([[components objectAtIndex:index] isEqualToString:@".."]) {
- [components removeObjectAtIndex:index];
- if (index > 0) {
- [components removeObjectAtIndex:index-1];
- --index;
- }
- }
- }
-
- if (isAbsolutePath) {
- return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]];
- } else {
- return [components componentsJoinedByString:@"/"];
- }
-
-
-}
-
-- (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
-{
- CDVPluginResult* result = nil;
- BOOL bDirRequest = NO;
- BOOL create = NO;
- BOOL exclusive = NO;
- int errorCode = 0; // !!! risky - no error code currently defined for 0
-
- if ([options valueForKeyIsNumber:@"create"]) {
- create = [(NSNumber*)[options valueForKey:@"create"] boolValue];
- }
- if ([options valueForKeyIsNumber:@"exclusive"]) {
- exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue];
- }
-
- if ([options valueForKeyIsNumber:@"getDir"]) {
- // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method
- bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue];
- }
- // see if the requested path has invalid characters - should we be checking for more than just ":"?
- if ([requestedPath rangeOfString:@":"].location != NSNotFound) {
- errorCode = ENCODING_ERR;
- } else {
- // Build new fullPath for the requested resource.
- // We concatenate the two paths together, and then scan the resulting string to remove
- // parent ("..") references. Any parent references at the beginning of the string are
- // silently removed.
- NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:[requestedPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
- combinedPath = [self normalizePath:combinedPath];
- CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath];
-
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- BOOL bIsDir;
- BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir];
- if (bExists && (create == NO) && (bIsDir == !bDirRequest)) {
- // path exists and is not of requested type - return TYPE_MISMATCH_ERR
- errorCode = TYPE_MISMATCH_ERR;
- } else if (!bExists && (create == NO)) {
- // path does not exist and create is false - return NOT_FOUND_ERR
- errorCode = NOT_FOUND_ERR;
- } else if (bExists && (create == YES) && (exclusive == YES)) {
- // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR
- errorCode = PATH_EXISTS_ERR;
- } else {
- // if bExists and create == YES - just return data
- // if bExists and create == NO - just return data
- // if !bExists and create == YES - create and return data
- BOOL bSuccess = YES;
- NSError __autoreleasing* pError = nil;
- if (!bExists && (create == YES)) {
- if (bDirRequest) {
- // create the dir
- bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError];
- } else {
- // create the empty file
- bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil];
- }
- }
- if (!bSuccess) {
- errorCode = ABORT_ERR;
- if (pError) {
- NSLog(@"error creating directory: %@", [pError localizedDescription]);
- }
- } else {
- // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]);
- // file existed or was created
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath fileSystemName:baseURI.fileSystemName isDirectory:bDirRequest]];
- }
- } // are all possible conditions met?
- }
-
- if (errorCode > 0) {
- // create error callback
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
- return result;
-
-}
-
-- (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
-{
- CDVPluginResult* result = nil;
- CDVFilesystemURL *newURI = nil;
- if ([localURI.fullPath isEqualToString:@""]) {
- // return self
- newURI = localURI;
- } else {
- newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */
- }
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- BOOL bIsDir;
- BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir];
- if (bExists) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath fileSystemName:newURI.fileSystemName isDirectory:bIsDir]];
- } else {
- // invalid path or file does not exist
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
- }
- return result;
-}
-
-- (void)getMetadataForURL:(CDVFilesystemURL *)url callback:(void (^)(CDVPluginResult *))callback
-{
-
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- NSError* __autoreleasing error = nil;
-
- CDVPluginResult *result;
- NSDictionary* fileAttribs = [fileMgr attributesOfItemAtPath:[self filesystemPathForURL:url] error:&error];
-
- if (fileAttribs) {
- // Ensure that directories (and other non-regular files) report size of 0
- unsigned long long size = ([fileAttribs fileType] == NSFileTypeRegular ? [fileAttribs fileSize] : 0);
- NSDate* modDate = [fileAttribs fileModificationDate];
- if (modDate) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:@{@"modificationTime": @([modDate timeIntervalSince1970] * 1000), @"size": @(size)}];
- }
- } else {
- // didn't get fileAttribs
- CDVFileError errorCode = ABORT_ERR;
- NSLog(@"error getting metadata: %@", [error localizedDescription]);
- if ([error code] == NSFileNoSuchFileError) {
- errorCode = NOT_FOUND_ERR;
- }
- // log [NSNumber numberWithDouble: theMessage] objCtype to see what it returns
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errorCode];
- }
- if (!result) {
- // invalid path or file does not exist
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION];
- }
- callback(result);
-}
-
-- (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
-{
- BOOL ok = NO;
-
- NSString* filePath = [self filesystemPathForURL:localURI];
- // we only care about this iCloud key for now.
- // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute)
- NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup";
- id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey];
-
- if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) {
- if (IsAtLeastiOSVersion(@"5.1")) {
- NSURL* url = [NSURL fileURLWithPath:filePath];
- NSError* __autoreleasing error = nil;
-
- ok = [url setResourceValue:[NSNumber numberWithBool:[iCloudBackupExtendedAttributeValue boolValue]] forKey:NSURLIsExcludedFromBackupKey error:&error];
- } else { // below 5.1 (deprecated - only really supported in 5.01)
- u_int8_t value = [iCloudBackupExtendedAttributeValue intValue];
- if (value == 0) { // remove the attribute (allow backup, the default)
- ok = (removexattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], 0) == 0);
- } else { // set the attribute (skip backup)
- ok = (setxattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], &value, sizeof(value), 0, 0) == 0);
- }
- }
- }
-
- if (ok) {
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
- } else {
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
- }
-}
-
-/* remove the file or directory (recursively)
- * IN:
- * NSString* fullPath - the full path to the file or directory to be removed
- * NSString* callbackId
- * called from remove and removeRecursively - check all pubic api specific error conditions (dir not empty, etc) before calling
- */
-
-- (CDVPluginResult*)doRemove:(NSString*)fullPath
-{
- CDVPluginResult* result = nil;
- BOOL bSuccess = NO;
- NSError* __autoreleasing pError = nil;
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
-
- @try {
- bSuccess = [fileMgr removeItemAtPath:fullPath error:&pError];
- if (bSuccess) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
- } else {
- // see if we can give a useful error
- CDVFileError errorCode = ABORT_ERR;
- NSLog(@"error removing filesystem entry at %@: %@", fullPath, [pError localizedDescription]);
- if ([pError code] == NSFileNoSuchFileError) {
- errorCode = NOT_FOUND_ERR;
- } else if ([pError code] == NSFileWriteNoPermissionError) {
- errorCode = NO_MODIFICATION_ALLOWED_ERR;
- }
-
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
- } @catch(NSException* e) { // NSInvalidArgumentException if path is . or ..
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:SYNTAX_ERR];
- }
-
- return result;
-}
-
-- (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
-{
- NSString *fileSystemPath = [self filesystemPathForURL:localURI];
-
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- BOOL bIsDir = NO;
- BOOL bExists = [fileMgr fileExistsAtPath:fileSystemPath isDirectory:&bIsDir];
- if (!bExists) {
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
- }
- if (bIsDir && ([[fileMgr contentsOfDirectoryAtPath:fileSystemPath error:nil] count] != 0)) {
- // dir is not empty
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
- }
- return [self doRemove:fileSystemPath];
-}
-
-- (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
-{
- NSString *fileSystemPath = [self filesystemPathForURL:localURI];
- return [self doRemove:fileSystemPath];
-}
-
-/*
- * IN
- * NSString localURI
- * OUT
- * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
- * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
- * or if the URL is malformed.
- * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
- */
-- (NSString *)fullPathForFileSystemPath:(NSString *)fsPath
-{
- if ([fsPath hasPrefix:self.fsRoot]) {
- return [fsPath substringFromIndex:[self.fsRoot length]];
- }
- return nil;
-}
-
-
-- (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
-{
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- NSError* __autoreleasing error = nil;
- NSString *fileSystemPath = [self filesystemPathForURL:localURI];
-
- NSArray* contents = [fileMgr contentsOfDirectoryAtPath:fileSystemPath error:&error];
-
- if (contents) {
- NSMutableArray* entries = [NSMutableArray arrayWithCapacity:1];
- if ([contents count] > 0) {
- // create an Entry (as JSON) for each file/dir
- for (NSString* name in contents) {
- // see if is dir or file
- NSString* entryPath = [fileSystemPath stringByAppendingPathComponent:name];
- BOOL bIsDir = NO;
- [fileMgr fileExistsAtPath:entryPath isDirectory:&bIsDir];
- NSDictionary* entryDict = [self makeEntryForPath:[self fullPathForFileSystemPath:entryPath] fileSystemName:localURI.fileSystemName isDirectory:bIsDir];
- [entries addObject:entryDict];
- }
- }
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:entries];
- } else {
- // assume not found but could check error for more specific error conditions
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
- }
-}
-
-- (unsigned long long)truncateFile:(NSString*)filePath atPosition:(unsigned long long)pos
-{
- unsigned long long newPos = 0UL;
-
- NSFileHandle* file = [NSFileHandle fileHandleForWritingAtPath:filePath];
-
- if (file) {
- [file truncateFileAtOffset:(unsigned long long)pos];
- newPos = [file offsetInFile];
- [file synchronizeFile];
- [file closeFile];
- }
- return newPos;
-}
-
-- (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
-{
- unsigned long long newPos = [self truncateFile:[self filesystemPathForURL:localURI] atPosition:pos];
- return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)newPos];
-}
-
-- (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
-{
- NSString *filePath = [self filesystemPathForURL:localURL];
-
- CDVPluginResult* result = nil;
- CDVFileError errCode = INVALID_MODIFICATION_ERR;
- int bytesWritten = 0;
-
- if (filePath) {
- NSOutputStream* fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:shouldAppend];
- if (fileStream) {
- NSUInteger len = [encData length];
- [fileStream open];
-
- bytesWritten = (int)[fileStream write:[encData bytes] maxLength:len];
-
- [fileStream close];
- if (bytesWritten > 0) {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:bytesWritten];
- // } else {
- // can probably get more detailed error info via [fileStream streamError]
- // errCode already set to INVALID_MODIFICATION_ERR;
- // bytesWritten = 0; // may be set to -1 on error
- }
- } // else fileStream not created return INVALID_MODIFICATION_ERR
- } else {
- // invalid filePath
- errCode = NOT_FOUND_ERR;
- }
- if (!result) {
- // was an error
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errCode];
- }
- return result;
-}
-
-/**
- * Helper function to check to see if the user attempted to copy an entry into its parent without changing its name,
- * or attempted to copy a directory into a directory that it contains directly or indirectly.
- *
- * IN:
- * NSString* srcDir
- * NSString* destinationDir
- * OUT:
- * YES copy/ move is allows
- * NO move is onto itself
- */
-- (BOOL)canCopyMoveSrc:(NSString*)src ToDestination:(NSString*)dest
-{
- // This weird test is to determine if we are copying or moving a directory into itself.
- // Copy /Documents/myDir to /Documents/myDir-backup is okay but
- // Copy /Documents/myDir to /Documents/myDir/backup not okay
- BOOL copyOK = YES;
- NSRange range = [dest rangeOfString:src];
-
- if (range.location != NSNotFound) {
- NSRange testRange = {range.length - 1, ([dest length] - range.length)};
- NSRange resultRange = [dest rangeOfString:@"/" options:0 range:testRange];
- if (resultRange.location != NSNotFound) {
- copyOK = NO;
- }
- }
- return copyOK;
-}
-
-- (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
-{
- NSFileManager *fileMgr = [[NSFileManager alloc] init];
- NSString *destRootPath = [self filesystemPathForURL:destURL];
- BOOL bDestIsDir = NO;
- BOOL bDestExists = [fileMgr fileExistsAtPath:destRootPath isDirectory:&bDestIsDir];
-
- NSString *newFileSystemPath = [destRootPath stringByAppendingPathComponent:newName];
- NSString *newFullPath = [self fullPathForFileSystemPath:newFileSystemPath];
-
- BOOL bNewIsDir = NO;
- BOOL bNewExists = [fileMgr fileExistsAtPath:newFileSystemPath isDirectory:&bNewIsDir];
-
- CDVPluginResult *result = nil;
- int errCode = 0;
-
- if (!bDestExists) {
- // the destination root does not exist
- errCode = NOT_FOUND_ERR;
- }
-
- else if ([srcFs isKindOfClass:[CDVLocalFilesystem class]]) {
- /* Same FS, we can shortcut with NSFileManager operations */
- NSString *srcFullPath = [srcFs filesystemPathForURL:srcURL];
-
- BOOL bSrcIsDir = NO;
- BOOL bSrcExists = [fileMgr fileExistsAtPath:srcFullPath isDirectory:&bSrcIsDir];
-
- if (!bSrcExists) {
- // the source does not exist
- errCode = NOT_FOUND_ERR;
- } else if ([newFileSystemPath isEqualToString:srcFullPath]) {
- // source and destination can not be the same
- errCode = INVALID_MODIFICATION_ERR;
- } else if (bSrcIsDir && (bNewExists && !bNewIsDir)) {
- // can't copy/move dir to file
- errCode = INVALID_MODIFICATION_ERR;
- } else { // no errors yet
- NSError* __autoreleasing error = nil;
- BOOL bSuccess = NO;
- if (bCopy) {
- if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {
- // can't copy dir into self
- errCode = INVALID_MODIFICATION_ERR;
- } else if (bNewExists) {
- // the full destination should NOT already exist if a copy
- errCode = PATH_EXISTS_ERR;
- } else {
- bSuccess = [fileMgr copyItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];
- }
- } else { // move
- // iOS requires that destination must not exist before calling moveTo
- // is W3C INVALID_MODIFICATION_ERR error if destination dir exists and has contents
- //
- if (!bSrcIsDir && (bNewExists && bNewIsDir)) {
- // can't move a file to directory
- errCode = INVALID_MODIFICATION_ERR;
- } else if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {
- // can't move a dir into itself
- errCode = INVALID_MODIFICATION_ERR;
- } else if (bNewExists) {
- if (bNewIsDir && ([[fileMgr contentsOfDirectoryAtPath:newFileSystemPath error:NULL] count] != 0)) {
- // can't move dir to a dir that is not empty
- errCode = INVALID_MODIFICATION_ERR;
- newFileSystemPath = nil; // so we won't try to move
- } else {
- // remove destination so can perform the moveItemAtPath
- bSuccess = [fileMgr removeItemAtPath:newFileSystemPath error:NULL];
- if (!bSuccess) {
- errCode = INVALID_MODIFICATION_ERR; // is this the correct error?
- newFileSystemPath = nil;
- }
- }
- } else if (bNewIsDir && [newFileSystemPath hasPrefix:srcFullPath]) {
- // can't move a directory inside itself or to any child at any depth;
- errCode = INVALID_MODIFICATION_ERR;
- newFileSystemPath = nil;
- }
-
- if (newFileSystemPath != nil) {
- bSuccess = [fileMgr moveItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];
- }
- }
- if (bSuccess) {
- // should verify it is there and of the correct type???
- NSDictionary* newEntry = [self makeEntryForPath:newFullPath fileSystemName:destURL.fileSystemName isDirectory:bSrcIsDir];
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];
- } else {
- if (error) {
- if (([error code] == NSFileReadUnknownError) || ([error code] == NSFileReadTooLargeError)) {
- errCode = NOT_READABLE_ERR;
- } else if ([error code] == NSFileWriteOutOfSpaceError) {
- errCode = QUOTA_EXCEEDED_ERR;
- } else if ([error code] == NSFileWriteNoPermissionError) {
- errCode = NO_MODIFICATION_ALLOWED_ERR;
- }
- }
- }
- }
- } else {
- // Need to copy the hard way
- [srcFs readFileAtURL:srcURL start:0 end:-1 callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
- CDVPluginResult* result = nil;
- if (data != nil) {
- BOOL bSuccess = [data writeToFile:newFileSystemPath atomically:YES];
- if (bSuccess) {
- // should verify it is there and of the correct type???
- NSDictionary* newEntry = [self makeEntryForPath:newFullPath fileSystemName:destURL.fileSystemName isDirectory:NO];
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ABORT_ERR];
- }
- } else {
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
- }
- callback(result);
- }];
- return; // Async IO; return without callback.
- }
- if (result == nil) {
- if (!errCode) {
- errCode = INVALID_MODIFICATION_ERR; // Catch-all default
- }
- result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errCode];
- }
- callback(result);
-}
-
-/* helper function to get the mimeType from the file extension
- * IN:
- * NSString* fullPath - filename (may include path)
- * OUT:
- * NSString* the mime type as type/subtype. nil if not able to determine
- */
-+ (NSString*)getMimeTypeFromPath:(NSString*)fullPath
-{
- NSString* mimeType = nil;
-
- if (fullPath) {
- CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
- if (typeId) {
- mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
- if (!mimeType) {
- // special case for m4a
- if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
- mimeType = @"audio/mp4";
- } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
- mimeType = @"audio/wav";
- }
- }
- CFRelease(typeId);
- }
- }
- return mimeType;
-}
-
-- (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
-{
- NSString *path = [self filesystemPathForURL:localURL];
-
- NSString* mimeType = [CDVLocalFilesystem getMimeTypeFromPath:path];
- if (mimeType == nil) {
- mimeType = @"*/*";
- }
- NSFileHandle* file = [NSFileHandle fileHandleForReadingAtPath:path];
- if (start > 0) {
- [file seekToFileOffset:start];
- }
-
- NSData* readData;
- if (end < 0) {
- readData = [file readDataToEndOfFile];
- } else {
- readData = [file readDataOfLength:(end - start)];
- }
- [file closeFile];
-
- callback(readData, mimeType, readData != nil ? NO_ERROR : NOT_FOUND_ERR);
-}
-
-- (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
-{
- NSString *path = [self filesystemPathForURL:localURL];
- NSFileManager* fileMgr = [[NSFileManager alloc] init];
- BOOL bIsDir = NO;
- // make sure it exists and is not a directory
- BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&bIsDir];
- if (!bExists || bIsDir) {
- callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]);
- } else {
- // create dictionary of file info
- NSError* __autoreleasing error = nil;
- NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:path error:&error];
- NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
- [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[fileAttrs fileSize]] forKey:@"size"];
- [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
- [fileInfo setObject:@"" forKey:@"type"]; // can't easily get the mimetype unless create URL, send request and read response so skipping
- [fileInfo setObject:[path lastPathComponent] forKey:@"name"];
- NSDate* modDate = [fileAttrs fileModificationDate];
- NSNumber* msDate = [NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000];
- [fileInfo setObject:msDate forKey:@"lastModifiedDate"];
- callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]);
- }
-}
-
-@end
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ubuntu/file.cpp
----------------------------------------------------------------------
diff --git a/src/ubuntu/file.cpp b/src/ubuntu/file.cpp
deleted file mode 100644
index 4c751e2..0000000
--- a/src/ubuntu/file.cpp
+++ /dev/null
@@ -1,773 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "file.h"
-
-#include <QApplication>
-
-namespace {
- class FileError {
- public:
- static const QString kEncodingErr;
- static const QString kTypeMismatchErr;
- static const QString kNotFoundErr;
- static const QString kSecurityErr;
- static const QString kAbortErr;
- static const QString kNotReadableErr;
- static const QString kNoModificationAllowedErr;
- static const QString kInvalidStateErr;
- static const QString kSyntaxErr;
- static const QString kInvalidModificationErr;
- static const QString kQuotaExceededErr;
- static const QString kPathExistsErr;
- };
-
- QVariantMap file2map(const QFileInfo &fileInfo) {
- QVariantMap res;
-
- res.insert("name", fileInfo.fileName());
- res.insert("fullPath", fileInfo.isDir() ? QDir::cleanPath(fileInfo.absoluteFilePath()) : fileInfo.absoluteFilePath());
- res.insert("isDirectory", (int)fileInfo.isDir());
- res.insert("isFile", (int)fileInfo.isFile());
-
- return res;
- }
- QVariantMap dir2map(const QDir &dir) {
- return file2map(QFileInfo(dir.absolutePath()));
- }
-};
-
-const QString FileError::kEncodingErr("FileError.ENCODING_ERR");
-const QString FileError::kTypeMismatchErr("FileError.TYPE_MISMATCH_ERR");
-const QString FileError::kNotFoundErr("FileError.NOT_FOUND_ERR");
-const QString FileError::kSecurityErr("FileError.SECURITY_ERR");
-const QString FileError::kAbortErr("FileError.ABORT_ERR");
-const QString FileError::kNotReadableErr("FileError.NOT_READABLE_ERR");
-const QString FileError::kNoModificationAllowedErr("FileError.NO_MODIFICATION_ALLOWED_ERR");
-const QString FileError::kInvalidStateErr("FileError.INVALID_STATE_ERR");
-const QString FileError::kSyntaxErr("FileError.SYNTAX_ERR");
-const QString FileError::kInvalidModificationErr("FileError.INVALID_MODIFICATION_ERR");
-const QString FileError::kQuotaExceededErr("FileError.QUOTA_EXCEEDED_ERR");
-const QString FileError::kPathExistsErr("FileError.PATH_EXISTS_ERR");
-
-File::File(Cordova *cordova) :
- CPlugin(cordova),
- _persistentDir(QString("%1/.local/share/%2/persistent").arg(QDir::homePath()).arg(QCoreApplication::applicationName())) {
- QDir::root().mkpath(QDir(_persistentDir).absolutePath());
-}
-
-void File::requestFileSystem(int scId, int ecId, unsigned short type, unsigned long long size) {
- QDir dir;
-
- //FIXEME,what is quota value
- if (size >= 10000){
- this->callback(ecId, FileError::kQuotaExceededErr);
- return;
- }
-
- if (type == 0)
- dir = QDir::temp();
- else
- dir = QDir(_persistentDir);
-
- if (type > 1) {
- this->callback(ecId, FileError::kSyntaxErr);
- return;
- } else {
- QVariantMap res;
- res.insert("root", dir2map(dir));
- if (type == 0)
- res.insert("name", "temporary");
- else
- res.insert("name", "persistent");
-
- this->cb(scId, res);
- }
-}
-
-void File::resolveLocalFileSystemURI(int scId, int ecId, QString uri) {
- QUrl url = QUrl::fromUserInput(uri);
-
- if (!url.isValid() || uri[0] == '/' || uri[0] == '.') {
- this->callback(ecId, FileError::kEncodingErr);
- return;
- }
-
- if (url.scheme() != "file") {
- this->callback(ecId, FileError::kTypeMismatchErr);
- return;
- }
-
- QFileInfo fileInfo(url.path());
-
- if (!fileInfo.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- this->cb(scId, file2map(fileInfo));
-}
-
-void File::getFile(int scId, int ecId, const QString &parentPath, const QString &rpath, const QVariantMap &options) {
- QString path(rpath);
-
- if (rpath[0] != '/') {
- if (!parentPath.size() || !QFileInfo(parentPath).isDir())
- path = _persistentDir + "/" + rpath;
- else
- path = parentPath + "/" + rpath;
- }
-
- //NOTE: colon is not safe in url, it is not a valid path in Win and Mac, simple disable it here.
- if (path.contains(":")){
- this->callback(ecId, FileError::kEncodingErr);
- return;
- }
-
- QUrl url = QUrl::fromUserInput(path);
- if (!url.isValid()) {
- this->callback(ecId, FileError::kEncodingErr);
- return;
- }
-
- if (url.scheme() != "file") {
- this->callback(ecId, FileError::kTypeMismatchErr);
- return;
- }
-
- bool create = options.value("create").toBool();
- bool exclusive = options.value("exclusive").toBool();
- QFile file(path);
-
- // if create is false and the path represents a directory, return error
- QFileInfo fileInfo(url.path());
- if ((!create) && fileInfo.isDir()) {
- this->callback(ecId, FileError::kTypeMismatchErr);
- return;
- }
-
- // if file does exist, and create is true and exclusive is true, return error
- if (file.exists()) {
- if (create && exclusive) {
- this->callback(ecId, FileError::kPathExistsErr);
- return;
- }
- }
- else {
- // if file does not exist and create is false, return error
- if (!create) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- file.open(QIODevice::WriteOnly);
- file.close();
-
- // Check if creation was successfull
- if (!file.exists()) {
- this->callback(ecId, FileError::kNoModificationAllowedErr);
- return;
- }
- }
-
- this->cb(scId, file2map(QFileInfo(file)));
-}
-
-void File::getDirectory(int scId, int ecId, QString parentPath, QString rpath, QVariantMap options) {
- QString path(rpath);
- if (rpath[0] != '/') {
- path = parentPath + "/" + rpath;
- }
-
- //NOTE: colon is not safe in url, it is not a valid path in Win and Mac, simple disable it here.
- if (path.contains(":")){
- this->callback(ecId, FileError::kEncodingErr);
- return;
- }
-
- QUrl url = QUrl::fromUserInput(path);
- if (!url.isValid()) {
- this->callback(ecId, FileError::kEncodingErr);
- return;
- }
-
- if (url.scheme() != "file") {
- this->callback(ecId, FileError::kTypeMismatchErr);
- return;
- }
-
- bool create = options.value("create").toBool();
- bool exclusive = options.value("exclusive").toBool();
- QDir dir(path);
-
- // if create is false and the path represents a file, return error
- QFileInfo fileInfo(url.path());
- if ((!create) && fileInfo.isFile()) {
- this->callback(ecId, FileError::kTypeMismatchErr);
- return;
- }
-
- // if directory does exist and create is true and exclusive is true, return error
- if (dir.exists()) {
- if (create && exclusive) {
- this->callback(ecId, FileError::kPathExistsErr);
- return;
- }
- }
- else {
- // if directory does not exist and create is false and directory does not exist, return error
- if (!create) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- // if directory does not exist and create is false and directory does not exist, return error
- QString folderName = dir.dirName();
- dir.cdUp();
- dir.mkdir(folderName);
- dir.cd(folderName);
-
- if (!dir.exists()) {
- this->callback(ecId, FileError::kNoModificationAllowedErr);
- return;
- }
- }
-
- QVariantMap res;
- res.insert("name", dir.dirName());
- res.insert("fullPath", dir.absolutePath());
- this->cb(scId, res);
-}
-
-void File::removeRecursively(int scId, int ecId, QString path) {
- QDir dir(path);
- if (File::rmDir(dir))
- this->cb(scId);
- else
- this->callback(ecId, FileError::kNoModificationAllowedErr);
-}
-
-void File::write(int scId, int ecId, const QString &path, const QString &_data, unsigned long long position, bool binary) {
- QFile file(path);
-
- file.open(QIODevice::WriteOnly);
- file.close();
-
- if (!file.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- QFileInfo fileInfo(file);
- if (!file.open(QIODevice::ReadWrite)) {
- this->callback(ecId, FileError::kNoModificationAllowedErr);
- return;
- }
-
- if (!binary) {
- QTextStream textStream(&file);
- textStream.setCodec("UTF-8");
- textStream.setAutoDetectUnicode(true);
-
- if (!textStream.seek(position)) {
- file.close();
- fileInfo.refresh();
-
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- textStream << _data;
- textStream.flush();
- } else {
- QByteArray data(_data.toUtf8());
- if (!file.seek(position)) {
- file.close();
- fileInfo.refresh();
-
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- file.write(data.data(), data.length());
- }
-
- file.flush();
- file.close();
- fileInfo.refresh();
-
- this->cb(scId, fileInfo.size() - position);
-}
-
-void File::truncate(int scId, int ecId, const QString &path, unsigned long long size) {
- QFile file(path);
-
- if (!file.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- if (!file.resize(size)) {
- this->callback(ecId, FileError::kNoModificationAllowedErr);
- return;
- }
-
- this->cb(scId, size);
-}
-
-void File::getParent(int scId, int ecId, QString path) {
- QDir dir(path);
-
- //can't cdup more than app's root
- // Try to change into upper directory
- if (path != _persistentDir){
- if (!dir.cdUp()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- }
- this->cb(scId, dir2map(dir));
-}
-
-void File::remove(int scId, int ecId, QString path) {
- QFileInfo fileInfo(path);
- if (!fileInfo.exists() || (path == _persistentDir)) {
- this->callback(ecId, FileError::kNoModificationAllowedErr);
- return;
- }
-
- if (fileInfo.isDir()) {
- QDir dir(path);
- if (dir.rmdir(dir.absolutePath())) {
- this->cb(scId);
- return;
- }
- } else {
- QFile file(path);
- if (file.remove()) {
- this->cb(scId);
- return;
- }
- }
-
- this->callback(ecId, FileError::kInvalidModificationErr);
-}
-
-void File::getFileMetadata(int scId, int ecId, const QString &path) {
- QFileInfo fileInfo(path);
-
- if (!fileInfo.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- } else {
- QMimeType mime = _db.mimeTypeForFile(fileInfo.fileName());
-
- QString args = QString("{name: %1, fullPath: %2, type: %3, lastModifiedDate: new Date(%4), size: %5}")
- .arg(CordovaInternal::format(fileInfo.fileName())).arg(CordovaInternal::format(fileInfo.absoluteFilePath()))
- .arg(CordovaInternal::format(mime.name())).arg(fileInfo.lastModified().toMSecsSinceEpoch())
- .arg(fileInfo.size());
-
- this->callback(scId, args);
- }
-}
-
-void File::getMetadata(int scId, int ecId, const QString &path) {
- QFileInfo fileInfo(path);
-
- if (!fileInfo.exists())
- this->callback(ecId, FileError::kNotFoundErr);
- else
- this->cb(scId, fileInfo.lastModified().toMSecsSinceEpoch());
-}
-
-void File::readEntries(int scId, int ecId, QString path) {
- QDir dir(path);
- QString entriesList;
-
- if (!dir.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- for (const QFileInfo &fileInfo: dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
- entriesList += CordovaInternal::format(file2map(fileInfo)) + ",";
- }
-
- // Remove trailing comma
- if (entriesList.size() > 0)
- entriesList.remove(entriesList.size()-1, 1);
- entriesList = "new Array(" + entriesList + ")";
-
- this->callback(scId, entriesList);
-}
-
-void File::readAsText(int scId, int ecId, const QString &path, const QString &encoding, int sliceStart, int sliceEnd) {
- QFile file(path);
-
- if (!file.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- if (!file.open(QIODevice::ReadOnly)) {
- this->callback(ecId, FileError::kNotReadableErr);
- return;
- }
-
- QByteArray content = file.readAll();
-
- if (sliceEnd == -1)
- sliceEnd = content.size();
- if (sliceEnd < 0) {
- sliceEnd++;
- sliceEnd = std::max(0, content.size() + sliceEnd);
- }
- if (sliceEnd > content.size())
- sliceEnd = content.size();
-
- if (sliceStart < 0)
- sliceStart = std::max(0, content.size() + sliceStart);
- if (sliceStart > content.size())
- sliceStart = content.size();
-
- if (sliceStart > sliceEnd)
- sliceEnd = sliceStart;
-
- //FIXME: encoding
- content = content.mid(sliceStart, sliceEnd - sliceStart);
-
- this->cb(scId, content);
-}
-
-void File::readAsArrayBuffer(int scId, int ecId, const QString &path, int sliceStart, int sliceEnd) {
- const QString str2array("\
- (function strToArray(str) { \
- var res = new Uint8Array(str.length); \
- for (var i = 0; i < str.length; i++) { \
- res[i] = str.charCodeAt(i); \
- } \
- return res; \
- })(\"%1\")");
- QFile file(path);
-
- if (!file.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- if (!file.open(QIODevice::ReadOnly)) {
- this->callback(ecId, FileError::kNotReadableErr);
- return;
- }
- QString res;
- QByteArray content = file.readAll();
-
- if (sliceEnd == -1)
- sliceEnd = content.size();
- if (sliceEnd < 0) {
- sliceEnd++;
- sliceEnd = std::max(0, content.size() + sliceEnd);
- }
- if (sliceEnd > content.size())
- sliceEnd = content.size();
-
- if (sliceStart < 0)
- sliceStart = std::max(0, content.size() + sliceStart);
- if (sliceStart > content.size())
- sliceStart = content.size();
-
- if (sliceStart > sliceEnd)
- sliceEnd = sliceStart;
-
- content = content.mid(sliceStart, sliceEnd - sliceStart);
-
- res.reserve(content.length() * 6);
- for (uchar c: content) {
- res += "\\x";
- res += QString::number(c, 16).rightJustified(2, '0').toUpper();
- }
-
- this->callback(scId, str2array.arg(res));
-}
-
-void File::readAsBinaryString(int scId, int ecId, const QString &path, int sliceStart, int sliceEnd) {
- QFile file(path);
-
- if (!file.exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- if (!file.open(QIODevice::ReadOnly)) {
- this->callback(ecId, FileError::kNotReadableErr);
- return;
- }
- QString res;
- QByteArray content = file.readAll();
-
- if (sliceEnd == -1)
- sliceEnd = content.size();
- if (sliceEnd < 0) {
- sliceEnd++;
- sliceEnd = std::max(0, content.size() + sliceEnd);
- }
- if (sliceEnd > content.size())
- sliceEnd = content.size();
-
- if (sliceStart < 0)
- sliceStart = std::max(0, content.size() + sliceStart);
- if (sliceStart > content.size())
- sliceStart = content.size();
-
- if (sliceStart > sliceEnd)
- sliceEnd = sliceStart;
-
- content = content.mid(sliceStart, sliceEnd - sliceStart);
-
- res.reserve(content.length() * 6);
- for (uchar c: content) {
- res += "\\x";
- res += QString::number(c, 16).rightJustified(2, '0').toUpper();
- }
- this->callback(scId, "\"" + res + "\"");
-}
-
-void File::readAsDataURL(int scId, int ecId, const QString &path, int sliceStart, int sliceEnd) {
- QFile file(path);
- QFileInfo fileInfo(path);
-
- if (path.startsWith("content:")){
- this->callback(ecId, FileError::kNotReadableErr);
- return;
- }
-
- if (!file.exists()) {
- this->callback(ecId, FileError::kNotReadableErr);
- return;
- }
- // Try to open file for reading
- if (!file.open(QIODevice::ReadOnly)) {
- this->callback(ecId, FileError::kNotReadableErr);
- return;
- }
- // Read the file content
- QByteArray content = file.readAll();
- QString contentType(_db.mimeTypeForFile(fileInfo.fileName()).name());
-
- if (sliceEnd == -1)
- sliceEnd = content.size();
- if (sliceEnd < 0) {
- sliceEnd++;
- sliceEnd = std::max(0, content.size() + sliceEnd);
- }
- if (sliceEnd > content.size())
- sliceEnd = content.size();
-
- if (sliceStart < 0)
- sliceStart = std::max(0, content.size() + sliceStart);
- if (sliceStart > content.size())
- sliceStart = content.size();
-
- if (sliceStart > sliceEnd)
- sliceEnd = sliceStart;
-
- content = content.mid(sliceStart, sliceEnd - sliceStart);
-
- this->cb(scId, QString("data:%1;base64,").arg(contentType) + content.toBase64());
-}
-
-bool File::rmDir(QDir dir) {
- if (dir == _persistentDir) {//can't remove root dir
- return false;
- }
- bool result = true;
- if (dir.exists()) {
- // Iterate over entries and remove them
- Q_FOREACH(const QFileInfo &fileInfo, dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
- if (fileInfo.isDir()) {
- result = rmDir(fileInfo.absoluteFilePath());
- }
- else {
- result = QFile::remove(fileInfo.absoluteFilePath());
- }
-
- if (!result) {
- return result;
- }
- }
-
- // Finally remove the current dir
- return dir.rmdir(dir.absolutePath());
- }
- return result;
-}
-
-bool File::copyFile(int scId, int ecId,const QString& sourceFile, const QString& destinationParentDir, const QString& newName) {
- if (!QDir(destinationParentDir).exists()){
- this->callback(ecId, FileError::kNotFoundErr);
- return false;
- }
-
- QFileInfo fileInfo(sourceFile);
- QString fileName = ((newName.isEmpty()) ? fileInfo.fileName() : newName);
- QString destinationFile(destinationParentDir + "/" + fileName);
-
- //NOTE: colon is not safe in url, it is not a valid path in Win and Mac, simple disable it here.
- if (!QUrl::fromUserInput(destinationFile).isValid() || destinationFile.contains(":")){
- this->callback(ecId, FileError::kEncodingErr);
- return false;
- }
-
- if (QFile::copy(sourceFile, destinationFile)){
- this->cb(scId, file2map(QFileInfo(destinationFile)));
- return true;
- } else {
- this->callback(ecId, FileError::kInvalidModificationErr);
- return false;
- }
-}
-
-void File::copyDir(int scId, int ecId,const QString& sourceFolder, const QString& destinationParentDir, const QString& newName) {
- QDir sourceDir(sourceFolder);
- QString dirName = ((newName.isEmpty()) ? sourceDir.dirName() : newName);
- QString destFolder(destinationParentDir + "/" + dirName);
-
- if (QFileInfo(destFolder).isFile()){
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
- QDir destDir(destFolder);
-
- if ((sourceFolder == destFolder) || (sourceFolder == destinationParentDir)){
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- if (!destDir.exists()){
- destDir.mkdir(destFolder);;
- } else{
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- if (copyFolder(sourceFolder, destFolder)){
- this->cb(scId, dir2map(destDir));
- return;
- } else {
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-}
-
-void File::copyTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName) {
- if (QFileInfo(source).isDir())
- copyDir(scId, ecId, source, destinationDir, newName);
- else
- copyFile(scId, ecId, source, destinationDir, newName);
-}
-
-void File::moveFile(int scId, int ecId,const QString& sourceFile, const QString& destinationParentDir, const QString& newName) {
- QString fileName = ((newName.isEmpty()) ? QFileInfo(sourceFile).fileName() : newName);
- QString destinationFile(destinationParentDir + "/" + fileName);
-
- if (QFileInfo(sourceFile) == QFileInfo(destinationFile)) {
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- if (!QFileInfo(destinationParentDir).exists()) {
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- if (QFileInfo(destinationFile).exists()) {
- if (!QFile::remove(QFileInfo(destinationFile).absoluteFilePath())) {
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
- }
-
- QFile::rename(sourceFile, destinationFile);
- this->cb(scId, file2map(QFileInfo(destinationFile)));
-}
-
-void File::moveDir(int scId, int ecId,const QString& sourceDir, const QString& destinationParentDir, const QString& newName){
- QString dirName = ((newName.isEmpty()) ? QDir(sourceDir).dirName() : newName);
- QString destFolder(destinationParentDir + "/" + dirName);
- QDir destDir(destFolder);
-
- if (!QFileInfo(destinationParentDir).exists()){
- this->callback(ecId, FileError::kNotFoundErr);
- return;
- }
-
- if (QFileInfo(destFolder).isFile()){
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- if ((QFileInfo(sourceDir) == QFileInfo(destFolder)) || (QFileInfo(sourceDir) == QFileInfo(destinationParentDir))) {
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- if (destDir.exists() && !QDir(destinationParentDir).rmdir(dirName)) {
- this->callback(ecId, FileError::kInvalidModificationErr);
- return;
- }
-
- if (copyFolder(sourceDir, destFolder)) {
- rmDir(sourceDir);
- this->cb(scId, file2map(QFileInfo(destFolder)));
- } else {
- this->callback(ecId, FileError::kNoModificationAllowedErr);
- }
-}
-
-void File::moveTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName) {
- if (newName.contains(":")) {
- this->callback(ecId, FileError::kEncodingErr);
- return;
- }
- if (QFileInfo(source).isDir())
- moveDir(scId, ecId, source, destinationDir, newName);
- else
- moveFile(scId, ecId, source, destinationDir, newName);
-}
-
-bool File::copyFolder(const QString& sourceFolder, const QString& destFolder) {
- QDir sourceDir(sourceFolder);
- if (!sourceDir.exists())
- return false;
- QDir destDir(destFolder);
- if (!destDir.exists()){
- destDir.mkdir(destFolder);
- }
- QStringList files = sourceDir.entryList(QDir::Files);
- for (int i = 0; i< files.count(); i++)
- {
- QString srcName = sourceFolder + "/" + files[i];
- QString destName = destFolder + "/" + files[i];
- QFile::copy(srcName, destName);
- }
- files.clear();
- files = sourceDir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
- for (int i = 0; i< files.count(); i++)
- {
- QString srcName = sourceFolder + "/" + files[i];
- QString destName = destFolder + "/" + files[i];
- copyFolder(srcName, destName);
- }
- return true;
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/ubuntu/file.h
----------------------------------------------------------------------
diff --git a/src/ubuntu/file.h b/src/ubuntu/file.h
deleted file mode 100644
index 0037ad2..0000000
--- a/src/ubuntu/file.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef FILEAPI_H_SDASDASDAS
-#define FILEAPI_H_SDASDASDAS
-
-#include <QNetworkReply>
-#include <QtCore>
-
-#include <cplugin.h>
-#include <cordova.h>
-
-class File: public CPlugin {
- Q_OBJECT
-public:
- explicit File(Cordova *cordova);
-
- virtual const QString fullName() override {
- return File::fullID();
- }
-
- virtual const QString shortName() override {
- return "File";
- }
-
- static const QString fullID() {
- return "File";
- }
-
-public slots:
- void requestFileSystem(int scId, int ecId, unsigned short type, unsigned long long size);
- void resolveLocalFileSystemURI(int scId, int ecId, QString uri);
- void getDirectory(int scId, int ecId, QString parentPath, QString path, QVariantMap options);
- void getFile(int scId, int ecId, const QString &parentPath, const QString &rpath, const QVariantMap &options);
- void readEntries(int scId, int ecId, QString path);
- void getParent(int scId, int ecId, QString path);
- void copyTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName);
- void moveTo(int scId, int ecId, const QString& source, const QString& destinationDir, const QString& newName);
- void getFileMetadata(int scId, int ecId, const QString &path);
- void getMetadata(int scId, int ecId, const QString &path);
- void remove(int scId, int ecId, QString path);
- void removeRecursively(int scId, int ecId, QString path);
- void readAsText(int scId, int ecId, const QString &path, const QString &encoding, int sliceStart, int sliceEnd);
- void write(int scId, int ecId, const QString &path, const QString &_data, unsigned long long position, bool binary);
- void readAsDataURL(int scId, int ecId, const QString &path, int sliceStart, int sliceEnd);
- void readAsArrayBuffer(int scId, int ecId, const QString &path, int sliceStart, int sliceEnd);
- void readAsBinaryString(int scId, int ecId, const QString &path, int sliceStart, int sliceEnd);
- void truncate(int scId, int ecId, const QString &path, unsigned long long size);
-private:
- void moveFile(int scId, int ecId,const QString& sourceFile, const QString& destinationParentDir, const QString& newName);
- void moveDir(int scId, int ecId,const QString& sourceFolder, const QString& destFolder, const QString& newName);
- bool copyFile(int scId, int ecId, const QString& sourceFile, const QString& destinationParentDir, const QString& newName);
- void copyDir(int scId, int ecId, const QString& sourceFolder, const QString& destFolder, const QString& newName);
- bool rmDir(QDir dir);
- bool copyFolder(const QString& sourceFolder, const QString& destFolder);
-
- QMimeDatabase _db;
- const QString _persistentDir;
- QNetworkAccessManager _manager;
-};
-
-#endif
[8/8] git commit: CB-6521: Remove development branch
Posted by ia...@apache.org.
CB-6521: Remove development branch
Project: http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/commit/9976b306
Tree: http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/tree/9976b306
Diff: http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/diff/9976b306
Branch: refs/heads/dev
Commit: 9976b30687047dc1aaa8c21fae5c2fb5a09d53ad
Parents: 757e692
Author: Ian Clelland <ic...@chromium.org>
Authored: Fri Apr 25 14:09:47 2014 -0400
Committer: Ian Clelland <ic...@chromium.org>
Committed: Fri Apr 25 14:09:47 2014 -0400
----------------------------------------------------------------------
LICENSE | 202 ---
NOTICE | 5 -
README.md | 2 +
RELEASENOTES.md | 175 --
doc/index.md | 211 ---
doc/plugins.md | 120 --
plugin.xml | 289 ---
src/android/ContentFilesystem.java | 296 ---
src/android/DirectoryManager.java | 133 --
src/android/EncodingException.java | 29 -
src/android/FileExistsException.java | 29 -
src/android/FileHelper.java | 158 --
src/android/FileUtils.java | 986 ----------
src/android/Filesystem.java | 216 ---
src/android/InvalidModificationException.java | 30 -
src/android/LocalFilesystem.java | 644 -------
src/android/LocalFilesystemURL.java | 74 -
src/android/NoModificationAllowedException.java | 29 -
src/android/TypeMismatchException.java | 30 -
src/blackberry10/index.js | 37 -
src/ios/CDVAssetLibraryFilesystem.h | 30 -
src/ios/CDVAssetLibraryFilesystem.m | 276 ---
src/ios/CDVFile.h | 157 --
src/ios/CDVFile.m | 1047 -----------
src/ios/CDVLocalFilesystem.h | 32 -
src/ios/CDVLocalFilesystem.m | 729 --------
src/ubuntu/file.cpp | 773 --------
src/ubuntu/file.h | 73 -
src/windows8/FileProxy.js | 887 ---------
src/wp/File.cs | 1683 ------------------
www/DirectoryEntry.js | 108 --
www/DirectoryReader.js | 73 -
www/Entry.js | 253 ---
www/File.js | 77 -
www/FileEntry.js | 81 -
www/FileError.js | 46 -
www/FileReader.js | 387 ----
www/FileSystem.js | 48 -
www/FileUploadOptions.js | 41 -
www/FileUploadResult.js | 30 -
www/FileWriter.js | 301 ----
www/Flags.js | 36 -
www/LocalFileSystem.js | 23 -
www/Metadata.js | 40 -
www/ProgressEvent.js | 67 -
www/android/FileSystem.js | 33 -
www/blackberry10/DirectoryEntry.js | 119 --
www/blackberry10/DirectoryReader.js | 54 -
www/blackberry10/Entry.js | 116 --
www/blackberry10/File.js | 56 -
www/blackberry10/FileEntry.js | 49 -
www/blackberry10/FileReader.js | 90 -
www/blackberry10/FileSystem.js | 27 -
www/blackberry10/FileWriter.js | 120 --
www/blackberry10/fileUtils.js | 52 -
www/blackberry10/requestFileSystem.js | 59 -
www/blackberry10/resolveLocalFileSystemURI.js | 25 -
www/blackberry10/resolveLocalFileSystemURL.js | 78 -
www/ios/FileSystem.js | 30 -
www/requestFileSystem.js | 61 -
www/resolveLocalFileSystemURI.js | 69 -
www/ubuntu/DirectoryEntry.js | 26 -
www/ubuntu/Entry.js | 32 -
www/ubuntu/FileWriter.js | 135 --
www/wp/FileUploadOptions.js | 49 -
65 files changed, 2 insertions(+), 12271 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/LICENSE
----------------------------------------------------------------------
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index 7a4a3ea..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,202 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/NOTICE
----------------------------------------------------------------------
diff --git a/NOTICE b/NOTICE
deleted file mode 100644
index 8ec56a5..0000000
--- a/NOTICE
+++ /dev/null
@@ -1,5 +0,0 @@
-Apache Cordova
-Copyright 2012 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/README.md
----------------------------------------------------------------------
diff --git a/README.md b/README.md
index 9ddc447..40d2a1c 100644
--- a/README.md
+++ b/README.md
@@ -20,3 +20,5 @@
# org.apache.cordova.file
Plugin documentation: [doc/index.md](doc/index.md)
+
+This is `dev` - the deprecated development branch of this plugin; development of this plugin has moved to the `master` branch
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/RELEASENOTES.md
----------------------------------------------------------------------
diff --git a/RELEASENOTES.md b/RELEASENOTES.md
deleted file mode 100644
index d34cb47..0000000
--- a/RELEASENOTES.md
+++ /dev/null
@@ -1,175 +0,0 @@
-<!--
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-#
--->
-# Release Notes
-
-### 0.2.1 (Sept 5, 2013)
-* [CB-4656] Don't add newlines in data urls within readAsDataUrl.
-* [CB-4514] Making DirectoryCopy Recursive
-* [iOS] Simplify the code in resolveLocalFileSystemURI
-
-### 0.2.3 (Sept 25, 2013)
-* CB-4889 bumping&resetting version
-* [CB-4903] File Plugin not loading Windows8
-* [CB-4903] File Plugin not loading Windows8
-* CB-4889 renaming references
-* CB-4889 renaming org.apache.cordova.core.file to org.apache.cordova.file
-* Rename CHANGELOG.md -> RELEASENOTES.md
-* [CB-4771] Expose TEMPORARY and PERSISTENT constants on window.
-* Fix compiler/lint warnings
-* [CB-4764] Move DirectoryManager.java into file plugin
-* [CB-4763] Copy FileHelper.java into the plugin.
-* [CB-2901] [BlackBerry10] Automatically unsandbox filesystem if path is not in app sandbox
-* [CB-4752] Incremented plugin version on dev branch.
-
-### 0.2.4 (Oct 9, 2013)
-* CB-5020 - File plugin should execute on a separate thread
-* [CB-4915] Incremented plugin version on dev branch.
-* CB-4504: Updating FileUtils.java to compensate for Java porting failures in the Android SDK. This fails because Java knows nothing about android_asset not being an actual filesystem
-
- ### 0.2.5 (Oct 28, 2013)
-* CB-5129: Add a consistent filesystem attribute to FileEntry and DirectoryEntry objects
-* CB-5128: added repo + issue tag to plugin.xml for file plugin
-* CB-5015 [BlackBerry10] Add missing dependency for File.slice
-* [CB-5010] Incremented plugin version on dev branch.
-
-### 1.0.0 (Feb 05, 2014)
-* CB-5974: Use safe 'Compatibilty' mode by default
-* CB-5915: CB-5916: Reorganize preference code to make defaults possible
-* CB-5974: Android: Don't allow File operations to continue when not configured
-* CB-5960: ios: android: Properly handle parent references in getFile/getDirectory
-* [ubuntu] adopt to recent changes
-* Add default FS root to new FS objects
-* CB-5899: Make DirectoryReader.readEntries return properly formatted Entry objects
-* Add constuctor params to FileUploadResult related to CB-2421
-* Fill out filesystem attribute of entities returned from resolveLocalFileSystemURL
-* CB-5916: Create documents directories if they don't exist
-* CB-5915: Create documents directories if they don't exist
-* CB-5916: Android: Fix unfortunate NPE in config check
-* CB-5916: Android: Add "/files/" to persistent files path
-* CB-5915: ios: Update config preference (and docs) to match issue
-* CB-5916: Android: Add config preference for Android persistent storage location
-* iOS: Add config preference for iOS persistent storage location
-* iOS: Android: Allow third-party plugin registration
-* Android: Expose filePlugin getter so that other plugins can register filesystems
-* Fix typos in deprecation message
-* Add backwards-compatibility shim for file-transfer
-* Android: Allow third-party plugin registration
-* CB-5810 [BlackBerry10] resolve local:/// paths (application assets)
-* CB-5774: create DirectoryEntry instead of FileEntry
-* Initial fix for CB-5747
-* Change default FS URL scheme to "cdvfile"
-* Android: Properly format content urls
-* Android, iOS: Replace "filesystem" protocol string with constant
-* Android: Allow absolute paths on Entry.getFile / Entry.getDirectory
-* Android: Make clear that getFile takes a path, not just a filename
-* CB-5008: Rename resolveLocalFileSystemURI to resolveLocalFileSystemURL; deprecate original
-* Remove old file reference from plugin.xml
-* Android: Refactor File API
-* CB-4899 [BlackBerry10] Fix resolve directories
-* CB-5602 Windows8. Fix File Api mobile spec tests
-* Android: Better support for content urls and cross-filesystem copy/move ops
-* CB-5699 [BlackBerry10] Update resolveLocalFileSystemURI implementation
-* CB-5658 Update license comment formatting of doc/index.md
-* CB-5658 Add doc.index.md for File plugin.
-* CB-5658 Delete stale snapshot of plugin docs
-* CB-5403: Backwards-compatibility with file:// urls where possible
-* CB-5407: Fixes for ContentFilesystem
-* Android: Add method for testing backwards-compatibility of filetransfer plugin
-* iOS: Add method for testing backwards-compatiblity of filetransfer plugin
-* Android: Updates to allow FileTransfer to continue to work
-* Android: Clean up unclosed file objects
-* CB-5407: Cleanup
-* CB-5407: Add new Android source files to plugin.xml
-* CB-5407: Move read, write and truncate methods into modules
-* CB-5407: Move copy/move methods into FS modules
-* CB-5407: Move getParent into FS modules
-* CB-5407: Move getmetadata methods into FS modules
-* CB-5407: Move readdir methods into FS modules
-* CB-5407: Move remove methods into FS modules
-* CB-5407: Move getFile into FS modules
-* CB-5407: Start refactoring android code: Modular filesystems, rfs, rlfsurl
-* CB-5407: Update android JS to use FS urls
-* CB-5405: Use URL formatting for Entry.toURL
-* CB-5532 Fix
-* Log file path for File exceptions.
-* Partial fix for iOS File compatibility with previous fileTransfer plugin
-* CB-5532 WP8. Add binary data support to FileWriter
-* CB-5531 WP8. File Api readAsText incorrectly handles position args
-* Added ubuntu platform support
-* Added amazon-fireos platform support
-* CB-5118 [BlackBerry10] Add check for undefined error handler
-* CB-5406: Extend public API for dependent plugins
-* CB-5403: Bump File plugin major version
-* CB-5406: Split iOS file plugin into modules
-* CB-5406: Factor out filesystem providers in iOS
-* CB-5408: Add handler for filesystem:// urls
-* CB-5406: Update iOS native code to use filesystem URLs internally
-* CB-5405: Update JS code to use URLs exclusively
-* CB-4816 Fix file creation outside sandbox for BB10
-
-### 1.0.1 (Feb 28, 2014)
-* CB-6116 Fix error where resolveLocalFileSystemURL would fail
-* CB-6106 Add support for nativeURL attribute on Entry objects
-* CB-6110 iOS: Fix typo in filesystemPathForURL: method
-* Android: Use most specific FS match when resolving file: URIs
-* iOS: Update fileSystemURLforLocalPath: to return the most match url.
-* Allow third-party plugin registration, and the total count of fs type is not limited to just 4.
-* CB-6097 Added missing files for amazon-fireos platform. Added onLoad flag to true.
-* CB-6087 Android, iOS: Load file plugin on startup
-* CB-6013 BlackBerry10: wrap webkit prefixed called in requestAnimationFrame
-* Update plugin writers' documentation
-* CB-6080 Fix file copy when src and dst are on different local file systems
-* CB-6057 Add methods for plugins to convert between URLs and paths
-* CB-6050 Public method for returning a FileEntry from a device file path
-* CB-2432 CB-3185, CB-5975: Fix Android handling of content:// URLs
-* CB-6022 Add upgrade notes to doc
-* CB-5233 Make asset-library urls work properly on iOS
-* CB-6012 Preserve query strings on cdvfile:// URLs where necessary
-* CB-6010 Test properly for presence of URLforFilesystemPath method
-* CB-5959 Entry.getMetadata should return size attribute
-
-### 1.1.0 (Apr 17, 2014)
-* CB-4965: Remove tests from file plugin
-* Android: Allow file:/ URLs
-* CB-6422: [windows8] use cordova/exec/proxy
-* CB-6249: [android] Opportunistically resolve content urls to file
-* CB-6394: [ios, android] Add extra filesystem roots
-* CB-6394: [ios, android] Fix file resolution for the device root case
-* CB-6394: [ios] Return ENCODING_ERR when fs name is not valid
-* CB-6393: Change behaviour of toURL and toNativeURL
-* ios: Style: plugin initialization
-* ios: Fix handling of file URLs with encoded spaces
-* Always use Android's recommended temp file location for temporary file system
-* CB-6352: Allow FileSystem objects to be serialized to JSON
-* CB-5959: size is explicitly 0 if not set, file.spec.46&47 are testing the type of size
-* CB-6242: [BlackBerry10] Add deprecated version of resolveLocalFileSystemURI
-* CB-6242: [BlackBerry10] add file:/// prefix for toURI / toURL
-* CB-6242: [BlackBerry10] Polyfill window.requestAnimationFrame for OS < 10.2
-* CB-6242: [BlackBerry10] Override window.resolveLocalFileSystemURL
-* CB-6212: [iOS] fix warnings compiled under arm64 64-bit
-* ios: Don't cache responses from CDVFile's URLProtocol
-* CB-6199: [iOS] Fix toNativeURL() not escaping characters properly
-* CB-6148: Fix cross-filesystem copy and move
-* fixed setMetadata() to use the formatted fullPath
-* corrected typo which leads to a "comma expression"
-* CB-4952: ios: Resolve symlinks in file:// URLs
-* Add docs about the extraFileSystems <preference>
-* CB-6460: Update license headers
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/doc/index.md
----------------------------------------------------------------------
diff --git a/doc/index.md b/doc/index.md
deleted file mode 100644
index b47c95f..0000000
--- a/doc/index.md
+++ /dev/null
@@ -1,211 +0,0 @@
-<!---
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-
-# org.apache.cordova.file
-
-This plugin provides the [HTML5 Filesystem API](http://dev.w3.org/2009/dap/file-system/pub/FileSystem/). For usage, refer
-to HTML5 Rocks' [FileSystem article](http://www.html5rocks.com/en/tutorials/file/filesystem/)
-on the subject. For an overview of other storage options, refer to Cordova's
-[storage guide](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
-
-## Installation
-
- cordova plugin add org.apache.cordova.file
-
-## Supported Platforms
-
-- Amazon Fire OS
-- Android
-- BlackBerry 10*
-- iOS
-- Windows Phone 7 and 8*
-- Windows 8*
-
-\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._
-
-## Configuring the Plugin
-
-The set of available filesystems can be configured per-platform. Both iOS and
-Android recognize a <preference> tag in `config.xml` which names the
-filesystems to be installed. By default, all file-system roots are enabled.
-
- <preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
- <preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,root" />
-
-### Android
-
-* files: The application's internal file storage directory
-* files-external: The application's external file storage directory
-* sdcard: The global external file storage directory (this is the root of the SD card, if one is installed)
-* cache: The application's internal cache directory
-* cache-external: The application's external cache directory
-* root: The entire device filesystem
-
-Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
-
-### iOS
-
-* library: The application's Library directory
-* documents: The application's Documents directory
-* cache: The application's Cache directory
-* app-bundle: The application's bundle; the location of the app itself on disk
-* root: The entire device filesystem
-
-By default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems, "library-nosync" and "documents-nosync", which represent a special non-synced directory within the Library or Documents filesystem.
-
-## Android Quirks
-
-### Android Persistent storage location
-
-There are multiple valid locations to store persistent files on an Android
-device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html)
-for an extensive discussion of the various possibilities.
-
-Previous versions of the plugin would choose the location of the temporary and
-persistent files on startup, based on whether the device claimed that the SD
-Card (or equivalent storage partition) was mounted. If the SD Card was mounted,
-or if a large internal storage partition was available (such as on Nexus
-devices,) then the persistent files would be stored in the root of that space.
-This meant that all Cordova apps could see all of the files available on the
-card.
-
-If the SD card was not available, then previous versions would store data under
-/data/data/<packageId>, which isolates apps from each other, but may still
-cause data to be shared between users.
-
-It is now possible to choose whether to store files in the internal file
-storage location, or using the previous logic, with a preference in your
-application's config.xml file. To do this, add one of these two lines to
-config.xml:
-
- <preference name="AndroidPersistentFileLocation" value="Internal" />
-
- <preference name="AndroidPersistentFileLocation" value="Compatibility" />
-
-Without this line, the File plugin will use "Compatibility" as the default. If
-a preference tag is present, and is not one of these values, the application
-will not start.
-
-If your application has previously been shipped to users, using an older (pre-
-1.0) version of this plugin, and has stored files in the persistent filesystem,
-then you should set the preference to "Compatibility". Switching the location to
-"Internal" would mean that existing users who upgrade their application may be
-unable to access their previously-stored files, depending on their device.
-
-If your application is new, or has never previously stored files in the
-persistent filesystem, then the "internal" setting is generally recommended.
-
-## BlackBerry Quirks
-
-`DirectoryEntry.removeRecursively()` may fail with a `ControlledAccessException` in the following cases:
-
-- An app attempts to access a directory created by a previous installation of the app.
-
-> Solution: ensure temporary directories are cleaned manually, or by the application prior to reinstallation.
-
-- If the device is connected by USB.
-
-> Solution: disconnect the USB cable from the device and run again.
-
-## iOS Quirks
-- `FileReader.readAsText(blob, encoding)`
- - The `encoding` parameter is not supported, and UTF-8 encoding is always in effect.
-
-### iOS Persistent storage location
-
-There are two valid locations to store persistent files on an iOS device: the
-Documents directory and the Library directory. Previous versions of the plugin
-only ever stored persistent files in the Documents directory. This had the
-side-effect of making all of an application's files visible in iTunes, which
-was often unintended, especially for applications which handle lots of small
-files, rather than producing complete documents for export, which is the
-intended purpose of the directory.
-
-It is now possible to choose whether to store files in the documents or library
-directory, with a preference in your application's config.xml file. To do this,
-add one of these two lines to config.xml:
-
- <preference name="iosPersistentFileLocation" value="Library" />
-
- <preference name="iosPersistentFileLocation" value="Compatibility" />
-
-Without this line, the File plugin will use "Compatibility" as the default. If
-a preference tag is present, and is not one of these values, the application
-will not start.
-
-If your application has previously been shipped to users, using an older (pre-
-1.0) version of this plugin, and has stored files in the persistent filesystem,
-then you should set the preference to "Compatibility". Switching the location to
-"Library" would mean that existing users who upgrade their application would be
-unable to access their previously-stored files.
-
-If your application is new, or has never previously stored files in the
-persistent filesystem, then the "Library" setting is generally recommended.
-
-## Upgrading Notes
-
-In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed,
-to be more in line with the published specification.
-
-Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location
-in the `fullPath` property of `Entry` objects. These paths would typically look like
-
- /var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
- /storage/emulated/0/path/to/file (Android)
-
-These paths were also returned by the `toURL()` method of the `Entry` objects.
-
-With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of
-the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry`
-object with a `fullPath` of
-
- /path/to/file
-
-If your application works with device-absolute-paths, and you previously retrieved those
-paths through the `fullPath` property of `Entry` objects, then you should update your code
-to use `entry.toURL()` instead. This method will now return filesystem URLs of the form
-
- cdvfile://localhost/persistent/path/to/file
-
-which can be used to identify the file uniquely.
-
-For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a
-device-absolute-path, and will return an `Entry` object corresponding to it, as long as that
-file exists within either the TEMPORARY or PERSISTENT filesystems.
-
-This has particularly been an issue with the File-Transfer plugin, which previously used
-device-absolute-paths (and can still accept them). It has been updated to work correctly
-with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any
-issues getting that plugin to work with files on the device.
-
-## List of Error Codes and Meanings
-When an error is thrown, one of the following codes will be used.
-
-* 1 = NOT_FOUND_ERR
-* 2 = SECURITY_ERR
-* 3 = ABORT_ERR
-* 4 = NOT_READABLE_ERR
-* 5 = ENCODING_ERR
-* 6 = NO_MODIFICATION_ALLOWED_ERR
-* 7 = INVALID_STATE_ERR
-* 8 = SYNTAX_ERR
-* 9 = INVALID_MODIFICATION_ERR
-* 10 = QUOTA_EXCEEDED_ERR
-* 11 = TYPE_MISMATCH_ERR
-* 12 = PATH_EXISTS_ERR
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/doc/plugins.md
----------------------------------------------------------------------
diff --git a/doc/plugins.md b/doc/plugins.md
deleted file mode 100644
index a3329d6..0000000
--- a/doc/plugins.md
+++ /dev/null
@@ -1,120 +0,0 @@
-<!---
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-
-Notes for plugin developers
-===========================
-
-These notes are primarily intended for Android and iOS developers who want to write plugins which interface with the file system using the File plugin.
-
-Working with Cordova file system URLs
--------------------------------------
-
-Since version 1.0.0, this plugin has used URLs with a `cdvfile` scheme for all communication over the bridge, rather than exposing raw device file system paths to JavaScript.
-
-On the JavaScript side, this means that FileEntry and DirectoryEntry objects have a fullPath attribute which is relative to the root of the HTML file system. If your plugin's JavaScript API accepts a FileEntry or DirectoryEntry object, you should call `.toURL()` on that object before passing it across the bridge to native code.
-
-### Converting cdvfile:// URLs to fileystem paths
-
-Plugins which need to write to the filesystem may want to convert a received file system URL to an actual filesystem location. There are multiple ways of doing this, depending on the native platform.
-
-It is important to remember that not all `cdvfile://` URLs are mappable to real files on the device. Some URLs can refer to assets on device which are not represented by files, or can even refer to remote resources. Because of these possibilities, plugins should always test whether they get a meaningful result back when trying to convert URLs to paths.
-
-#### Android
-
-On Android, the simplest method to convert a `cdvfile://` URL to a filesystem path is to use `org.apache.cordova.CordovaResourceApi`. `CordovaResourceApi` has several methods which can handle `cdvfile://` URLs:
-
- // webView is a member of the Plugin class
- CordovaResourceApi resourceApi = webView.getResourceApi();
-
- // Obtain a file:/// URL representing this file on the device,
- // or the same URL unchanged if it cannot be mapped to a file
- Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));
-
-It is also possible to use the File plugin directly:
-
- import org.apache.cordova.file.FileUtils;
- import org.apache.cordova.file.FileSystem;
- import java.net.MalformedURLException;
-
- // Get the File plugin from the plugin manager
- FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");
-
- // Given a URL, get a path for it
- try {
- String path = filePlugin.filesystemPathForURL(cdvfileURL);
- } catch (MalformedURLException e) {
- // The filesystem url wasn't recognized
- }
-
-To convert from a path to a `cdvfile://` URL:
-
- import org.apache.cordova.file.LocalFilesystemURL;
-
- // Get a LocalFilesystemURL object for a device path,
- // or null if it cannot be represented as a cdvfile URL.
- LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
- // Get the string representation of the URL object
- String cdvfileURL = url.toString();
-
-If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin:
-
- // Return a JSON structure suitable for returning to JavaScript,
- // or null if this file is not representable as a cdvfile URL.
- JSONObject entry = filePlugin.getEntryForFile(file);
-
-#### iOS
-
-Cordova on iOS does not use the same `CordovaResourceApi` concept as Android. On iOS, you should use the File plugin to convert between URLs and filesystem paths.
-
- // Get a CDVFilesystem URL object from a URL string
- CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
- // Get a path for the URL object, or nil if it cannot be mapped to a file
- NSString* path = [filePlugin filesystemPathForURL:url];
-
-
- // Get a CDVFilesystem URL object for a device path, or
- // nil if it cannot be represented as a cdvfile URL.
- CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
- // Get the string representation of the URL object
- NSString* cdvfileURL = [url absoluteString];
-
-If your plugin creates a file, and you want to return a FileEntry object for it, use the File plugin:
-
- // Get a CDVFilesystem URL object for a device path, or
- // nil if it cannot be represented as a cdvfile URL.
- CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
- // Get a structure to return to JavaScript
- NSDictionary* entry = [filePlugin makeEntryForLocalURL:url]
-
-#### JavaScript
-
-In JavaScript, to get a `cdvfile://` URL from a FileEntry or DirectoryEntry object, simply call `.toURL()` on it:
-
- var cdvfileURL = entry.toURL();
-
-In plugin response handlers, to convert from a returned FileEntry structure to an actual Entry object, your handler code should import the File plugin and create a new object:
-
- // create appropriate Entry object
- var entry;
- if (entryStruct.isDirectory) {
- entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
- } else {
- entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
- }
-
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/plugin.xml
----------------------------------------------------------------------
diff --git a/plugin.xml b/plugin.xml
deleted file mode 100644
index cedabbf..0000000
--- a/plugin.xml
+++ /dev/null
@@ -1,289 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
--->
-
-<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
-xmlns:android="http://schemas.android.com/apk/res/android"
- id="org.apache.cordova.file"
- version="1.1.1-dev">
- <name>File</name>
- <description>Cordova File Plugin</description>
- <license>Apache 2.0</license>
- <keywords>cordova,file</keywords>
- <repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git</repo>
- <issue>https://issues.apache.org/jira/browse/CB/component/12320651</issue>
-
- <js-module src="www/DirectoryEntry.js" name="DirectoryEntry">
- <clobbers target="window.DirectoryEntry" />
- </js-module>
-
- <js-module src="www/DirectoryReader.js" name="DirectoryReader">
- <clobbers target="window.DirectoryReader" />
- </js-module>
-
- <js-module src="www/Entry.js" name="Entry">
- <clobbers target="window.Entry" />
- </js-module>
-
- <js-module src="www/File.js" name="File">
- <clobbers target="window.File" />
- </js-module>
-
- <js-module src="www/FileEntry.js" name="FileEntry">
- <clobbers target="window.FileEntry" />
- </js-module>
-
- <js-module src="www/FileError.js" name="FileError">
- <clobbers target="window.FileError" />
- </js-module>
-
- <js-module src="www/FileReader.js" name="FileReader">
- <clobbers target="window.FileReader" />
- </js-module>
-
- <js-module src="www/FileSystem.js" name="FileSystem">
- <clobbers target="window.FileSystem" />
- </js-module>
-
- <js-module src="www/FileUploadOptions.js" name="FileUploadOptions">
- <clobbers target="window.FileUploadOptions" />
- </js-module>
-
- <js-module src="www/FileUploadResult.js" name="FileUploadResult">
- <clobbers target="window.FileUploadResult" />
- </js-module>
-
- <js-module src="www/FileWriter.js" name="FileWriter">
- <clobbers target="window.FileWriter" />
- </js-module>
-
- <js-module src="www/Flags.js" name="Flags">
- <clobbers target="window.Flags" />
- </js-module>
-
- <js-module src="www/LocalFileSystem.js" name="LocalFileSystem">
- <!-- Non-standards way -->
- <clobbers target="window.LocalFileSystem" />
- <!-- Standards-compliant way -->
- <merges target="window" />
- </js-module>
-
- <js-module src="www/Metadata.js" name="Metadata">
- <clobbers target="window.Metadata" />
- </js-module>
-
- <js-module src="www/ProgressEvent.js" name="ProgressEvent">
- <clobbers target="window.ProgressEvent" />
- </js-module>
-
- <js-module src="www/requestFileSystem.js" name="requestFileSystem">
- <clobbers target="window.requestFileSystem" />
- </js-module>
-
- <js-module src="www/resolveLocalFileSystemURI.js" name="resolveLocalFileSystemURI">
- <merges target="window" />
- </js-module>
-
- <!-- android -->
- <platform name="android">
- <config-file target="res/xml/config.xml" parent="/*">
- <feature name="File" >
- <param name="android-package" value="org.apache.cordova.file.FileUtils"/>
- <param name="onload" value="true" />
- </feature>
- </config-file>
-
- <config-file target="AndroidManifest.xml" parent="/*">
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- </config-file>
-
- <source-file src="src/android/EncodingException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/FileExistsException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/InvalidModificationException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/NoModificationAllowedException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/TypeMismatchException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/FileUtils.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/FileHelper.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/DirectoryManager.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/LocalFilesystemURL.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/Filesystem.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/LocalFilesystem.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/ContentFilesystem.java" target-dir="src/org/apache/cordova/file" />
-
- <!-- android specific file apis -->
- <js-module src="www/android/FileSystem.js" name="androidFileSystem">
- <merges target="window.FileSystem" />
- </js-module>
- </platform>
-
- <!-- amazon-fireos -->
- <platform name="amazon-fireos">
- <config-file target="res/xml/config.xml" parent="/*">
- <feature name="File" >
- <param name="android-package" value="org.apache.cordova.file.FileUtils"/>
- <param name="onload" value="true" />
- </feature>
- </config-file>
-
- <config-file target="AndroidManifest.xml" parent="/*">
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- </config-file>
-
- <source-file src="src/android/EncodingException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/FileExistsException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/InvalidModificationException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/NoModificationAllowedException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/TypeMismatchException.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/FileUtils.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/FileHelper.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/DirectoryManager.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/LocalFilesystemURL.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/Filesystem.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/LocalFilesystem.java" target-dir="src/org/apache/cordova/file" />
- <source-file src="src/android/ContentFilesystem.java" target-dir="src/org/apache/cordova/file" />
-
- <!-- android specific file apis -->
- <js-module src="www/android/FileSystem.js" name="androidFileSystem">
- <merges target="window.FileSystem" />
- </js-module>
- </platform>
-
- <!-- ubuntu -->
- <platform name="ubuntu">
- <header-file src="src/ubuntu/file.h" />
- <source-file src="src/ubuntu/file.cpp" />
- <js-module src="www/ubuntu/Entry.js" name="Entry1">
- <merges target="window.Entry" />
- </js-module>
- <js-module src="www/ubuntu/DirectoryEntry.js" name="DirectoryEntry1">
- <merges target="window.DirectoryEntry" />
- </js-module>
- <js-module src="www/ubuntu/FileWriter.js" name="FileWriter1">
- <merges target="window.FileWriter" />
- </js-module>
- </platform>
-
- <!-- ios -->
- <platform name="ios">
- <config-file target="config.xml" parent="/*">
- <feature name="File">
- <param name="ios-package" value="CDVFile" />
- <param name="onload" value="true" />
- </feature>
- </config-file>
- <header-file src="src/ios/CDVFile.h" />
- <source-file src="src/ios/CDVFile.m" />
- <header-file src="src/ios/CDVLocalFilesystem.h" />
- <source-file src="src/ios/CDVLocalFilesystem.m" />
- <header-file src="src/ios/CDVAssetLibraryFilesystem.h" />
- <source-file src="src/ios/CDVAssetLibraryFilesystem.m" />
-
- <!-- ios specific file apis -->
- <js-module src="www/ios/FileSystem.js" name="iosFileSystem">
- <merges target="window.FileSystem" />
- </js-module>
-
- <framework src="AssetsLibrary.framework" />
- <framework src="MobileCoreServices.framework" />
- </platform>
-
- <!-- wp7 -->
- <platform name="wp7">
- <config-file target="config.xml" parent="/*">
- <feature name="File">
- <param name="wp-package" value="File"/>
- </feature>
- </config-file>
-
- <source-file src="src/wp/File.cs" />
-
- <!-- wp specific file apis -->
- <js-module src="www/wp/FileUploadOptions.js" name="FileUploadOptions1">
- <merges target="window.FileUploadOptions" />
- </js-module>
-
- </platform>
-
- <!-- wp8 -->
- <platform name="wp8">
- <config-file target="config.xml" parent="/*">
- <feature name="File">
- <param name="wp-package" value="File"/>
- </feature>
- </config-file>
-
- <source-file src="src/wp/File.cs" />
-
- <!-- wp specific file apis -->
- <js-module src="www/wp/FileUploadOptions.js" name="FileUploadOptions1">
- <merges target="window.FileUploadOptions" />
- </js-module>
-
- </platform>
-
- <!-- blackberry10 -->
- <platform name="blackberry10">
- <config-file target="www/config.xml" parent="/widget">
- <feature name="File" value="File" />
- </config-file>
- <js-module src="www/blackberry10/fileUtils.js" name="BB10Utils" />
- <js-module src="www/blackberry10/DirectoryEntry.js" name="BB10DirectoryEntry">
- <clobbers target="window.DirectoryEntry" />
- </js-module>
- <js-module src="www/blackberry10/DirectoryReader.js" name="BB10DirectoryReader">
- <clobbers target="window.DirectoryReader" />
- </js-module>
- <js-module src="www/blackberry10/Entry.js" name="BB10Entry">
- <clobbers target="window.Entry" />
- </js-module>
- <js-module src="www/blackberry10/File.js" name="BB10File">
- <clobbers target="window.File" />
- </js-module>
- <js-module src="www/blackberry10/FileEntry.js" name="BB10FileEntry">
- <clobbers target="window.FileEntry" />
- </js-module>
- <js-module src="www/blackberry10/FileReader.js" name="BB10FileReader">
- <clobbers target="window.FileReader" />
- </js-module>
- <js-module src="www/blackberry10/FileSystem.js" name="BB10FileSystem">
- <clobbers target="window.FileSystem" />
- </js-module>
- <js-module src="www/blackberry10/FileWriter.js" name="BB10FileWriter">
- <clobbers target="window.FileWriter" />
- </js-module>
- <js-module src="www/blackberry10/requestFileSystem.js" name="BB10requestFileSystem">
- <clobbers target="window.requestFileSystem" />
- </js-module>
- <js-module src="www/blackberry10/resolveLocalFileSystemURI.js" name="BB10resolveLocalFileSystemURI">
- <clobbers target="window.resolveLocalFileSystemURI" />
- </js-module>
- <js-module src="www/blackberry10/resolveLocalFileSystemURL.js" name="BB10resolveLocalFileSystemURL">
- <clobbers target="window.resolveLocalFileSystemURL" />
- </js-module>
- <source-file src="src/blackberry10/index.js"></source-file>
- </platform>
-
- <!-- windows8 -->
- <platform name="windows8">
- <js-module src="src/windows8/FileProxy.js" name="FileProxy">
- <merges target="" />
- </js-module>
- </platform>
-
-</plugin>
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/ContentFilesystem.java
----------------------------------------------------------------------
diff --git a/src/android/ContentFilesystem.java b/src/android/ContentFilesystem.java
deleted file mode 100644
index 4206033..0000000
--- a/src/android/ContentFilesystem.java
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-package org.apache.cordova.file;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import org.apache.cordova.CordovaInterface;
-import org.apache.cordova.CordovaResourceApi;
-import org.apache.cordova.CordovaWebView;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import android.content.ContentResolver;
-import android.database.Cursor;
-import android.net.Uri;
-import android.provider.MediaStore;
-import android.provider.OpenableColumns;
-
-public class ContentFilesystem extends Filesystem {
-
- private CordovaInterface cordova;
- private CordovaResourceApi resourceApi;
-
- public ContentFilesystem(String name, CordovaInterface cordova, CordovaWebView webView) {
- this.name = name;
- this.cordova = cordova;
- this.resourceApi = new CordovaResourceApi(webView.getContext(), webView.pluginManager);
- }
-
- @Override
- public JSONObject getEntryForLocalURL(LocalFilesystemURL inputURL) throws IOException {
- // Get the cursor to validate that the file exists
- Cursor cursor = openCursorForURL(inputURL);
- String filePath = null;
- try {
- if (cursor == null || !cursor.moveToFirst()) {
- throw new FileNotFoundException();
- }
- filePath = filesystemPathForCursor(cursor);
- } finally {
- if (cursor != null)
- cursor.close();
- }
- if (filePath == null) {
- filePath = inputURL.URL.toString();
- } else {
- filePath = "file://" + filePath;
- }
- try {
- return makeEntryForPath(inputURL.fullPath, inputURL.filesystemName, false /*fp.isDirectory()*/, filePath);
- } catch (JSONException e) {
- throw new IOException();
- }
- }
-
- @Override
- public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
- String fileName, JSONObject options, boolean directory) throws IOException, TypeMismatchException, JSONException {
- if (options != null) {
- if (options.optBoolean("create")) {
- throw new IOException("Cannot create content url");
- }
- }
- LocalFilesystemURL requestedURL = new LocalFilesystemURL(Uri.withAppendedPath(inputURL.URL, fileName));
- File fp = new File(this.filesystemPathForURL(requestedURL));
- if (!fp.exists()) {
- throw new FileNotFoundException("path does not exist");
- }
- if (directory) {
- if (fp.isFile()) {
- throw new TypeMismatchException("path doesn't exist or is file");
- }
- } else {
- if (fp.isDirectory()) {
- throw new TypeMismatchException("path doesn't exist or is directory");
- }
- }
- // Return the directory
- return makeEntryForPath(requestedURL.fullPath, requestedURL.filesystemName, directory, Uri.fromFile(fp).toString());
-
- }
-
- @Override
- public boolean removeFileAtLocalURL(LocalFilesystemURL inputURL)
- throws NoModificationAllowedException {
-
- String filePath = filesystemPathForURL(inputURL);
- File file = new File(filePath);
- try {
- this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
- MediaStore.Images.Media.DATA + " = ?",
- new String[] { filePath });
- } catch (UnsupportedOperationException t) {
- // Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
- // The ContentResolver applies only when the file was registered in the
- // first case, which is generally only the case with images.
- }
- return file.delete();
- }
-
- @Override
- public boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL)
- throws NoModificationAllowedException {
- throw new NoModificationAllowedException("Cannot remove content url");
- }
-
- @Override
- public JSONArray readEntriesAtLocalURL(LocalFilesystemURL inputURL)
- throws FileNotFoundException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
- Integer size = null;
- Integer lastModified = null;
- Cursor cursor = openCursorForURL(inputURL);
- try {
- if (cursor != null && cursor.moveToFirst()) {
- size = resourceSizeForCursor(cursor);
- lastModified = lastModifiedDateForCursor(cursor);
- } else {
- throw new FileNotFoundException();
- }
- } finally {
- if (cursor != null)
- cursor.close();
- }
-
- JSONObject metadata = new JSONObject();
- try {
- metadata.put("size", size);
- metadata.put("type", resourceApi.getMimeType(inputURL.URL));
- metadata.put("name", inputURL.filesystemName);
- metadata.put("fullPath", inputURL.fullPath);
- metadata.put("lastModifiedDate", lastModified);
- } catch (JSONException e) {
- return null;
- }
- return metadata;
- }
-
- @Override
- public JSONObject copyFileToURL(LocalFilesystemURL destURL, String newName,
- Filesystem srcFs, LocalFilesystemURL srcURL, boolean move)
- throws IOException, InvalidModificationException, JSONException,
- NoModificationAllowedException, FileExistsException {
- if (LocalFilesystem.class.isInstance(srcFs)) {
- /* Same FS, we can shortcut with CordovaResourceApi operations */
- // Figure out where we should be copying to
- final LocalFilesystemURL destinationURL = makeDestinationURL(newName, srcURL, destURL);
-
- OutputStream os = resourceApi.openOutputStream(destURL.URL);
- CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(srcURL.URL);
- if (move && !srcFs.canRemoveFileAtLocalURL(srcURL)) {
- throw new NoModificationAllowedException("Cannot move file at source URL");
- }
- try {
- resourceApi.copyResource(ofrr, os);
- } catch (IOException e) {
- throw new IOException("Cannot read file at source URL");
- }
- if (move) {
- srcFs.removeFileAtLocalURL(srcURL);
- }
- return makeEntryForURL(destinationURL, false, destinationURL.URL.toString());
- } else {
- // Need to copy the hard way
- return super.copyFileToURL(destURL, newName, srcFs, srcURL, move);
- }
- }
-
-
- @Override
- public void readFileAtURL(LocalFilesystemURL inputURL, long start, long end,
- ReadFileCallback readFileCallback) throws IOException {
- CordovaResourceApi.OpenForReadResult ofrr = resourceApi.openForRead(inputURL.URL);
- if (end < 0) {
- end = ofrr.length;
- }
- long numBytesToRead = end - start;
- try {
- if (start > 0) {
- ofrr.inputStream.skip(start);
- }
- LimitedInputStream inputStream = new LimitedInputStream(ofrr.inputStream, numBytesToRead);
- readFileCallback.handleData(inputStream, ofrr.mimeType);
- } finally {
- ofrr.inputStream.close();
- }
- }
-
- @Override
- public long writeToFileAtURL(LocalFilesystemURL inputURL, String data,
- int offset, boolean isBinary) throws NoModificationAllowedException {
- throw new NoModificationAllowedException("Couldn't write to file given its content URI");
- }
- @Override
- public long truncateFileAtURL(LocalFilesystemURL inputURL, long size)
- throws NoModificationAllowedException {
- throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
- }
-
- protected Cursor openCursorForURL(LocalFilesystemURL url) {
- ContentResolver contentResolver = this.cordova.getActivity().getContentResolver();
- Cursor cursor = contentResolver.query(url.URL, null, null, null, null);
- return cursor;
- }
-
- protected String filesystemPathForCursor(Cursor cursor) {
- final String[] LOCAL_FILE_PROJECTION = { MediaStore.Images.Media.DATA };
- int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
- if (columnIndex != -1) {
- return cursor.getString(columnIndex);
- }
- return null;
- }
-
- protected Integer resourceSizeForCursor(Cursor cursor) {
- int columnIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
- if (columnIndex != -1) {
- String sizeStr = cursor.getString(columnIndex);
- if (sizeStr != null) {
- return Integer.parseInt(sizeStr,10);
- }
- }
- return null;
- }
-
- protected Integer lastModifiedDateForCursor(Cursor cursor) {
- final String[] LOCAL_FILE_PROJECTION = { MediaStore.MediaColumns.DATE_MODIFIED };
- int columnIndex = cursor.getColumnIndex(LOCAL_FILE_PROJECTION[0]);
- if (columnIndex != -1) {
- String dateStr = cursor.getString(columnIndex);
- if (dateStr != null) {
- return Integer.parseInt(dateStr,10);
- }
- }
- return null;
- }
-
- @Override
- public String filesystemPathForURL(LocalFilesystemURL url) {
- Cursor cursor = openCursorForURL(url);
- try {
- if (cursor != null && cursor.moveToFirst()) {
- return filesystemPathForCursor(cursor);
- }
- } finally {
- if (cursor != null)
- cursor.close();
- }
- return null;
- }
-
- @Override
- public LocalFilesystemURL URLforFilesystemPath(String path) {
- // Returns null as we don't support reverse mapping back to content:// URLs
- return null;
- }
-
- @Override
- public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
- String path = filesystemPathForURL(inputURL);
- File file = new File(path);
- return file.exists();
- }
-
- @Override
- OutputStream getOutputStreamForURL(LocalFilesystemURL inputURL)
- throws IOException {
- OutputStream os = resourceApi.openOutputStream(inputURL.URL);
- return os;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/DirectoryManager.java
----------------------------------------------------------------------
diff --git a/src/android/DirectoryManager.java b/src/android/DirectoryManager.java
deleted file mode 100644
index c2d1278..0000000
--- a/src/android/DirectoryManager.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-package org.apache.cordova.file;
-
-import android.os.Environment;
-import android.os.StatFs;
-
-import java.io.File;
-
-/**
- * This class provides file directory utilities.
- * All file operations are performed on the SD card.
- *
- * It is used by the FileUtils class.
- */
-public class DirectoryManager {
-
- @SuppressWarnings("unused")
- private static final String LOG_TAG = "DirectoryManager";
-
- /**
- * Determine if a file or directory exists.
- * @param name The name of the file to check.
- * @return T=exists, F=not found
- */
- public static boolean testFileExists(String name) {
- boolean status;
-
- // If SD card exists
- if ((testSaveLocationExists()) && (!name.equals(""))) {
- File path = Environment.getExternalStorageDirectory();
- File newPath = constructFilePaths(path.toString(), name);
- status = newPath.exists();
- }
- // If no SD card
- else {
- status = false;
- }
- return status;
- }
-
- /**
- * Get the free disk space
- *
- * @return Size in KB or -1 if not available
- */
- public static long getFreeDiskSpace(boolean checkInternal) {
- String status = Environment.getExternalStorageState();
- long freeSpace = 0;
-
- // If SD card exists
- if (status.equals(Environment.MEDIA_MOUNTED)) {
- freeSpace = freeSpaceCalculation(Environment.getExternalStorageDirectory().getPath());
- }
- else if (checkInternal) {
- freeSpace = freeSpaceCalculation("/");
- }
- // If no SD card and we haven't been asked to check the internal directory then return -1
- else {
- return -1;
- }
-
- return freeSpace;
- }
-
- /**
- * Given a path return the number of free KB
- *
- * @param path to the file system
- * @return free space in KB
- */
- private static long freeSpaceCalculation(String path) {
- StatFs stat = new StatFs(path);
- long blockSize = stat.getBlockSize();
- long availableBlocks = stat.getAvailableBlocks();
- return availableBlocks * blockSize / 1024;
- }
-
- /**
- * Determine if SD card exists.
- *
- * @return T=exists, F=not found
- */
- public static boolean testSaveLocationExists() {
- String sDCardStatus = Environment.getExternalStorageState();
- boolean status;
-
- // If SD card is mounted
- if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
- status = true;
- }
-
- // If no SD card
- else {
- status = false;
- }
- return status;
- }
-
- /**
- * Create a new file object from two file paths.
- *
- * @param file1 Base file path
- * @param file2 Remaining file path
- * @return File object
- */
- private static File constructFilePaths (String file1, String file2) {
- File newPath;
- if (file2.startsWith(file1)) {
- newPath = new File(file2);
- }
- else {
- newPath = new File(file1 + "/" + file2);
- }
- return newPath;
- }
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/EncodingException.java
----------------------------------------------------------------------
diff --git a/src/android/EncodingException.java b/src/android/EncodingException.java
deleted file mode 100644
index e9e1653..0000000
--- a/src/android/EncodingException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-package org.apache.cordova.file;
-
-@SuppressWarnings("serial")
-public class EncodingException extends Exception {
-
- public EncodingException(String message) {
- super(message);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/FileExistsException.java
----------------------------------------------------------------------
diff --git a/src/android/FileExistsException.java b/src/android/FileExistsException.java
deleted file mode 100644
index 5c4d83d..0000000
--- a/src/android/FileExistsException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
-*/
-
-package org.apache.cordova.file;
-
-@SuppressWarnings("serial")
-public class FileExistsException extends Exception {
-
- public FileExistsException(String msg) {
- super(msg);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cordova-plugin-file/blob/9976b306/src/android/FileHelper.java
----------------------------------------------------------------------
diff --git a/src/android/FileHelper.java b/src/android/FileHelper.java
deleted file mode 100644
index 9e8b626..0000000
--- a/src/android/FileHelper.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing,
- software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
- specific language governing permissions and limitations
- under the License.
- */
-package org.apache.cordova.file;
-
-import android.database.Cursor;
-import android.net.Uri;
-import android.webkit.MimeTypeMap;
-
-import org.apache.cordova.CordovaInterface;
-import org.apache.cordova.LOG;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Locale;
-
-public class FileHelper {
- private static final String LOG_TAG = "FileUtils";
- private static final String _DATA = "_data";
-
- /**
- * Returns the real path of the given URI string.
- * If the given URI string represents a content:// URI, the real path is retrieved from the media store.
- *
- * @param uriString the URI string of the audio/image/video
- * @param cordova the current application context
- * @return the full path to the file
- */
- @SuppressWarnings("deprecation")
- public static String getRealPath(String uriString, CordovaInterface cordova) {
- String realPath = null;
-
- if (uriString.startsWith("content://")) {
- String[] proj = { _DATA };
- Cursor cursor = cordova.getActivity().managedQuery(Uri.parse(uriString), proj, null, null, null);
- int column_index = cursor.getColumnIndexOrThrow(_DATA);
- cursor.moveToFirst();
- realPath = cursor.getString(column_index);
- if (realPath == null) {
- LOG.e(LOG_TAG, "Could get real path for URI string %s", uriString);
- }
- } else if (uriString.startsWith("file://")) {
- realPath = uriString.substring(7);
- if (realPath.startsWith("/android_asset/")) {
- LOG.e(LOG_TAG, "Cannot get real path for URI string %s because it is a file:///android_asset/ URI.", uriString);
- realPath = null;
- }
- } else {
- realPath = uriString;
- }
-
- return realPath;
- }
-
- /**
- * Returns the real path of the given URI.
- * If the given URI is a content:// URI, the real path is retrieved from the media store.
- *
- * @param uri the URI of the audio/image/video
- * @param cordova the current application context
- * @return the full path to the file
- */
- public static String getRealPath(Uri uri, CordovaInterface cordova) {
- return FileHelper.getRealPath(uri.toString(), cordova);
- }
-
- /**
- * Returns an input stream based on given URI string.
- *
- * @param uriString the URI string from which to obtain the input stream
- * @param cordova the current application context
- * @return an input stream into the data at the given URI or null if given an invalid URI string
- * @throws IOException
- */
- public static InputStream getInputStreamFromUriString(String uriString, CordovaInterface cordova) throws IOException {
- if (uriString.startsWith("content")) {
- Uri uri = Uri.parse(uriString);
- return cordova.getActivity().getContentResolver().openInputStream(uri);
- } else if (uriString.startsWith("file://")) {
- int question = uriString.indexOf("?");
- if (question > -1) {
- uriString = uriString.substring(0,question);
- }
- if (uriString.startsWith("file:///android_asset/")) {
- Uri uri = Uri.parse(uriString);
- String relativePath = uri.getPath().substring(15);
- return cordova.getActivity().getAssets().open(relativePath);
- } else {
- return new FileInputStream(getRealPath(uriString, cordova));
- }
- } else {
- return new FileInputStream(getRealPath(uriString, cordova));
- }
- }
-
- /**
- * Removes the "file://" prefix from the given URI string, if applicable.
- * If the given URI string doesn't have a "file://" prefix, it is returned unchanged.
- *
- * @param uriString the URI string to operate on
- * @return a path without the "file://" prefix
- */
- public static String stripFileProtocol(String uriString) {
- if (uriString.startsWith("file://")) {
- uriString = uriString.substring(7);
- }
- return uriString;
- }
-
- public static String getMimeTypeForExtension(String path) {
- String extension = path;
- int lastDot = extension.lastIndexOf('.');
- if (lastDot != -1) {
- extension = extension.substring(lastDot + 1);
- }
- // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
- extension = extension.toLowerCase(Locale.getDefault());
- if (extension.equals("3ga")) {
- return "audio/3gpp";
- }
- return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
- }
-
- /**
- * Returns the mime type of the data specified by the given URI string.
- *
- * @param uriString the URI string of the data
- * @return the mime type of the specified data
- */
- public static String getMimeType(String uriString, CordovaInterface cordova) {
- String mimeType = null;
-
- Uri uri = Uri.parse(uriString);
- if (uriString.startsWith("content://")) {
- mimeType = cordova.getActivity().getContentResolver().getType(uri);
- } else {
- mimeType = getMimeTypeForExtension(uri.getPath());
- }
-
- return mimeType;
- }
-}