incubator-callback-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From shaz...@apache.org
Subject ios commit: Change FileTransfer download to not use a blocking call
Date Fri, 06 Apr 2012 22:14:56 GMT
Updated Branches:
  refs/heads/master 39c03e294 -> 2bf695b0b


Change FileTransfer download to not use a blocking call


Project: http://git-wip-us.apache.org/repos/asf/incubator-cordova-ios/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-cordova-ios/commit/2bf695b0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-cordova-ios/tree/2bf695b0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-cordova-ios/diff/2bf695b0

Branch: refs/heads/master
Commit: 2bf695b0bc7ec47e2ec1f40842035106811e35f2
Parents: 39c03e2
Author: Marcus Wu <mwu@digitaltorque.com>
Authored: Fri Apr 6 10:25:16 2012 -0400
Committer: Shazron Abdullah <shazron@apache.org>
Committed: Fri Apr 6 15:14:42 2012 -0700

----------------------------------------------------------------------
 CordovaLib/Classes/CDVFileTransfer.h |   14 ++-
 CordovaLib/Classes/CDVFileTransfer.m |  164 ++++++++++++++++------------
 2 files changed, 104 insertions(+), 74 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-cordova-ios/blob/2bf695b0/CordovaLib/Classes/CDVFileTransfer.h
----------------------------------------------------------------------
diff --git a/CordovaLib/Classes/CDVFileTransfer.h b/CordovaLib/Classes/CDVFileTransfer.h
index 8bcb46a..38fe3b2 100644
--- a/CordovaLib/Classes/CDVFileTransfer.h
+++ b/CordovaLib/Classes/CDVFileTransfer.h
@@ -28,6 +28,12 @@ enum CDVFileTransferError {
 };
 typedef int CDVFileTransferError;
 
+enum CDVFileTransferDirection {
+	CDV_TRANSFER_UPLOAD = 1,
+    CDV_TRANSFER_DOWNLOAD = 2,
+};
+typedef int CDVFileTransferDirection;
+
 @interface CDVFileTransfer : CDVPlugin {
     
 }
@@ -35,27 +41,27 @@ typedef int CDVFileTransferError;
 - (void) upload:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
 - (void) download:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
 
--(void) downloadFile:(NSMutableArray*)arguments;
--(void) downloadSuccess:(NSMutableArray*)arguments; 
--(void) downloadFail:(NSMutableArray*)arguments; 
-
 -(NSMutableDictionary*) createFileTransferError:(NSString*)code AndSource:(NSString*)source
AndTarget:(NSString*)target;
 @end
 
 
 @interface CDVFileTransferDelegate : NSObject {
 	CDVFileTransfer* command;
+    CDVFileTransferDirection direction;
 	NSString* callbackId;
 	NSString* source;
 	NSString* target;
     NSInteger bytesWritten;
+    int responseCode;
 }
 
 @property (nonatomic, retain) NSMutableData* responseData;
 @property (nonatomic, retain) CDVFileTransfer* command;
+@property (nonatomic, assign) CDVFileTransferDirection direction;
 @property (nonatomic, retain) NSString* callbackId;
 @property (nonatomic, retain) NSString* source;
 @property (nonatomic, retain) NSString* target;
+@property (nonatomic, assign) int responseCode;
 @property NSInteger bytesWritten;
 
 

http://git-wip-us.apache.org/repos/asf/incubator-cordova-ios/blob/2bf695b0/CordovaLib/Classes/CDVFileTransfer.m
----------------------------------------------------------------------
diff --git a/CordovaLib/Classes/CDVFileTransfer.m b/CordovaLib/Classes/CDVFileTransfer.m
index f367657..01a77cf 100644
--- a/CordovaLib/Classes/CDVFileTransfer.m
+++ b/CordovaLib/Classes/CDVFileTransfer.m
@@ -163,76 +163,47 @@
 
 - (void) download:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
     DLog(@"File Transfer downloading file...");
-    
-    [self performSelectorInBackground:@selector(downloadFile:) withObject:arguments];
-}
-
--(void) downloadFile:(NSMutableArray*)arguments {
     NSString * callbackId = [arguments objectAtIndex:0];
     NSString * sourceUrl = [arguments objectAtIndex:1];
     NSString * filePath = [arguments objectAtIndex:2];
+    CDVPluginResult *result = nil;
+    CDVFileTransferError errorCode = 0;
+
+    NSURL* file;
     
-    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-    NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:sourceUrl] ];
-    NSArray * results = nil;
+    if ([filePath hasPrefix:@"/"]) {
+        file = [NSURL fileURLWithPath:filePath];
+    } else {
+        file = [NSURL URLWithString:filePath];
+    }
     
-    DLog(@"Write file %@", filePath);
-    NSError *error=[[[NSError alloc]init] autorelease];
+    NSURL *url = [NSURL URLWithString:sourceUrl];
     
-    @try {
-        NSString * parentPath = [ filePath stringByDeletingLastPathComponent ];
-        
-        // check if the path exists => create directories if needed
-        if(![[NSFileManager defaultManager] fileExistsAtPath:parentPath ]) [[NSFileManager
defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil
error:nil];
-        
-    	BOOL response = [data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error];
-        
-        if ( response == NO ) {
-        	// send our results back to the main thread
-            results = [NSArray arrayWithObjects: callbackId, [NSString stringWithFormat:@"%d",
INVALID_URL_ERR], sourceUrl, filePath, nil];
-        	[self performSelectorOnMainThread:@selector(downloadFail:) withObject:results waitUntilDone:YES];
-    	} else {
-        	// jump back to main thread
-            results = [NSArray arrayWithObjects: callbackId, filePath, nil];
-        	[self performSelectorOnMainThread:@selector(downloadSuccess:) withObject:results
waitUntilDone:YES];
-    	}
-    }
-    @catch (id exception) {
-        // jump back to main thread
-        results = [NSArray arrayWithObjects: callbackId, [NSString stringWithFormat:@"%d",
FILE_NOT_FOUND_ERR], sourceUrl, filePath, nil];
-        [self performSelectorOnMainThread:@selector(downloadFail:) withObject:results waitUntilDone:YES];
+    if (!url) {
+        errorCode = INVALID_URL_ERR;
+        NSLog(@"File Transfer Error: Invalid server URL");
+    } else if(![file isFileURL]) {
+        errorCode = FILE_NOT_FOUND_ERR;
+        NSLog(@"File Transfer Error: Invalid file path or URL");
     }
     
-    [pool drain];
-}
-
--(void) downloadSuccess:(NSMutableArray *)arguments 
-{
-    NSString * callbackId = [arguments objectAtIndex:0];
-    NSString * filePath = [arguments objectAtIndex:1];
-
-    BOOL bDirRequest = NO;
-
-    DLog(@"File Transfer Download success");
-    
-    CDVFile * file = [[[CDVFile alloc] init] autorelease];
+    if(errorCode > 0) {
+        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:
[self createFileTransferError:[NSString stringWithFormat:@"%d", errorCode] AndSource:sourceUrl
AndTarget:filePath]];
+        
+        [self writeJavascript:[result toErrorCallbackString:callbackId]];
+        return;
+    }
     
-    CDVPluginResult* result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsDictionary:
[file getDirectoryEntry: filePath isDirectory: bDirRequest] cast: @"window.localFileSystem._castEntry"];
-    [self writeJavascript: [result toSuccessCallbackString:callbackId]];
-}
-
--(void) downloadFail:(NSMutableArray *)arguments 
-{
-    NSString * callbackId = [arguments objectAtIndex:0];
-    NSString * code = [arguments objectAtIndex:1];
-    NSString * source = [arguments objectAtIndex:2];
-    NSString * target = [arguments objectAtIndex:3];
+    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
 
-    NSLog(@"File Transfer Error: %@", source);
-    
-    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK
messageAsDictionary: [self createFileTransferError:code AndSource:source AndTarget:target]];
-                                    
-    [self writeJavascript: [pluginResult toErrorCallbackString:callbackId]];
+    CDVFileTransferDelegate* delegate = [[[CDVFileTransferDelegate alloc] init] autorelease];
+	delegate.command = self;
+    delegate.direction = CDV_TRANSFER_DOWNLOAD;
+    delegate.callbackId = callbackId;
+    delegate.source = sourceUrl;
+    delegate.target = filePath;
+	
+	[NSURLConnection connectionWithRequest:req delegate:delegate];
 }
 
 -(NSMutableDictionary*) createFileTransferError:(NSString*)code AndSource:(NSString*)source
AndTarget:(NSString*)target
@@ -250,22 +221,75 @@
 
 @implementation CDVFileTransferDelegate
 
-@synthesize callbackId, source, target, responseData, command, bytesWritten;
+@synthesize callbackId, source, target, responseData, command, bytesWritten, direction, responseCode;
 
 
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection 
 {
-    NSString* response = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
-    // create dictionary to return FileUploadResult object
-    NSMutableDictionary* uploadResult = [NSMutableDictionary dictionaryWithCapacity:3];
-    if (response != nil) {
-        [uploadResult setObject: [response stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
forKey: @"response"];
+    NSString* uploadResponse = nil;
+    BOOL downloadResponse;
+    NSMutableDictionary* uploadResult;
+    CDVPluginResult* result;
+    NSError *error;
+    NSString *parentPath;
+    BOOL bDirRequest = NO;
+    CDVFile * file;
+    
+    if(direction == CDV_TRANSFER_UPLOAD)
+    {
+        // create dictionary to return FileUploadResult object
+        uploadResponse = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
+        uploadResult = [NSMutableDictionary dictionaryWithCapacity:3];
+        if (uploadResponse != nil) {
+            [uploadResult setObject: [uploadResponse stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
forKey: @"response"];
+        }
+        [uploadResult setObject:[NSNumber numberWithInt: self.bytesWritten] forKey:@"bytesSent"];
+        [uploadResult setObject:[NSNull null] forKey: @"responseCode"];
+        result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsDictionary:
uploadResult cast: @"navigator.fileTransfer._castUploadResult"];
+    }
+    if(direction == CDV_TRANSFER_DOWNLOAD)
+    {
+        DLog(@"Write file %@", target);
+        error=[[[NSError alloc]init] autorelease];
+        NSLog(@"File Transfer Finished with response code %d", responseCode);
+
+        if(responseCode >= 200 && responseCode < 300)
+        {
+            @try {
+                parentPath = [ self.target stringByDeletingLastPathComponent ];
+                
+                // check if the path exists => create directories if needed
+                if(![[NSFileManager defaultManager] fileExistsAtPath:parentPath ]) [[NSFileManager
defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil
error:nil];
+                
+                downloadResponse = [self.responseData writeToFile:self.target options:NSDataWritingFileProtectionNone
error:&error];
+                
+                if ( downloadResponse == NO ) {
+                    // send our results back
+                    result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:
[command createFileTransferError:[NSString stringWithFormat:@"%d", INVALID_URL_ERR] AndSource:source
AndTarget:target]];
+                } else {
+                    DLog(@"File Transfer Download success");
+                    
+                    file = [[[CDVFile alloc] init] autorelease];
+                    
+                    result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsDictionary:
[file getDirectoryEntry: target isDirectory: bDirRequest] cast: @"window.localFileSystem._castEntry"];
+                }
+            }
+            @catch (id exception) {
+                // jump back to main thread
+                result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:
[command createFileTransferError:[NSString stringWithFormat:@"%d", FILE_NOT_FOUND_ERR] AndSource:source
AndTarget:target]];
+            }
+        } else {
+            result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:
[command createFileTransferError:[NSString stringWithFormat:@"%d", CONNECTION_ERR] AndSource:source
AndTarget:target]];
+        }
     }
-    [uploadResult setObject:[NSNumber numberWithInt: self.bytesWritten] forKey:@"bytesSent"];
-    [uploadResult setObject:[NSNull null] forKey: @"responseCode"];
-    CDVPluginResult* result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsDictionary:
uploadResult cast: @"navigator.fileTransfer._castUploadResult"];
     [command writeJavascript:[result toSuccessCallbackString: callbackId]];
-    [response release];
+    [uploadResponse release];
+}
+
+- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
+{
+    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
+    responseCode = [response statusCode];
 }
 
 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 


Mime
View raw message