Brak opisu

CDVAssetLibraryFilesystem.m 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 "CDVAssetLibraryFilesystem.h"
  19. #import <Cordova/CDV.h>
  20. #import <AssetsLibrary/ALAsset.h>
  21. #import <AssetsLibrary/ALAssetRepresentation.h>
  22. #import <AssetsLibrary/ALAssetsLibrary.h>
  23. #import <MobileCoreServices/MobileCoreServices.h>
  24. NSString* const kCDVAssetsLibraryPrefix = @"assets-library://";
  25. NSString* const kCDVAssetsLibraryScheme = @"assets-library";
  26. @implementation CDVAssetLibraryFilesystem
  27. @synthesize name=_name, urlTransformer;
  28. /*
  29. The CDVAssetLibraryFilesystem works with resources which are identified
  30. by iOS as
  31. asset-library://<path>
  32. and represents them internally as URLs of the form
  33. cdvfile://localhost/assets-library/<path>
  34. */
  35. - (NSURL *)assetLibraryURLForLocalURL:(CDVFilesystemURL *)url
  36. {
  37. if ([url.url.scheme isEqualToString:kCDVFilesystemURLPrefix]) {
  38. NSString *path = [[url.url absoluteString] substringFromIndex:[@"cdvfile://localhost/assets-library" length]];
  39. return [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@", path]];
  40. }
  41. return url.url;
  42. }
  43. - (CDVPluginResult *)entryForLocalURI:(CDVFilesystemURL *)url
  44. {
  45. NSDictionary* entry = [self makeEntryForLocalURL:url];
  46. return [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:entry];
  47. }
  48. - (NSDictionary *)makeEntryForLocalURL:(CDVFilesystemURL *)url {
  49. return [self makeEntryForPath:url.fullPath isDirectory:NO];
  50. }
  51. - (NSDictionary*)makeEntryForPath:(NSString*)fullPath isDirectory:(BOOL)isDir
  52. {
  53. NSMutableDictionary* dirEntry = [NSMutableDictionary dictionaryWithCapacity:5];
  54. NSString* lastPart = [fullPath lastPathComponent];
  55. if (isDir && ![fullPath hasSuffix:@"/"]) {
  56. fullPath = [fullPath stringByAppendingString:@"/"];
  57. }
  58. [dirEntry setObject:[NSNumber numberWithBool:!isDir] forKey:@"isFile"];
  59. [dirEntry setObject:[NSNumber numberWithBool:isDir] forKey:@"isDirectory"];
  60. [dirEntry setObject:fullPath forKey:@"fullPath"];
  61. [dirEntry setObject:lastPart forKey:@"name"];
  62. [dirEntry setObject:self.name forKey: @"filesystemName"];
  63. NSURL* nativeURL = [NSURL URLWithString:[NSString stringWithFormat:@"assets-library:/%@",fullPath]];
  64. if (self.urlTransformer) {
  65. nativeURL = self.urlTransformer(nativeURL);
  66. }
  67. dirEntry[@"nativeURL"] = [nativeURL absoluteString];
  68. return dirEntry;
  69. }
  70. /* helper function to get the mimeType from the file extension
  71. * IN:
  72. * NSString* fullPath - filename (may include path)
  73. * OUT:
  74. * NSString* the mime type as type/subtype. nil if not able to determine
  75. */
  76. + (NSString*)getMimeTypeFromPath:(NSString*)fullPath
  77. {
  78. NSString* mimeType = nil;
  79. if (fullPath) {
  80. CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
  81. if (typeId) {
  82. mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
  83. if (!mimeType) {
  84. // special case for m4a
  85. if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
  86. mimeType = @"audio/mp4";
  87. } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
  88. mimeType = @"audio/wav";
  89. } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
  90. mimeType = @"text/css";
  91. }
  92. }
  93. CFRelease(typeId);
  94. }
  95. }
  96. return mimeType;
  97. }
  98. - (id)initWithName:(NSString *)name
  99. {
  100. if (self) {
  101. self.name = name;
  102. }
  103. return self;
  104. }
  105. - (CDVPluginResult *)getFileForURL:(CDVFilesystemURL *)baseURI requestedPath:(NSString *)requestedPath options:(NSDictionary *)options
  106. {
  107. // return unsupported result for assets-library URLs
  108. return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"getFile not supported for assets-library URLs."];
  109. }
  110. - (CDVPluginResult*)getParentForURL:(CDVFilesystemURL *)localURI
  111. {
  112. // we don't (yet?) support getting the parent of an asset
  113. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_READABLE_ERR];
  114. }
  115. - (CDVPluginResult*)setMetadataForURL:(CDVFilesystemURL *)localURI withObject:(NSDictionary *)options
  116. {
  117. // setMetadata doesn't make sense for asset library files
  118. return [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
  119. }
  120. - (CDVPluginResult *)removeFileAtURL:(CDVFilesystemURL *)localURI
  121. {
  122. // return error for assets-library URLs
  123. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
  124. }
  125. - (CDVPluginResult *)recursiveRemoveFileAtURL:(CDVFilesystemURL *)localURI
  126. {
  127. // return error for assets-library URLs
  128. return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"removeRecursively not supported for assets-library URLs."];
  129. }
  130. - (CDVPluginResult *)readEntriesAtURL:(CDVFilesystemURL *)localURI
  131. {
  132. // return unsupported result for assets-library URLs
  133. return [CDVPluginResult resultWithStatus:CDVCommandStatus_MALFORMED_URL_EXCEPTION messageAsString:@"readEntries not supported for assets-library URLs."];
  134. }
  135. - (CDVPluginResult *)truncateFileAtURL:(CDVFilesystemURL *)localURI atPosition:(unsigned long long)pos
  136. {
  137. // assets-library files can't be truncated
  138. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
  139. }
  140. - (CDVPluginResult *)writeToFileAtURL:(CDVFilesystemURL *)localURL withData:(NSData*)encData append:(BOOL)shouldAppend
  141. {
  142. // text can't be written into assets-library files
  143. return [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NO_MODIFICATION_ALLOWED_ERR];
  144. }
  145. - (void)copyFileToURL:(CDVFilesystemURL *)destURL withName:(NSString *)newName fromFileSystem:(NSObject<CDVFileSystem> *)srcFs atURL:(CDVFilesystemURL *)srcURL copy:(BOOL)bCopy callback:(void (^)(CDVPluginResult *))callback
  146. {
  147. // Copying to an assets library file is not doable, since we can't write it.
  148. CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:INVALID_MODIFICATION_ERR];
  149. callback(result);
  150. }
  151. - (NSString *)filesystemPathForURL:(CDVFilesystemURL *)url
  152. {
  153. NSString *path = nil;
  154. if ([[url.url scheme] isEqualToString:kCDVAssetsLibraryScheme]) {
  155. path = [url.url path];
  156. } else {
  157. path = url.fullPath;
  158. }
  159. if ([path hasSuffix:@"/"]) {
  160. path = [path substringToIndex:([path length]-1)];
  161. }
  162. return path;
  163. }
  164. - (void)readFileAtURL:(CDVFilesystemURL *)localURL start:(NSInteger)start end:(NSInteger)end callback:(void (^)(NSData*, NSString* mimeType, CDVFileError))callback
  165. {
  166. ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
  167. if (asset) {
  168. // We have the asset! Get the data and send it off.
  169. ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
  170. NSUInteger size = (end > start) ? (end - start) : [assetRepresentation size];
  171. Byte* buffer = (Byte*)malloc(size);
  172. NSUInteger bufferSize = [assetRepresentation getBytes:buffer fromOffset:start length:size error:nil];
  173. NSData* data = [NSData dataWithBytesNoCopy:buffer length:bufferSize freeWhenDone:YES];
  174. NSString* MIMEType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)[assetRepresentation UTI], kUTTagClassMIMEType);
  175. callback(data, MIMEType, NO_ERROR);
  176. } else {
  177. callback(nil, nil, NOT_FOUND_ERR);
  178. }
  179. };
  180. ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
  181. // Retrieving the asset failed for some reason. Send the appropriate error.
  182. NSLog(@"Error: %@", error);
  183. callback(nil, nil, SECURITY_ERR);
  184. };
  185. ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
  186. [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
  187. }
  188. - (void)getFileMetadataForURL:(CDVFilesystemURL *)localURL callback:(void (^)(CDVPluginResult *))callback
  189. {
  190. // In this case, we need to use an asynchronous method to retrieve the file.
  191. // Because of this, we can't just assign to `result` and send it at the end of the method.
  192. // Instead, we return after calling the asynchronous method and send `result` in each of the blocks.
  193. ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset) {
  194. if (asset) {
  195. // We have the asset! Populate the dictionary and send it off.
  196. NSMutableDictionary* fileInfo = [NSMutableDictionary dictionaryWithCapacity:5];
  197. ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
  198. [fileInfo setObject:[NSNumber numberWithUnsignedLongLong:[assetRepresentation size]] forKey:@"size"];
  199. [fileInfo setObject:localURL.fullPath forKey:@"fullPath"];
  200. NSString* filename = [assetRepresentation filename];
  201. [fileInfo setObject:filename forKey:@"name"];
  202. [fileInfo setObject:[CDVAssetLibraryFilesystem getMimeTypeFromPath:filename] forKey:@"type"];
  203. NSDate* creationDate = [asset valueForProperty:ALAssetPropertyDate];
  204. NSNumber* msDate = [NSNumber numberWithDouble:[creationDate timeIntervalSince1970] * 1000];
  205. [fileInfo setObject:msDate forKey:@"lastModifiedDate"];
  206. callback([CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:fileInfo]);
  207. } else {
  208. // We couldn't find the asset. Send the appropriate error.
  209. callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsInt:NOT_FOUND_ERR]);
  210. }
  211. };
  212. ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError* error) {
  213. // Retrieving the asset failed for some reason. Send the appropriate error.
  214. callback([CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsString:[error localizedDescription]]);
  215. };
  216. ALAssetsLibrary* assetsLibrary = [[ALAssetsLibrary alloc] init];
  217. [assetsLibrary assetForURL:[self assetLibraryURLForLocalURL:localURL] resultBlock:resultBlock failureBlock:failureBlock];
  218. return;
  219. }
  220. @end