Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

CDVLocalFilesystem.m 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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 <Cordova/CDV.h>
  20. #import <MobileCoreServices/MobileCoreServices.h>
  21. #import <sys/xattr.h>
  22. @implementation CDVLocalFilesystem
  23. @synthesize name=_name, fsRoot=_fsRoot, urlTransformer;
  24. - (id) initWithName:(NSString *)name root:(NSString *)fsRoot
  25. {
  26. if (self) {
  27. self.name = name;
  28. self.fsRoot = fsRoot;
  29. }
  30. return self;
  31. }
  32. /*
  33. * IN
  34. * NSString localURI
  35. * OUT
  36. * CDVPluginResult result containing a file or directoryEntry for the localURI, or an error if the
  37. * URI represents a non-existent path, or is unrecognized or otherwise malformed.
  38. */
  39. - (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
  40. {
  41. CDVPluginResult* result = nil;
  42. NSDictionary* entry = [self makeEntryForLocalURL:url];
  43. if (entry) {
  44. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
  45. } else {
  46. // return NOT_FOUND_ERR
  47. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
  48. }
  49. return result;
  50. }
  51. - (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
  52. NSString *path = [self filesystemPathForURL:url];
  53. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  54. BOOL isDir = NO;
  55. // see if exists and is file or dir
  56. BOOL bExists = [fileMgr fileExistsAtPath:path isDirectory:&isDir];
  57. if (bExists) {
  58. return [self makeEntryForPath:url.fullPath isDirectory:isDir];
  59. } else {
  60. return nil;
  61. }
  62. }
  63. - (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir
  64. {
  65. NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
  66. NSString* lastPart = [[self stripQueryParametersFromPath:fullPath] lastPathComponent];
  67. if (isDir && ![fullPath hasSuffix:@"/"]) {
  68. fullPath = [fullPath stringByAppendingString:@"/"];
  69. }
  70. [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
  71. [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
  72. [dirEntry setObject:fullPath forKey:@"fullPath"];
  73. [dirEntry setObject:lastPart forKey:@"name"];
  74. [dirEntry setObject:self.name forKey: @"filesystemName"];
  75. NSURL* nativeURL = [NSURL fileURLWithPath:[self filesystemPathForFullPath:fullPath]];
  76. if (self.urlTransformer) {
  77. nativeURL = self.urlTransformer(nativeURL);
  78. }
  79. dirEntry[@"nativeURL"] = [nativeURL absoluteString];
  80. return dirEntry;
  81. }
  82. - (NSString *)stripQueryParametersFromPath:(NSString *)fullPath
  83. {
  84. NSRange questionMark = [fullPath rangeOfString:@"?"];
  85. if (questionMark.location != NSNotFound) {
  86. return [fullPath substringWithRange:NSMakeRange(0,questionMark.location)];
  87. }
  88. return fullPath;
  89. }
  90. - (NSString *)filesystemPathForFullPath:(NSString *)fullPath
  91. {
  92. NSString *path = nil;
  93. NSString *strippedFullPath = [self stripQueryParametersFromPath:fullPath];
  94. path = [NSString stringWithFormat:@"%@%@", self.fsRoot, strippedFullPath];
  95. if ([path length] > 1 && [path hasSuffix:@"/"]) {
  96. path = [path substringToIndex:([path length]-1)];
  97. }
  98. return path;
  99. }
  100. /*
  101. * IN
  102. * NSString localURI
  103. * OUT
  104. * NSString full local filesystem path for the represented file or directory, or nil if no such path is possible
  105. * The file or directory does not necessarily have to exist. nil is returned if the filesystem type is not recognized,
  106. * or if the URL is malformed.
  107. * The incoming URI should be properly escaped (no raw spaces, etc. URI percent-encoding is expected).
  108. */
  109. - (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
  110. {
  111. return [self filesystemPathForFullPath:url.fullPath];
  112. }
  113. - (CDVFilesystemURL *)URLforFullPath:(NSString *)fullPath
  114. {
  115. if (fullPath) {
  116. NSString* escapedPath = [fullPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  117. if ([fullPath hasPrefix:@"/"]) {
  118. return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];
  119. }
  120. return [CDVFilesystemURL fileSystemURLWithString:[NSString stringWithFormat:@"%@://localhost/%@/%@", kCDVFilesystemURLPrefix, self.name, escapedPath]];
  121. }
  122. return nil;
  123. }
  124. - (CDVFilesystemURL *)URLforFilesystemPath:(NSString *)path
  125. {
  126. return [self URLforFullPath:[self fullPathForFileSystemPath:path]];
  127. }
  128. - (NSString *)normalizePath:(NSString *)rawPath
  129. {
  130. // If this is an absolute path, the first path component will be '/'. Skip it if that's the case
  131. BOOL isAbsolutePath = [rawPath hasPrefix:@"/"];
  132. if (isAbsolutePath) {
  133. rawPath = [rawPath substringFromIndex:1];
  134. }
  135. NSMutableArray *components = [NSMutableArray arrayWithArray:[rawPath pathComponents]];
  136. for (int index = 0; index < [components count]; ++index) {
  137. if ([[components objectAtIndex:index] isEqualToString:@".."]) {
  138. [components removeObjectAtIndex:index];
  139. if (index > 0) {
  140. [components removeObjectAtIndex:index-1];
  141. --index;
  142. }
  143. }
  144. }
  145. if (isAbsolutePath) {
  146. return [NSString stringWithFormat:@"/%@", [components componentsJoinedByString:@"/"]];
  147. } else {
  148. return [components componentsJoinedByString:@"/"];
  149. }
  150. }
  151. - (BOOL)valueForKeyIsNumber:(NSDictionary*)dict key:(NSString*)key
  152. {
  153. BOOL bNumber = NO;
  154. NSObject* value = dict[key];
  155. if (value) {
  156. bNumber = [value isKindOfClass:[NSNumber class]];
  157. }
  158. return bNumber;
  159. }
  160. - (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
  161. {
  162. CDVPluginResult* result = nil;
  163. BOOL bDirRequest = NO;
  164. BOOL create = NO;
  165. BOOL exclusive = NO;
  166. int errorCode = 0; // !!! risky - no error code currently defined for 0
  167. if ([self valueForKeyIsNumber:options key:@"create"]) {
  168. create = [(NSNumber*)[options valueForKey:@"create"] boolValue];
  169. }
  170. if ([self valueForKeyIsNumber:options key:@"exclusive"]) {
  171. exclusive = [(NSNumber*)[options valueForKey:@"exclusive"] boolValue];
  172. }
  173. if ([self valueForKeyIsNumber:options key:@"getDir"]) {
  174. // this will not exist for calls directly to getFile but will have been set by getDirectory before calling this method
  175. bDirRequest = [(NSNumber*)[options valueForKey:@"getDir"] boolValue];
  176. }
  177. // see if the requested path has invalid characters - should we be checking for more than just ":"?
  178. if ([requestedPath rangeOfString:@":"].location != NSNotFound) {
  179. errorCode = ENCODING_ERR;
  180. } else {
  181. // Build new fullPath for the requested resource.
  182. // We concatenate the two paths together, and then scan the resulting string to remove
  183. // parent ("..") references. Any parent references at the beginning of the string are
  184. // silently removed.
  185. NSString *combinedPath = [baseURI.fullPath stringByAppendingPathComponent:requestedPath];
  186. combinedPath = [self normalizePath:combinedPath];
  187. CDVFilesystemURL* requestedURL = [self URLforFullPath:combinedPath];
  188. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  189. BOOL bIsDir;
  190. BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:requestedURL] isDirectory:&bIsDir];
  191. if (bExists && (create == NO) && (bIsDir == !bDirRequest)) {
  192. // path exists and is not of requested type - return TYPE_MISMATCH_ERR
  193. errorCode = TYPE_MISMATCH_ERR;
  194. } else if (!bExists && (create == NO)) {
  195. // path does not exist and create is false - return NOT_FOUND_ERR
  196. errorCode = NOT_FOUND_ERR;
  197. } else if (bExists && (create == YES) && (exclusive == YES)) {
  198. // file/dir already exists and exclusive and create are both true - return PATH_EXISTS_ERR
  199. errorCode = PATH_EXISTS_ERR;
  200. } else {
  201. // if bExists and create == YES - just return data
  202. // if bExists and create == NO - just return data
  203. // if !bExists and create == YES - create and return data
  204. BOOL bSuccess = YES;
  205. NSError __autoreleasing* pError = nil;
  206. if (!bExists && (create == YES)) {
  207. if (bDirRequest) {
  208. // create the dir
  209. bSuccess = [fileMgr createDirectoryAtPath:[self filesystemPathForURL:requestedURL] withIntermediateDirectories:NO attributes:nil error:&pError];
  210. } else {
  211. // create the empty file
  212. bSuccess = [fileMgr createFileAtPath:[self filesystemPathForURL:requestedURL] contents:nil attributes:nil];
  213. }
  214. }
  215. if (!bSuccess) {
  216. errorCode = ABORT_ERR;
  217. if (pError) {
  218. NSLog(@"error creating directory: %@", [pError localizedDescription]);
  219. }
  220. } else {
  221. // NSLog(@"newly created file/dir (%@) exists: %d", reqFullPath, [fileMgr fileExistsAtPath:reqFullPath]);
  222. // file existed or was created
  223. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:requestedURL.fullPath isDirectory:bDirRequest]];
  224. }
  225. } // are all possible conditions met?
  226. }
  227. if (errorCode > 0) {
  228. // create error callback
  229. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:errorCode];
  230. }
  231. return result;
  232. }
  233. - (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
  234. {
  235. CDVPluginResult* result = nil;
  236. CDVFilesystemURL *newURI = nil;
  237. if ([localURI.fullPath isEqualToString:@""]) {
  238. // return self
  239. newURI = localURI;
  240. } else {
  241. newURI = [CDVFilesystemURL fileSystemURLWithURL:[localURI.url URLByDeletingLastPathComponent]]; /* TODO: UGLY - FIX */
  242. }
  243. NSFileManager* fileMgr = [[NSFileManager alloc] init];
  244. BOOL bIsDir;
  245. BOOL bExists = [fileMgr fileExistsAtPath:[self filesystemPathForURL:newURI] isDirectory:&bIsDir];
  246. if (bExists) {
  247. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self makeEntryForPath:newURI.fullPath isDirectory:bIsDir]];
  248. } else {
  249. // invalid path or file does not exist
  250. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR];
  251. }
  252. return result;
  253. }
  254. - (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
  255. {
  256. BOOL ok = NO;
  257. NSString* filePath = [self filesystemPathForURL:localURI];
  258. // we only care about this iCloud key for now.
  259. // set to 1/true to skip backup, set to 0/false to back it up (effectively removing the attribute)
  260. NSString* iCloudBackupExtendedAttributeKey = @"com.apple.MobileBackup";
  261. id iCloudBackupExtendedAttributeValue = [options objectForKey:iCloudBackupExtendedAttributeKey];
  262. if ((iCloudBackupExtendedAttributeValue != nil) && [iCloudBackupExtendedAttributeValue isKindOfClass:[NSNumber class]]) {
  263. if (IsAtLeastiOSVersion(@"5.1")) {
  264. NSURL* url = [NSURL fileURLWithPath:filePath];
  265. NSError* __autoreleasing error = nil;
  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:[self mimeTypeForFileAtPath: path] forKey:@"type"];
  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. // fix errors that base on Alexsander Akers from http://stackoverflow.com/a/5998683/2613194
  655. - (NSString*) mimeTypeForFileAtPath: (NSString *) path {
  656. if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
  657. return nil;
  658. }
  659. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL);
  660. CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
  661. CFRelease(UTI);
  662. if (!mimeType) {
  663. return @"application/octet-stream";
  664. }
  665. return (__bridge NSString *)mimeType;
  666. }
  667. @end