PageRenderTime 94ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/front/plugins/cordova-plugin-file/src/osx/CDVLocalFilesystem.m

https://gitlab.com/boxnia/NFU_MOVIL
Objective C | 733 lines | 515 code | 77 blank | 141 comment | 173 complexity | 0194df8fdacf822f792922376f58e3c4 MD5 | raw file
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. #import "CDVFile.h"
  18. #import "CDVLocalFilesystem.h"
  19. #import <sys/xattr.h>
  20. @implementation CDVLocalFilesystem
  21. @synthesize name=_name, fsRoot=_fsRoot, urlTransformer;
  22. - (id) initWithName:(NSString *)name root:(NSString *)fsRoot
  23. {
  24. if (self) {
  25. _name = name;
  26. _fsRoot = fsRoot;
  27. }
  28. return self;
  29. }
  30. /*
  31. * IN
  32. * NSString localURI
  33. * OUT
  34. * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the
  35. * URI represents a non-existent path, or is unrecognized or otherwise malformed.
  36. */
  37. - (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
  38. {
  39. CDVPluginResult* result = nil;
  40. NSDictionary* entry = [self makeEntryForLocalURL:url];
  41. if (entry) {
  42. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
  43. } else {
  44. // return NOT_FOUND_ERR
  45. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
  46. }
  47. return result;
  48. }
  49. - (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
  50. NSString *path = [self filesystemPathForURL:url];
  51. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  52. BOOL isDir = NO;
  53. // see if exists and is file or dir
  54. BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir];
  55. if (bExists) {
  56. return [self makeEntryForPath:url.fullPath isDirectory:isDir];
  57. } else {
  58. return nil;
  59. }
  60. }
  61. - (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir
  62. {
  63. NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
  64. NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent];
  65. if (isDir && ![fullPath hasSuffix:@"/"]) {
  66. fullPath = [fullPath stringByAppendingString:@"/"];
  67. }
  68. [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
  69. [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
  70. [dirEntry setObject:fullPath forKey:@"fullPath"];
  71. [dirEntry setObject:lastPart forKey:@"name"];
  72. [dirEntry setObject:self.name forKey: @"filesystemName"];
  73. NSURL* nativeURL = [NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]];
  74. if (self.urlTransformer) {
  75. nativeURL = self.urlTransformer(nativeURL);
  76. }
  77. dirEntry[@"nativeURL"] = [nativeURL absoluteString];
  78. return dirEntry;
  79. }
  80. - (NSString *)stripQueryParametersFromPath:(NSString *)fullPath
  81. {
  82. NSRange questionMark = [fullPath rangeOfString:@"?"];
  83. if (questionMark.location != NSNotFound) {
  84. return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)];
  85. }
  86. return fullPath;
  87. }
  88. - (NSString *)filesystemPathForFullPath:(NSString *)fullPath
  89. {
  90. NSString *path = nil;
  91. NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath];
  92. path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath];
  93. if ([path length] > 1 && [path hasSuffix:@"/"]) {
  94. path = [path substringToIndex:([path length]-1)];
  95. }
  96. return path;
  97. }
  98. /*
  99. * IN
  100. * NSString localURI
  101. * OUT
  102. * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
  103. * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
  104. * or if the URL is malformed.
  105. * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
  106. */
  107. - (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
  108. {
  109. return [self filesystemPathForFullPath:url.fullPath];
  110. }
  111. - (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath
  112. {
  113. if (fullPath) {
  114. NSString* escapedPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  115. if ([fullPath hasPrefix:@"/"]) {
  116. return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];
  117. }
  118. return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];
  119. }
  120. return nil;
  121. }
  122. - (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path
  123. {
  124. return [self URLforFullPath:[self fullPathForFileSystemPath:path]];
  125. }
  126. - (NSString *)normalizePath:(NSString *)rawPath
  127. {
  128. // If this is an absolute path, the first path component will be '/'. Skip it if that's the case
  129. BOOL isAbsolutePath = [rawPath hasPrefix:@"/"];
  130. if (isAbsolutePath) {
  131. rawPath = [rawPath substringFromIndex:1];
  132. }
  133. NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]];
  134. for (int index = 0; index < [components count]; ++index) {
  135. if ([[components objectAtIndex:index] isEqualToString:@".."]) {
  136. [components removeObjectAtIndex:index];
  137. if (index > 0) {
  138. [components removeObjectAtIndex:index-1];
  139. --index;
  140. }
  141. }
  142. }
  143. if (isAbsolutePath) {
  144. return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]];
  145. } else {
  146. return [components componentsJoinedByString:@"/"];
  147. }
  148. }
  149. - (BOOL)valueForKeyIsNumber:(NSDictionary*)dict key:(NSString*)key
  150. {
  151. BOOL bNumber = NO;
  152. NSObject* value = dict[key];
  153. if (value) {
  154. bNumber = [value isKindOfClass:[NSNumber class]];
  155. }
  156. return bNumber;
  157. }
  158. - (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
  159. {
  160. CDVPluginResult* result = nil;
  161. BOOL bDirRequest = NO;
  162. BOOL create = NO;
  163. BOOL exclusive = NO;
  164. int errorCode = 0; // !!! risky - no error code currently defined for 0
  165. if ([self valueForKeyIsNumber:options key:@"create"]) {
  166. create = [(NSNumber*)[options valueForKey:@"create"] boolValue];
  167. }
  168. if ([self valueForKeyIsNumber:options key:@"exclusive"]) {
  169. exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue];
  170. }
  171. if ([self valueForKeyIsNumber:options key:@"getDir"]) {
  172. // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method
  173. bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue];
  174. }
  175. // see if the requested path has invalid characters - should we be checking for more than just ":"?
  176. if ([requestedPath rangeOfString:@":"].location != NSNotFound) {
  177. errorCode = ENCODING_ERR;
  178. } else {
  179. // Build new fullPath for the requested resource.
  180. // We concatenate the two paths together, and then scan the resulting string to remove
  181. // parent ("..") references. Any parent references at the beginning of the string are
  182. // silently removed.
  183. NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:requestedPath];
  184. combinedPath = [self normalizePath:combinedPath];
  185. CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath];
  186. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  187. BOOL bIsDir;
  188. BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir];
  189. if (bExists && (create == NO) && (bIsDir == !bDirRequest)) {
  190. // path exists and is not of requested type - return TYPE_MISMATCH_ERR
  191. errorCode = TYPE_MISMATCH_ERR;
  192. } else if (!bExists && (create == NO)) {
  193. // path does not exist and create is false - return NOT_FOUND_ERR
  194. errorCode = NOT_FOUND_ERR;
  195. } else if (bExists && (create == YES) && (exclusive == YES)) {
  196. // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR
  197. errorCode = PATH_EXISTS_ERR;
  198. } else {
  199. // if bExists and create == YES - just return data
  200. // if bExists and create == NO - just return data
  201. // if !bExists and create == YES - create and return data
  202. BOOL bSuccess = YES;
  203. NSError __autoreleasing* pError = nil;
  204. if (!bExists && (create == YES)) {
  205. if (bDirRequest) {
  206. // create the dir
  207. bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError];
  208. } else {
  209. // create the empty file
  210. bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil];
  211. }
  212. }
  213. if (!bSuccess) {
  214. errorCode = ABORT_ERR;
  215. if (pError) {
  216. NSLog(@"error creating directory: %@", [pError localizedDescription]);
  217. }
  218. } else {
  219. // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]);
  220. // file existed or was created
  221. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath isDirectory:bDirRequest]];
  222. }
  223. } // are all possible conditions met?
  224. }
  225. if (errorCode > 0) {
  226. // create error callback
  227. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
  228. }
  229. return result;
  230. }
  231. - (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
  232. {
  233. CDVPluginResult* result = nil;
  234. CDVFilesystemURL *newURI = nil;
  235. if ([localURI.fullPath isEqualToString:@""]) {
  236. // return self
  237. newURI = localURI;
  238. } else {
  239. newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */
  240. }
  241. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  242. BOOL bIsDir;
  243. BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir];
  244. if (bExists) {
  245. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath isDirectory:bIsDir]];
  246. } else {
  247. // invalid path or file does not exist
  248. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
  249. }
  250. return result;
  251. }
  252. - (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
  253. {
  254. BOOL ok = NO;
  255. NSString* filePath = [self filesystemPathForURL:localURI];
  256. // we only care about this iCloud key for now.
  257. // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute)
  258. NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup";
  259. id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey];
  260. if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) {
  261. // todo: fix me
  262. // if (IsAtLeastiOSVersion(@"5.1")) {
  263. // NSURL* url = [NSURL fileURLWithPath:filePath];
  264. // NSError* __autoreleasing error = nil;
  265. //
  266. // ok = [url setResourceValue:[NSNumber numberWithBool:[iCloudBackupExtendedAttributeValue boolValue]] forKey:NSURLIsExcludedFromBackupKey error:&error];
  267. // } else { // below 5.1 (deprecated - only really supported in 5.01)
  268. // u_int8_t value = [iCloudBackupExtendedAttributeValue intValue];
  269. // if (value == 0) { // remove the attribute (allow backup, the default)
  270. // ok = (removexattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], 0) == 0);
  271. // } else { // set the attribute (skip backup)
  272. // ok = (setxattr([filePath fileSystemRepresentation], [iCloudBackupExtendedAttributeKey cStringUsingEncoding:NSUTF8StringEncoding], &value, sizeof(value), 0, 0) == 0);
  273. // }
  274. // }
  275. }
  276. if (ok) {
  277. return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
  278. } else {
  279. return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
  280. }
  281. }
  282. /* remove the file or directory (recursively)
  283. * IN:
  284. * NSString* fullPath - the full path to the file or directory to be removed
  285. * NSString* callbackId
  286. * called from remove and removeRecursively - check all pubic api specific error conditions (dir not empty, etc) before calling
  287. */
  288. - (CDVPluginResult*)doRemove:(NSString*)fullPath
  289. {
  290. CDVPluginResult* result = nil;
  291. BOOL bSuccess = NO;
  292. NSError* __autoreleasing pError = nil;
  293. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  294. @try {
  295. bSuccess = [fileMgr removeItemAtPath:fullPath error:&pError];
  296. if (bSuccess) {
  297. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
  298. } else {
  299. // see if we can give a useful error
  300. CDVFileError errorCode = ABORT_ERR;
  301. NSLog(@"error removing filesystem entry at %@: %@", fullPath, [pError localizedDescription]);
  302. if ([pError code] == NSFileNoSuchFileError) {
  303. errorCode = NOT_FOUND_ERR;
  304. } else if ([pError code] == NSFileWriteNoPermissionError) {
  305. errorCode = NO_MODIFICATION_ALLOWED_ERR;
  306. }
  307. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
  308. }
  309. } @catch(NSException* e) { // NSInvalidArgumentException if path is . or ..
  310. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:SYNTAX_ERR];
  311. }
  312. return result;
  313. }
  314. - (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
  315. {
  316. NSString *fileSystemPath = [self filesystemPathForURL:localURI];
  317. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  318. BOOL bIsDir = NO;
  319. BOOL bExists = [fileMgr fileExistsAtPath:fileSystemPath isDirectory:&bIsDir];
  320. if (!bExists) {
  321. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
  322. }
  323. if (bIsDir && ([[fileMgr contentsOfDirectoryAtPath:fileSystemPath error:nil] count] != 0)) {
  324. // dir is not empty
  325. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
  326. }
  327. return [self doRemove:fileSystemPath];
  328. }
  329. - (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
  330. {
  331. NSString *fileSystemPath = [self filesystemPathForURL:localURI];
  332. return [self doRemove:fileSystemPath];
  333. }
  334. /*
  335. * IN
  336. * NSString localURI
  337. * OUT
  338. * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
  339. * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
  340. * or if the URL is malformed.
  341. * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
  342. */
  343. - (NSString *)fullPathForFileSystemPath:(NSString *)fsPath
  344. {
  345. if ([fsPath hasPrefix:self.fsRoot]) {
  346. return [fsPath substringFromIndex:[self.fsRoot length]];
  347. }
  348. return nil;
  349. }
  350. - (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
  351. {
  352. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  353. NSError* __autoreleasing error = nil;
  354. NSString *fileSystemPath = [self filesystemPathForURL:localURI];
  355. NSArray* contents = [fileMgr contentsOfDirectoryAtPath:fileSystemPath error:&error];
  356. if (contents) {
  357. NSMutableArray* entries = [NSMutableArray arrayWithCapacity:1];
  358. if ([contents count] > 0) {
  359. // create an Entry (as JSON) for each file/dir
  360. for (NSString* name in contents) {
  361. // see if is dir or file
  362. NSString* entryPath = [fileSystemPath stringByAppendingPathComponent:name];
  363. BOOL bIsDir = NO;
  364. [fileMgr fileExistsAtPath:entryPath isDirectory:&bIsDir];
  365. NSDictionary* entryDict = [self makeEntryForPath:[self fullPathForFileSystemPath:entryPath] isDirectory:bIsDir];
  366. [entries addObject:entryDict];
  367. }
  368. }
  369. return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:entries];
  370. } else {
  371. // assume not found but could check error for more specific error conditions
  372. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
  373. }
  374. }
  375. - (unsigned long long)truncateFile:(NSString*)filePath atPosition:(unsigned long long)pos
  376. {
  377. unsigned long long newPos = 0UL;
  378. NSFileHandle* file = [NSFileHandle fileHandleForWritingAtPath:filePath];
  379. if (file) {
  380. [file truncateFileAtOffset:(unsigned long long)pos];
  381. newPos = [file offsetInFile];
  382. [file synchronizeFile];
  383. [file closeFile];
  384. }
  385. return newPos;
  386. }
  387. - (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
  388. {
  389. unsigned long long newPos = [self truncateFile:[self filesystemPathForURL:localURI] atPosition:pos];
  390. return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)newPos];
  391. }
  392. - (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
  393. {
  394. NSString *filePath = [self filesystemPathForURL:localURL];
  395. CDVPluginResult* result = nil;
  396. CDVFileError errCode = INVALID_MODIFICATION_ERR;
  397. int bytesWritten = 0;
  398. if (filePath) {
  399. NSOutputStream* fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:shouldAppend];
  400. if (fileStream) {
  401. NSUInteger len = [encData length];
  402. if (len == 0) {
  403. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:(double)len];
  404. } else {
  405. [fileStream open];
  406. bytesWritten = (int)[fileStream write:[encData bytes] maxLength:len];
  407. [fileStream close];
  408. if (bytesWritten > 0) {
  409. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:bytesWritten];
  410. // } else {
  411. // can probably get more detailed error info via [fileStream streamError]
  412. // errCode already set to INVALID_MODIFICATION_ERR;
  413. // bytesWritten = 0; // may be set to -1 on error
  414. }
  415. }
  416. } // else fileStream not created return INVALID_MODIFICATION_ERR
  417. } else {
  418. // invalid filePath
  419. errCode = NOT_FOUND_ERR;
  420. }
  421. if (!result) {
  422. // was an error
  423. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errCode];
  424. }
  425. return result;
  426. }
  427. /**
  428. * Helper function to check to see if the user attempted to copy an entry into its parent without changing its name,
  429. * or attempted to copy a directory into a directory that it contains directly or indirectly.
  430. *
  431. * IN:
  432. * NSString* srcDir
  433. * NSString* destinationDir
  434. * OUT:
  435. * YES copy/ move is allows
  436. * NO move is onto itself
  437. */
  438. - (BOOL)canCopyMoveSrc:(NSString*)src ToDestination:(NSString*)dest
  439. {
  440. // This weird test is to determine if we are copying or moving a directory into itself.
  441. // Copy /Documents/myDir to /Documents/myDir-backup is okay but
  442. // Copy /Documents/myDir to /Documents/myDir/backup not okay
  443. BOOL copyOK = YES;
  444. NSRange range = [dest rangeOfString:src];
  445. if (range.location != NSNotFound) {
  446. NSRange testRange = {range.length - 1, ([dest length] - range.length)};
  447. NSRange resultRange = [dest rangeOfString:@"/" options:0 range:testRange];
  448. if (resultRange.location != NSNotFound) {
  449. copyOK = NO;
  450. }
  451. }
  452. return copyOK;
  453. }
  454. - (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
  455. {
  456. NSFileManager *fileMgr = [[NSFileManager alloc] init];
  457. NSString *destRootPath = [self filesystemPathForURL:destURL];
  458. BOOL bDestIsDir = NO;
  459. BOOL bDestExists = [fileMgr fileExistsAtPath:destRootPath isDirectory:&bDestIsDir];
  460. NSString *newFileSystemPath = [destRootPath stringByAppendingPathComponent:newName];
  461. NSString *newFullPath = [self fullPathForFileSystemPath:newFileSystemPath];
  462. BOOL bNewIsDir = NO;
  463. BOOL bNewExists = [fileMgr fileExistsAtPath:newFileSystemPath isDirectory:&bNewIsDir];
  464. CDVPluginResult *result = nil;
  465. int errCode = 0;
  466. if (!bDestExists) {
  467. // the destination root does not exist
  468. errCode = NOT_FOUND_ERR;
  469. }
  470. else if ([srcFs isKindOfClass:[CDVLocalFilesystem class]]) {
  471. /* Same FS, we can shortcut with NSFileManager operations */
  472. NSString *srcFullPath = [srcFs filesystemPathForURL:srcURL];
  473. BOOL bSrcIsDir = NO;
  474. BOOL bSrcExists = [fileMgr fileExistsAtPath:srcFullPath isDirectory:&bSrcIsDir];
  475. if (!bSrcExists) {
  476. // the source does not exist
  477. errCode = NOT_FOUND_ERR;
  478. } else if ([newFileSystemPath isEqualToString:srcFullPath]) {
  479. // source and destination can not be the same
  480. errCode = INVALID_MODIFICATION_ERR;
  481. } else if (bSrcIsDir && (bNewExists && !bNewIsDir)) {
  482. // can't copy/move dir to file
  483. errCode = INVALID_MODIFICATION_ERR;
  484. } else { // no errors yet
  485. NSError* __autoreleasing error = nil;
  486. BOOL bSuccess = NO;
  487. if (bCopy) {
  488. if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {
  489. // can't copy dir into self
  490. errCode = INVALID_MODIFICATION_ERR;
  491. } else if (bNewExists) {
  492. // the full destination should NOT already exist if a copy
  493. errCode = PATH_EXISTS_ERR;
  494. } else {
  495. bSuccess = [fileMgr copyItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];
  496. }
  497. } else { // move
  498. // iOS requires that destination must not exist before calling moveTo
  499. // is W3C INVALID_MODIFICATION_ERR error if destination dir exists and has contents
  500. //
  501. if (!bSrcIsDir && (bNewExists && bNewIsDir)) {
  502. // can't move a file to directory
  503. errCode = INVALID_MODIFICATION_ERR;
  504. } else if (bSrcIsDir && ![self canCopyMoveSrc:srcFullPath ToDestination:newFileSystemPath]) {
  505. // can't move a dir into itself
  506. errCode = INVALID_MODIFICATION_ERR;
  507. } else if (bNewExists) {
  508. if (bNewIsDir && ([[fileMgr contentsOfDirectoryAtPath:newFileSystemPath error:NULL] count] != 0)) {
  509. // can't move dir to a dir that is not empty
  510. errCode = INVALID_MODIFICATION_ERR;
  511. newFileSystemPath = nil; // so we won't try to move
  512. } else {
  513. // remove destination so can perform the moveItemAtPath
  514. bSuccess = [fileMgr removeItemAtPath:newFileSystemPath error:NULL];
  515. if (!bSuccess) {
  516. errCode = INVALID_MODIFICATION_ERR; // is this the correct error?
  517. newFileSystemPath = nil;
  518. }
  519. }
  520. } else if (bNewIsDir && [newFileSystemPath hasPrefix:srcFullPath]) {
  521. // can't move a directory inside itself or to any child at any depth;
  522. errCode = INVALID_MODIFICATION_ERR;
  523. newFileSystemPath = nil;
  524. }
  525. if (newFileSystemPath != nil) {
  526. bSuccess = [fileMgr moveItemAtPath:srcFullPath toPath:newFileSystemPath error:&error];
  527. }
  528. }
  529. if (bSuccess) {
  530. // should verify it is there and of the correct type???
  531. NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:bSrcIsDir];
  532. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];
  533. } else {
  534. if (error) {
  535. if (([error code] == NSFileReadUnknownError) || ([error code] == NSFileReadTooLargeError)) {
  536. errCode = NOT_READABLE_ERR;
  537. } else if ([error code] == NSFileWriteOutOfSpaceError) {
  538. errCode = QUOTA_EXCEEDED_ERR;
  539. } else if ([error code] == NSFileWriteNoPermissionError) {
  540. errCode = NO_MODIFICATION_ALLOWED_ERR;
  541. }
  542. }
  543. }
  544. }
  545. } else {
  546. // Need to copy the hard way
  547. [srcFs readFileAtURL:srcURL start:0 end:-1 callback:^(NSData* data, NSString* mimeType, CDVFileError errorCode) {
  548. CDVPluginResult* result = nil;
  549. if (data != nil) {
  550. BOOL bSuccess = [data writeToFile:newFileSystemPath atomically:YES];
  551. if (bSuccess) {
  552. // should verify it is there and of the correct type???
  553. NSDictionary* newEntry = [self makeEntryForPath:newFullPath isDirectory:NO];
  554. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:newEntry];
  555. } else {
  556. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:ABORT_ERR];
  557. }
  558. } else {
  559. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
  560. }
  561. callback(result);
  562. }];
  563. return; // Async IO; return without callback.
  564. }
  565. if (result == nil) {
  566. if (!errCode) {
  567. errCode = INVALID_MODIFICATION_ERR; // Catch-all default
  568. }
  569. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errCode];
  570. }
  571. callback(result);
  572. }
  573. /* helper function to get the mimeType from the file extension
  574. * IN:
  575. * NSString* fullPath - filename (may include path)
  576. * OUT:
  577. * NSString* the mime type as type/subtype. nil if not able to determine
  578. */
  579. + (NSString*)getMimeTypeFromPath:(NSString*)fullPath
  580. {
  581. NSString* mimeType = nil;
  582. if (fullPath) {
  583. CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
  584. if (typeId) {
  585. mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
  586. if (!mimeType) {
  587. // special case for m4a
  588. if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
  589. mimeType = @"audio/mp4";
  590. } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
  591. mimeType = @"audio/wav";
  592. } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
  593. mimeType = @"text/css";
  594. }
  595. }
  596. CFRelease(typeId);
  597. }
  598. }
  599. return mimeType;
  600. }
  601. - (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
  602. {
  603. NSString *path = [self filesystemPathForURL:localURL];
  604. NSString* mimeType = [CDVLocalFilesystem getMimeTypeFromPath:path];
  605. if (mimeType == nil) {
  606. mimeType = @"*/*";
  607. }
  608. NSFileHandle* file = [NSFileHandle fileHandleForReadingAtPath:path];
  609. if (start > 0) {
  610. [file seekToFileOffset:start];
  611. }
  612. NSData* readData;
  613. if (end < 0) {
  614. readData = [file readDataToEndOfFile];
  615. } else {
  616. readData = [file readDataOfLength:(end - start)];
  617. }
  618. [file closeFile];
  619. callback(readData, mimeType, readData != nil ? NO_ERROR : NOT_FOUND_ERR);
  620. }
  621. - (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
  622. {
  623. NSString *path = [self filesystemPathForURL:localURL];
  624. CDVPluginResult *result;
  625. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  626. NSError* __autoreleasing error = nil;
  627. NSDictionary* fileAttrs = [fileMgr attributesOfItemAtPath:path error:&error];
  628. if (fileAttrs) {
  629. // create dictionary of file info
  630. NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
  631. [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
  632. [fileInfo setObject:@"" forKey:@"type"]; // can't easily get the mimetype unless create URL, send request and read response so skipping
  633. [fileInfo setObject:[path lastPathComponent] forKey:@"name"];
  634. // Ensure that directories (and other non-regular files) report size of 0
  635. unsigned long long size = ([fileAttrs fileType] == NSFileTypeRegular ? [fileAttrs fileSize] : 0);
  636. [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:size] forKey:@"size"];
  637. NSDate* modDate = [fileAttrs fileModificationDate];
  638. if (modDate) {
  639. [fileInfo setObject:[NSNumber numberWithDouble:[modDate timeIntervalSince1970] * 1000] forKey:@"lastModifiedDate"];
  640. }
  641. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo];
  642. } else {
  643. // didn't get fileAttribs
  644. CDVFileError errorCode = ABORT_ERR;
  645. NSLog(@"error getting metadata: %@", [error localizedDescription]);
  646. if ([error code] == NSFileNoSuchFileError || [error code] == NSFileReadNoSuchFileError) {
  647. errorCode = NOT_FOUND_ERR;
  648. }
  649. // log [NSNumber numberWithDouble: theMessage] objCtype to see what it returns
  650. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:errorCode];
  651. }
  652. callback(result);
  653. }
  654. @end