PageRenderTime 64ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/front/plugins/cordova-plugin-file-transfer/src/ios/CDVFileTransfer.m

https://gitlab.com/boxnia/NFU_MOVIL
Objective C | 845 lines | 645 code | 122 blank | 78 comment | 150 complexity | c729265518264699331d7cce90bd2b98 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 <Cordova/CDV.h>
  18. #import "CDVFileTransfer.h"
  19. #import "CDVLocalFilesystem.h"
  20. #import <AssetsLibrary/ALAsset.h>
  21. #import <AssetsLibrary/ALAssetRepresentation.h>
  22. #import <AssetsLibrary/ALAssetsLibrary.h>
  23. #import <CFNetwork/CFNetwork.h>
  24. #ifndef DLog
  25. #ifdef DEBUG
  26. #define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
  27. #else
  28. #define DLog(...)
  29. #endif
  30. #endif
  31. @interface CDVFileTransfer ()
  32. // Sets the requests headers for the request.
  33. - (void)applyRequestHeaders:(NSDictionary*)headers toRequest:(NSMutableURLRequest*)req;
  34. // Creates a delegate to handle an upload.
  35. - (CDVFileTransferDelegate*)delegateForUploadCommand:(CDVInvokedUrlCommand*)command;
  36. // Creates an NSData* for the file for the given upload arguments.
  37. - (void)fileDataForUploadCommand:(CDVInvokedUrlCommand*)command;
  38. @end
  39. // Buffer size to use for streaming uploads.
  40. static const NSUInteger kStreamBufferSize = 32768;
  41. // Magic value within the options dict used to set a cookie.
  42. NSString* const kOptionsKeyCookie = @"__cookie";
  43. // Form boundary for multi-part requests.
  44. NSString* const kFormBoundary = @"+++++org.apache.cordova.formBoundary";
  45. // Writes the given data to the stream in a blocking way.
  46. // If successful, returns bytesToWrite.
  47. // If the stream was closed on the other end, returns 0.
  48. // If there was an error, returns -1.
  49. static CFIndex WriteDataToStream(NSData* data, CFWriteStreamRef stream)
  50. {
  51. UInt8* bytes = (UInt8*)[data bytes];
  52. long long bytesToWrite = [data length];
  53. long long totalBytesWritten = 0;
  54. while (totalBytesWritten < bytesToWrite) {
  55. CFIndex result = CFWriteStreamWrite(stream,
  56. bytes + totalBytesWritten,
  57. bytesToWrite - totalBytesWritten);
  58. if (result < 0) {
  59. CFStreamError error = CFWriteStreamGetError(stream);
  60. NSLog(@"WriteStreamError domain: %ld error: %ld", error.domain, (long)error.error);
  61. return result;
  62. } else if (result == 0) {
  63. return result;
  64. }
  65. totalBytesWritten += result;
  66. }
  67. return totalBytesWritten;
  68. }
  69. @implementation CDVFileTransfer
  70. @synthesize activeTransfers;
  71. - (void)pluginInitialize {
  72. activeTransfers = [[NSMutableDictionary alloc] init];
  73. }
  74. - (NSString*)escapePathComponentForUrlString:(NSString*)urlString
  75. {
  76. NSRange schemeAndHostRange = [urlString rangeOfString:@"://.*?/" options:NSRegularExpressionSearch];
  77. if (schemeAndHostRange.length == 0) {
  78. return urlString;
  79. }
  80. NSInteger schemeAndHostEndIndex = NSMaxRange(schemeAndHostRange);
  81. NSString* schemeAndHost = [urlString substringToIndex:schemeAndHostEndIndex];
  82. NSString* pathComponent = [urlString substringFromIndex:schemeAndHostEndIndex];
  83. pathComponent = [pathComponent stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  84. return [schemeAndHost stringByAppendingString:pathComponent];
  85. }
  86. - (void)applyRequestHeaders:(NSDictionary*)headers toRequest:(NSMutableURLRequest*)req
  87. {
  88. [req setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
  89. NSString* userAgent = [self.commandDelegate userAgent];
  90. if (userAgent) {
  91. [req setValue:userAgent forHTTPHeaderField:@"User-Agent"];
  92. }
  93. for (NSString* headerName in headers) {
  94. id value = [headers objectForKey:headerName];
  95. if (!value || (value == [NSNull null])) {
  96. value = @"null";
  97. }
  98. // First, remove an existing header if one exists.
  99. [req setValue:nil forHTTPHeaderField:headerName];
  100. if (![value isKindOfClass:[NSArray class]]) {
  101. value = [NSArray arrayWithObject:value];
  102. }
  103. // Then, append all header values.
  104. for (id __strong subValue in value) {
  105. // Convert from an NSNumber -> NSString.
  106. if ([subValue respondsToSelector:@selector(stringValue)]) {
  107. subValue = [subValue stringValue];
  108. }
  109. if ([subValue isKindOfClass:[NSString class]]) {
  110. [req addValue:subValue forHTTPHeaderField:headerName];
  111. }
  112. }
  113. }
  114. }
  115. - (NSURLRequest*)requestForUploadCommand:(CDVInvokedUrlCommand*)command fileData:(NSData*)fileData
  116. {
  117. // arguments order from js: [filePath, server, fileKey, fileName, mimeType, params, debug, chunkedMode]
  118. // however, params is a JavaScript object and during marshalling is put into the options dict,
  119. // thus debug and chunkedMode are the 6th and 7th arguments
  120. NSString* target = [command argumentAtIndex:0];
  121. NSString* server = [command argumentAtIndex:1];
  122. NSString* fileKey = [command argumentAtIndex:2 withDefault:@"file"];
  123. NSString* fileName = [command argumentAtIndex:3 withDefault:@"image.jpg"];
  124. NSString* mimeType = [command argumentAtIndex:4 withDefault:@"image/jpeg"];
  125. NSDictionary* options = [command argumentAtIndex:5 withDefault:nil];
  126. // BOOL trustAllHosts = [[command argumentAtIndex:6 withDefault:[NSNumber numberWithBool:YES]] boolValue]; // allow self-signed certs
  127. BOOL chunkedMode = [[command argumentAtIndex:7 withDefault:[NSNumber numberWithBool:YES]] boolValue];
  128. NSDictionary* headers = [command argumentAtIndex:8 withDefault:nil];
  129. // Allow alternative http method, default to POST. JS side checks
  130. // for allowed methods, currently PUT or POST (forces POST for
  131. // unrecognised values)
  132. NSString* httpMethod = [command argumentAtIndex:10 withDefault:@"POST"];
  133. CDVPluginResult* result = nil;
  134. CDVFileTransferError errorCode = 0;
  135. // NSURL does not accepts URLs with spaces in the path. We escape the path in order
  136. // to be more lenient.
  137. NSURL* url = [NSURL URLWithString:server];
  138. if (!url) {
  139. errorCode = INVALID_URL_ERR;
  140. NSLog(@"File Transfer Error: Invalid server URL %@", server);
  141. } else if (!fileData) {
  142. errorCode = FILE_NOT_FOUND_ERR;
  143. }
  144. if (errorCode > 0) {
  145. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:errorCode AndSource:target AndTarget:server]];
  146. [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  147. return nil;
  148. }
  149. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url];
  150. [req setHTTPMethod:httpMethod];
  151. // Magic value to set a cookie
  152. if ([options objectForKey:kOptionsKeyCookie]) {
  153. [req setValue:[options objectForKey:kOptionsKeyCookie] forHTTPHeaderField:@"Cookie"];
  154. [req setHTTPShouldHandleCookies:NO];
  155. }
  156. // if we specified a Content-Type header, don't do multipart form upload
  157. BOOL multipartFormUpload = [headers objectForKey:@"Content-Type"] == nil;
  158. if (multipartFormUpload) {
  159. NSString* contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", kFormBoundary];
  160. [req setValue:contentType forHTTPHeaderField:@"Content-Type"];
  161. }
  162. [self applyRequestHeaders:headers toRequest:req];
  163. NSData* formBoundaryData = [[NSString stringWithFormat:@"--%@\r\n", kFormBoundary] dataUsingEncoding:NSUTF8StringEncoding];
  164. NSMutableData* postBodyBeforeFile = [NSMutableData data];
  165. for (NSString* key in options) {
  166. id val = [options objectForKey:key];
  167. if (!val || (val == [NSNull null]) || [key isEqualToString:kOptionsKeyCookie]) {
  168. continue;
  169. }
  170. // if it responds to stringValue selector (eg NSNumber) get the NSString
  171. if ([val respondsToSelector:@selector(stringValue)]) {
  172. val = [val stringValue];
  173. }
  174. // finally, check whether it is a NSString (for dataUsingEncoding selector below)
  175. if (![val isKindOfClass:[NSString class]]) {
  176. continue;
  177. }
  178. [postBodyBeforeFile appendData:formBoundaryData];
  179. [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
  180. [postBodyBeforeFile appendData:[val dataUsingEncoding:NSUTF8StringEncoding]];
  181. [postBodyBeforeFile appendData:[@"\r\n" dataUsingEncoding : NSUTF8StringEncoding]];
  182. }
  183. [postBodyBeforeFile appendData:formBoundaryData];
  184. [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileKey, fileName] dataUsingEncoding:NSUTF8StringEncoding]];
  185. if (mimeType != nil) {
  186. [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType] dataUsingEncoding:NSUTF8StringEncoding]];
  187. }
  188. [postBodyBeforeFile appendData:[[NSString stringWithFormat:@"Content-Length: %ld\r\n\r\n", (long)[fileData length]] dataUsingEncoding:NSUTF8StringEncoding]];
  189. DLog(@"fileData length: %d", [fileData length]);
  190. NSData* postBodyAfterFile = [[NSString stringWithFormat:@"\r\n--%@--\r\n", kFormBoundary] dataUsingEncoding:NSUTF8StringEncoding];
  191. long long totalPayloadLength = [fileData length];
  192. if (multipartFormUpload) {
  193. totalPayloadLength += [postBodyBeforeFile length] + [postBodyAfterFile length];
  194. }
  195. [req setValue:[[NSNumber numberWithLongLong:totalPayloadLength] stringValue] forHTTPHeaderField:@"Content-Length"];
  196. if (chunkedMode) {
  197. CFReadStreamRef readStream = NULL;
  198. CFWriteStreamRef writeStream = NULL;
  199. CFStreamCreateBoundPair(NULL, &readStream, &writeStream, kStreamBufferSize);
  200. [req setHTTPBodyStream:CFBridgingRelease(readStream)];
  201. [self.commandDelegate runInBackground:^{
  202. if (CFWriteStreamOpen(writeStream)) {
  203. if (multipartFormUpload) {
  204. NSData* chunks[] = { postBodyBeforeFile, fileData, postBodyAfterFile };
  205. int numChunks = sizeof(chunks) / sizeof(chunks[0]);
  206. for (int i = 0; i < numChunks; ++i) {
  207. // Allow uploading of an empty file
  208. if (chunks[i].length == 0) {
  209. continue;
  210. }
  211. CFIndex result = WriteDataToStream(chunks[i], writeStream);
  212. if (result <= 0) {
  213. break;
  214. }
  215. }
  216. } else {
  217. WriteDataToStream(fileData, writeStream);
  218. }
  219. } else {
  220. NSLog(@"FileTransfer: Failed to open writeStream");
  221. }
  222. CFWriteStreamClose(writeStream);
  223. CFRelease(writeStream);
  224. }];
  225. } else {
  226. if (multipartFormUpload) {
  227. [postBodyBeforeFile appendData:fileData];
  228. [postBodyBeforeFile appendData:postBodyAfterFile];
  229. [req setHTTPBody:postBodyBeforeFile];
  230. } else {
  231. [req setHTTPBody:fileData];
  232. }
  233. }
  234. return req;
  235. }
  236. - (CDVFileTransferDelegate*)delegateForUploadCommand:(CDVInvokedUrlCommand*)command
  237. {
  238. NSString* source = [command argumentAtIndex:0];
  239. NSString* server = [command argumentAtIndex:1];
  240. BOOL trustAllHosts = [[command argumentAtIndex:6 withDefault:[NSNumber numberWithBool:NO]] boolValue]; // allow self-signed certs
  241. NSString* objectId = [command argumentAtIndex:9];
  242. CDVFileTransferDelegate* delegate = [[CDVFileTransferDelegate alloc] init];
  243. delegate.command = self;
  244. delegate.callbackId = command.callbackId;
  245. delegate.direction = CDV_TRANSFER_UPLOAD;
  246. delegate.objectId = objectId;
  247. delegate.source = source;
  248. delegate.target = server;
  249. delegate.trustAllHosts = trustAllHosts;
  250. delegate.filePlugin = [self.commandDelegate getCommandInstance:@"File"];
  251. return delegate;
  252. }
  253. - (void)fileDataForUploadCommand:(CDVInvokedUrlCommand*)command
  254. {
  255. NSString* source = (NSString*)[command argumentAtIndex:0];
  256. NSString* server = [command argumentAtIndex:1];
  257. NSError* __autoreleasing err = nil;
  258. if ([source hasPrefix:@"data:"] && [source rangeOfString:@"base64"].location != NSNotFound) {
  259. NSRange commaRange = [source rangeOfString: @","];
  260. if (commaRange.location == NSNotFound) {
  261. // Return error is there is no comma
  262. __weak CDVFileTransfer* weakSelf = self;
  263. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[weakSelf createFileTransferError:INVALID_URL_ERR AndSource:source AndTarget:server]];
  264. [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  265. return;
  266. }
  267. if (commaRange.location + 1 > source.length - 1) {
  268. // Init as an empty data
  269. NSData *fileData = [[NSData alloc] init];
  270. [self uploadData:fileData command:command];
  271. return;
  272. }
  273. NSData *fileData = [[NSData alloc] initWithBase64EncodedString:[source substringFromIndex:(commaRange.location + 1)] options:NSDataBase64DecodingIgnoreUnknownCharacters];
  274. [self uploadData:fileData command:command];
  275. return;
  276. }
  277. CDVFilesystemURL *sourceURL = [CDVFilesystemURL fileSystemURLWithString:source];
  278. NSObject<CDVFileSystem> *fs;
  279. if (sourceURL) {
  280. // Try to get a CDVFileSystem which will handle this file.
  281. // This requires talking to the current CDVFile plugin.
  282. fs = [[self.commandDelegate getCommandInstance:@"File"] filesystemForURL:sourceURL];
  283. }
  284. if (fs) {
  285. __weak CDVFileTransfer* weakSelf = self;
  286. [fs readFileAtURL:sourceURL start:0 end:-1 callback:^(NSData *fileData, NSString *mimeType, CDVFileError err) {
  287. if (err) {
  288. // We couldn't find the asset. Send the appropriate error.
  289. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[weakSelf createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]];
  290. [weakSelf.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  291. } else {
  292. [weakSelf uploadData:fileData command:command];
  293. }
  294. }];
  295. return;
  296. } else {
  297. // Extract the path part out of a file: URL.
  298. NSString* filePath = [source hasPrefix:@"/"] ? [source copy] : [(NSURL *)[NSURL URLWithString:source] path];
  299. if (filePath == nil) {
  300. // We couldn't find the asset. Send the appropriate error.
  301. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]];
  302. [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  303. return;
  304. }
  305. // Memory map the file so that it can be read efficiently even if it is large.
  306. NSData* fileData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&err];
  307. if (err != nil) {
  308. NSLog(@"Error opening file %@: %@", source, err);
  309. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:NOT_FOUND_ERR AndSource:source AndTarget:server]];
  310. [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  311. } else {
  312. [self uploadData:fileData command:command];
  313. }
  314. }
  315. }
  316. - (void)upload:(CDVInvokedUrlCommand*)command
  317. {
  318. // fileData and req are split into helper functions to ease the unit testing of delegateForUpload.
  319. // First, get the file data. This method will call `uploadData:command`.
  320. [self fileDataForUploadCommand:command];
  321. }
  322. - (void)uploadData:(NSData*)fileData command:(CDVInvokedUrlCommand*)command
  323. {
  324. NSURLRequest* req = [self requestForUploadCommand:command fileData:fileData];
  325. if (req == nil) {
  326. return;
  327. }
  328. CDVFileTransferDelegate* delegate = [self delegateForUploadCommand:command];
  329. delegate.connection = [[NSURLConnection alloc] initWithRequest:req delegate:delegate startImmediately:NO];
  330. if (self.queue == nil) {
  331. self.queue = [[NSOperationQueue alloc] init];
  332. }
  333. [delegate.connection setDelegateQueue:self.queue];
  334. // sets a background task ID for the transfer object.
  335. delegate.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  336. [delegate cancelTransfer:delegate.connection];
  337. }];
  338. @synchronized (activeTransfers) {
  339. activeTransfers[delegate.objectId] = delegate;
  340. }
  341. [delegate.connection start];
  342. }
  343. - (void)abort:(CDVInvokedUrlCommand*)command
  344. {
  345. NSString* objectId = [command argumentAtIndex:0];
  346. @synchronized (activeTransfers) {
  347. CDVFileTransferDelegate* delegate = activeTransfers[objectId];
  348. if (delegate != nil) {
  349. [delegate cancelTransfer:delegate.connection];
  350. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:CONNECTION_ABORTED AndSource:delegate.source AndTarget:delegate.target]];
  351. [self.commandDelegate sendPluginResult:result callbackId:delegate.callbackId];
  352. }
  353. }
  354. }
  355. - (void)download:(CDVInvokedUrlCommand*)command
  356. {
  357. DLog(@"File Transfer downloading file...");
  358. NSString* source = [command argumentAtIndex:0];
  359. NSString* target = [command argumentAtIndex:1];
  360. BOOL trustAllHosts = [[command argumentAtIndex:2 withDefault:[NSNumber numberWithBool:NO]] boolValue]; // allow self-signed certs
  361. NSString* objectId = [command argumentAtIndex:3];
  362. NSDictionary* headers = [command argumentAtIndex:4 withDefault:nil];
  363. CDVPluginResult* result = nil;
  364. CDVFileTransferError errorCode = 0;
  365. NSURL* targetURL;
  366. if ([target hasPrefix:@"/"]) {
  367. /* Backwards-compatibility:
  368. * Check here to see if it looks like the user passed in a raw filesystem path. (Perhaps they had the path saved, and were previously using it with the old version of File). If so, normalize it by removing empty path segments, and check with File to see if any of the installed filesystems will handle it. If so, then we will end up with a filesystem url to use for the remainder of this operation.
  369. */
  370. target = [target stringByReplacingOccurrencesOfString:@"//" withString:@"/"];
  371. targetURL = [[self.commandDelegate getCommandInstance:@"File"] fileSystemURLforLocalPath:target].url;
  372. } else {
  373. targetURL = [NSURL URLWithString:target];
  374. }
  375. NSURL* sourceURL = [NSURL URLWithString:source];
  376. if (!sourceURL) {
  377. errorCode = INVALID_URL_ERR;
  378. NSLog(@"File Transfer Error: Invalid server URL %@", source);
  379. } else if (![targetURL isFileURL]) {
  380. CDVFilesystemURL *fsURL = [CDVFilesystemURL fileSystemURLWithString:target];
  381. if (!fsURL) {
  382. errorCode = FILE_NOT_FOUND_ERR;
  383. NSLog(@"File Transfer Error: Invalid file path or URL %@", target);
  384. }
  385. }
  386. if (errorCode > 0) {
  387. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[self createFileTransferError:errorCode AndSource:source AndTarget:target]];
  388. [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
  389. return;
  390. }
  391. NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:sourceURL];
  392. [self applyRequestHeaders:headers toRequest:req];
  393. CDVFileTransferDelegate* delegate = [[CDVFileTransferDelegate alloc] init];
  394. delegate.command = self;
  395. delegate.direction = CDV_TRANSFER_DOWNLOAD;
  396. delegate.callbackId = command.callbackId;
  397. delegate.objectId = objectId;
  398. delegate.source = source;
  399. delegate.target = [targetURL absoluteString];
  400. delegate.targetURL = targetURL;
  401. delegate.trustAllHosts = trustAllHosts;
  402. delegate.filePlugin = [self.commandDelegate getCommandInstance:@"File"];
  403. delegate.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  404. [delegate cancelTransfer:delegate.connection];
  405. }];
  406. delegate.connection = [[NSURLConnection alloc] initWithRequest:req delegate:delegate startImmediately:NO];
  407. if (self.queue == nil) {
  408. self.queue = [[NSOperationQueue alloc] init];
  409. }
  410. [delegate.connection setDelegateQueue:self.queue];
  411. @synchronized (activeTransfers) {
  412. activeTransfers[delegate.objectId] = delegate;
  413. }
  414. // Downloads can take time
  415. // sending this to a new thread calling the download_async method
  416. dispatch_async(
  417. dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL),
  418. ^(void) { [delegate.connection start];}
  419. );
  420. }
  421. - (NSMutableDictionary*)createFileTransferError:(int)code AndSource:(NSString*)source AndTarget:(NSString*)target
  422. {
  423. NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:3];
  424. [result setObject:[NSNumber numberWithInt:code] forKey:@"code"];
  425. if (source != nil) {
  426. [result setObject:source forKey:@"source"];
  427. }
  428. if (target != nil) {
  429. [result setObject:target forKey:@"target"];
  430. }
  431. NSLog(@"FileTransferError %@", result);
  432. return result;
  433. }
  434. - (NSMutableDictionary*)createFileTransferError:(int)code
  435. AndSource:(NSString*)source
  436. AndTarget:(NSString*)target
  437. AndHttpStatus:(int)httpStatus
  438. AndBody:(NSString*)body
  439. {
  440. NSMutableDictionary* result = [NSMutableDictionary dictionaryWithCapacity:5];
  441. [result setObject:[NSNumber numberWithInt:code] forKey:@"code"];
  442. if (source != nil) {
  443. [result setObject:source forKey:@"source"];
  444. }
  445. if (target != nil) {
  446. [result setObject:target forKey:@"target"];
  447. }
  448. [result setObject:[NSNumber numberWithInt:httpStatus] forKey:@"http_status"];
  449. if (body != nil) {
  450. [result setObject:body forKey:@"body"];
  451. }
  452. NSLog(@"FileTransferError %@", result);
  453. return result;
  454. }
  455. - (void)onReset {
  456. @synchronized (activeTransfers) {
  457. while ([activeTransfers count] > 0) {
  458. CDVFileTransferDelegate* delegate = [activeTransfers allValues][0];
  459. [delegate cancelTransfer:delegate.connection];
  460. }
  461. }
  462. }
  463. @end
  464. @interface CDVFileTransferEntityLengthRequest : NSObject {
  465. NSURLConnection* _connection;
  466. CDVFileTransferDelegate* __weak _originalDelegate;
  467. }
  468. - (CDVFileTransferEntityLengthRequest*)initWithOriginalRequest:(NSURLRequest*)originalRequest andDelegate:(CDVFileTransferDelegate*)originalDelegate;
  469. @end
  470. @implementation CDVFileTransferEntityLengthRequest
  471. - (CDVFileTransferEntityLengthRequest*)initWithOriginalRequest:(NSURLRequest*)originalRequest andDelegate:(CDVFileTransferDelegate*)originalDelegate
  472. {
  473. if (self) {
  474. DLog(@"Requesting entity length for GZIPped content...");
  475. NSMutableURLRequest* req = [originalRequest mutableCopy];
  476. [req setHTTPMethod:@"HEAD"];
  477. [req setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
  478. _originalDelegate = originalDelegate;
  479. _connection = [NSURLConnection connectionWithRequest:req delegate:self];
  480. }
  481. return self;
  482. }
  483. - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
  484. {
  485. DLog(@"HEAD request returned; content-length is %lld", [response expectedContentLength]);
  486. [_originalDelegate updateBytesExpected:[response expectedContentLength]];
  487. }
  488. - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
  489. {}
  490. - (void)connectionDidFinishLoading:(NSURLConnection*)connection
  491. {}
  492. @end
  493. @implementation CDVFileTransferDelegate
  494. @synthesize callbackId, connection = _connection, source, target, responseData, responseHeaders, command, bytesTransfered, bytesExpected, direction, responseCode, objectId, targetFileHandle, filePlugin;
  495. - (void)connectionDidFinishLoading:(NSURLConnection*)connection
  496. {
  497. NSString* uploadResponse = nil;
  498. NSString* downloadResponse = nil;
  499. NSMutableDictionary* uploadResult;
  500. CDVPluginResult* result = nil;
  501. NSLog(@"File Transfer Finished with response code %d", self.responseCode);
  502. if (self.direction == CDV_TRANSFER_UPLOAD) {
  503. uploadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
  504. if (uploadResponse == nil) {
  505. uploadResponse = [[NSString alloc] initWithData: self.responseData encoding:NSISOLatin1StringEncoding];
  506. }
  507. if ((self.responseCode >= 200) && (self.responseCode < 300)) {
  508. // create dictionary to return FileUploadResult object
  509. uploadResult = [NSMutableDictionary dictionaryWithCapacity:3];
  510. if (uploadResponse != nil) {
  511. [uploadResult setObject:uploadResponse forKey:@"response"];
  512. [uploadResult setObject:self.responseHeaders forKey:@"headers"];
  513. }
  514. [uploadResult setObject:[NSNumber numberWithLongLong:self.bytesTransfered] forKey:@"bytesSent"];
  515. [uploadResult setObject:[NSNumber numberWithInt:self.responseCode] forKey:@"responseCode"];
  516. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:uploadResult];
  517. } else {
  518. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:CONNECTION_ERR AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:uploadResponse]];
  519. }
  520. }
  521. if (self.direction == CDV_TRANSFER_DOWNLOAD) {
  522. if (self.targetFileHandle) {
  523. [self.targetFileHandle closeFile];
  524. self.targetFileHandle = nil;
  525. DLog(@"File Transfer Download success");
  526. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self.filePlugin makeEntryForURL:self.targetURL]];
  527. } else {
  528. downloadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
  529. if (downloadResponse == nil) {
  530. downloadResponse = [[NSString alloc] initWithData: self.responseData encoding:NSISOLatin1StringEncoding];
  531. }
  532. CDVFileTransferError errorCode = self.responseCode == 404 ? FILE_NOT_FOUND_ERR
  533. : (self.responseCode == 304 ? NOT_MODIFIED : CONNECTION_ERR);
  534. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:errorCode AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:downloadResponse]];
  535. }
  536. }
  537. [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
  538. // remove connection for activeTransfers
  539. @synchronized (command.activeTransfers) {
  540. [command.activeTransfers removeObjectForKey:objectId];
  541. // remove background id task in case our upload was done in the background
  542. [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
  543. self.backgroundTaskID = UIBackgroundTaskInvalid;
  544. }
  545. }
  546. - (void)removeTargetFile
  547. {
  548. NSFileManager* fileMgr = [NSFileManager defaultManager];
  549. NSString *targetPath = [self targetFilePath];
  550. if ([fileMgr fileExistsAtPath:targetPath])
  551. {
  552. [fileMgr removeItemAtPath:targetPath error:nil];
  553. }
  554. }
  555. - (void)cancelTransfer:(NSURLConnection*)connection
  556. {
  557. [connection cancel];
  558. @synchronized (self.command.activeTransfers) {
  559. CDVFileTransferDelegate* delegate = self.command.activeTransfers[self.objectId];
  560. [self.command.activeTransfers removeObjectForKey:self.objectId];
  561. [[UIApplication sharedApplication] endBackgroundTask:delegate.backgroundTaskID];
  562. delegate.backgroundTaskID = UIBackgroundTaskInvalid;
  563. }
  564. if (self.direction == CDV_TRANSFER_DOWNLOAD) {
  565. [self removeTargetFile];
  566. }
  567. }
  568. - (void)cancelTransferWithError:(NSURLConnection*)connection errorMessage:(NSString*)errorMessage
  569. {
  570. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_IO_EXCEPTION messageAsDictionary:[self.command createFileTransferError:FILE_NOT_FOUND_ERR AndSource:self.source AndTarget:self.target AndHttpStatus:self.responseCode AndBody:errorMessage]];
  571. NSLog(@"File Transfer Error: %@", errorMessage);
  572. [self cancelTransfer:connection];
  573. [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
  574. }
  575. - (NSString *)targetFilePath
  576. {
  577. NSString *path = nil;
  578. CDVFilesystemURL *sourceURL = [CDVFilesystemURL fileSystemURLWithString:self.target];
  579. if (sourceURL && sourceURL.fileSystemName != nil) {
  580. // This requires talking to the current CDVFile plugin
  581. NSObject<CDVFileSystem> *fs = [self.filePlugin filesystemForURL:sourceURL];
  582. path = [fs filesystemPathForURL:sourceURL];
  583. } else {
  584. // Extract the path part out of a file: URL.
  585. path = [self.target hasPrefix:@"/"] ? [self.target copy] : [(NSURL *)[NSURL URLWithString:self.target] path];
  586. }
  587. return path;
  588. }
  589. - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
  590. {
  591. NSError* __autoreleasing error = nil;
  592. self.mimeType = [response MIMEType];
  593. self.targetFileHandle = nil;
  594. // required for iOS 4.3, for some reason; response is
  595. // a plain NSURLResponse, not the HTTP subclass
  596. if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
  597. NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
  598. self.responseCode = (int)[httpResponse statusCode];
  599. self.bytesExpected = [response expectedContentLength];
  600. self.responseHeaders = [httpResponse allHeaderFields];
  601. if ((self.direction == CDV_TRANSFER_DOWNLOAD) && (self.responseCode == 200) && (self.bytesExpected == NSURLResponseUnknownLength)) {
  602. // Kick off HEAD request to server to get real length
  603. // bytesExpected will be updated when that response is returned
  604. self.entityLengthRequest = [[CDVFileTransferEntityLengthRequest alloc] initWithOriginalRequest:connection.currentRequest andDelegate:self];
  605. }
  606. } else if ([response.URL isFileURL]) {
  607. NSDictionary* attr = [[NSFileManager defaultManager] attributesOfItemAtPath:[response.URL path] error:nil];
  608. self.responseCode = 200;
  609. self.bytesExpected = [attr[NSFileSize] longLongValue];
  610. } else {
  611. self.responseCode = 200;
  612. self.bytesExpected = NSURLResponseUnknownLength;
  613. }
  614. if ((self.direction == CDV_TRANSFER_DOWNLOAD) && (self.responseCode >= 200) && (self.responseCode < 300)) {
  615. // Download response is okay; begin streaming output to file
  616. NSString *filePath = [self targetFilePath];
  617. if (filePath == nil) {
  618. // We couldn't find the asset. Send the appropriate error.
  619. [self cancelTransferWithError:connection errorMessage:[NSString stringWithFormat:@"Could not create target file"]];
  620. return;
  621. }
  622. NSString* parentPath = [filePath stringByDeletingLastPathComponent];
  623. // create parent directories if needed
  624. if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
  625. if (error) {
  626. [self cancelTransferWithError:connection errorMessage:[NSString stringWithFormat:@"Could not create path to save downloaded file: %@", [error localizedDescription]]];
  627. } else {
  628. [self cancelTransferWithError:connection errorMessage:@"Could not create path to save downloaded file"];
  629. }
  630. return;
  631. }
  632. // create target file
  633. if ([[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil] == NO) {
  634. [self cancelTransferWithError:connection errorMessage:@"Could not create target file"];
  635. return;
  636. }
  637. // open target file for writing
  638. self.targetFileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  639. if (self.targetFileHandle == nil) {
  640. [self cancelTransferWithError:connection errorMessage:@"Could not open target file for writing"];
  641. }
  642. DLog(@"Streaming to file %@", filePath);
  643. }
  644. }
  645. - (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
  646. {
  647. NSString* body = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
  648. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:[command createFileTransferError:CONNECTION_ERR AndSource:source AndTarget:target AndHttpStatus:self.responseCode AndBody:body]];
  649. NSLog(@"File Transfer Error: %@", [error localizedDescription]);
  650. [self cancelTransfer:connection];
  651. [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
  652. }
  653. - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
  654. {
  655. self.bytesTransfered += data.length;
  656. if (self.targetFileHandle) {
  657. [self.targetFileHandle writeData:data];
  658. } else {
  659. [self.responseData appendData:data];
  660. }
  661. [self updateProgress];
  662. }
  663. - (void)updateBytesExpected:(long long)newBytesExpected
  664. {
  665. DLog(@"Updating bytesExpected to %lld", newBytesExpected);
  666. self.bytesExpected = newBytesExpected;
  667. [self updateProgress];
  668. }
  669. - (void)updateProgress
  670. {
  671. if (self.direction == CDV_TRANSFER_DOWNLOAD) {
  672. BOOL lengthComputable = (self.bytesExpected != NSURLResponseUnknownLength);
  673. // If the response is GZipped, and we have an outstanding HEAD request to get
  674. // the length, then hold off on sending progress events.
  675. if (!lengthComputable && (self.entityLengthRequest != nil)) {
  676. return;
  677. }
  678. NSMutableDictionary* downloadProgress = [NSMutableDictionary dictionaryWithCapacity:3];
  679. [downloadProgress setObject:[NSNumber numberWithBool:lengthComputable] forKey:@"lengthComputable"];
  680. [downloadProgress setObject:[NSNumber numberWithLongLong:self.bytesTransfered] forKey:@"loaded"];
  681. [downloadProgress setObject:[NSNumber numberWithLongLong:self.bytesExpected] forKey:@"total"];
  682. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:downloadProgress];
  683. [result setKeepCallbackAsBool:true];
  684. [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
  685. }
  686. }
  687. - (void)connection:(NSURLConnection*)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
  688. {
  689. if (self.direction == CDV_TRANSFER_UPLOAD) {
  690. NSMutableDictionary* uploadProgress = [NSMutableDictionary dictionaryWithCapacity:3];
  691. [uploadProgress setObject:[NSNumber numberWithBool:true] forKey:@"lengthComputable"];
  692. [uploadProgress setObject:[NSNumber numberWithLongLong:totalBytesWritten] forKey:@"loaded"];
  693. [uploadProgress setObject:[NSNumber numberWithLongLong:totalBytesExpectedToWrite] forKey:@"total"];
  694. CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:uploadProgress];
  695. [result setKeepCallbackAsBool:true];
  696. [self.command.commandDelegate sendPluginResult:result callbackId:callbackId];
  697. }
  698. self.bytesTransfered = totalBytesWritten;
  699. }
  700. // for self signed certificates
  701. - (void)connection:(NSURLConnection*)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge
  702. {
  703. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  704. if (self.trustAllHosts) {
  705. NSURLCredential* credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  706. [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
  707. }
  708. [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
  709. } else {
  710. [challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
  711. }
  712. }
  713. - (id)init
  714. {
  715. if ((self = [super init])) {
  716. self.responseData = [NSMutableData data];
  717. self.targetFileHandle = nil;
  718. }
  719. return self;
  720. }
  721. @end