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:51 UTC
[5/8] CB-6521: Remove development branch
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