Skip to content

Commit

Permalink
Use NSURLSession to download files on iOS and update error returned o…
Browse files Browse the repository at this point in the history
…n Android
  • Loading branch information
jrouault committed May 19, 2016
1 parent 42a741f commit 84e121c
Show file tree
Hide file tree
Showing 5 changed files with 227 additions and 178 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import java.io.*;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import java.util.zip.GZIPInputStream;
Expand All @@ -39,6 +40,8 @@

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
Expand All @@ -55,6 +58,16 @@ public class WizAssetsPlugin extends CordovaPlugin {
private static final String DELETE_FILE_ACTION = "deleteFile";
private static final String DELETE_FILES_ACTION = "deleteFiles";

private static final int NO_ERROR = 0;
private static final int ARGS_MISSING_ERROR = 1;
private static final int INVALID_URL_ERROR = 2;
private static final int CONNECTIVITY_ERROR = 3;
private static final int HTTP_REQUEST_ERROR = 4;
private static final int HTTP_REQUEST_CONTENT_ERROR = 5;
private static final int DIRECTORY_CREATION_ERROR = 6;
private static final int FILE_CREATION_ERROR = 7;
private static final int JSON_CREATION_ERROR = 8;

private String pathToStorage;

@Override
Expand Down Expand Up @@ -300,7 +313,7 @@ protected void onPostExecute(Integer result) {
}
}

private class AsyncDownload extends AsyncTask<File, String , String> {
private class AsyncDownload extends AsyncTask<File, Void, Void> {

private String url;
private String uri;
Expand All @@ -317,80 +330,147 @@ public AsyncDownload(String url, String uri, String filePath, CallbackContext ca
}

@Override
protected String doInBackground(File... params) {
File file = new File(this.filePath);

// Run async download task
File dir = file.getParentFile();
if (dir != null && !(dir.mkdirs() || dir.isDirectory())) {
Log.e("WizAssetsPlugin", "Error : subdirectory " + dir.getPath() + " could not be created");
this.callbackContext.error("subdirectoryCreationError");
return null;
}
protected Void doInBackground(File... params) {
try {
File file = new File(this.filePath);

// Run async download task
File dir = file.getParentFile();
if (dir != null && !(dir.mkdirs() || dir.isDirectory())) {
Log.e("WizAssetsPlugin", "Error : subdirectory " + dir.getPath() + " could not be created");
this.callbackContext.error(createDownloadFileError(DIRECTORY_CREATION_ERROR));
return null;
}

Log.d(TAG, "[Downloading] " + file.getAbsolutePath());
Log.d(TAG, "[Downloading] " + file.getAbsolutePath());

try {
URL url = new URL(this.url);
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpGet httpRequest;
try {
URL url = new URL(this.url);
httpRequest = new HttpGet(url.toURI());

// Credential check
String credentials = url.getUserInfo();
if (credentials != null) {
// Add Basic Authentication header
httpRequest.setHeader("Authorization", "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP));
}
} catch (MalformedURLException e) {
this.callbackContext.error(createDownloadFileError(INVALID_URL_ERROR));
return null;
} catch (URISyntaxException e) {
this.callbackContext.error(createDownloadFileError(INVALID_URL_ERROR));
return null;
}

HttpResponse response;
HttpClient httpclient = new DefaultHttpClient();

// Credential check
String credentials = url.getUserInfo();
if (credentials != null) {
// Add Basic Authentication header
httpRequest.setHeader("Authorization", "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP));
try {
response = httpclient.execute(httpRequest);
if (response == null) {
this.callbackContext.error(createDownloadFileError(CONNECTIVITY_ERROR));
return null;
}
StatusLine statusLine = response.getStatusLine();
if (statusLine == null) {
this.callbackContext.error(createDownloadFileError(HTTP_REQUEST_ERROR, "No status available"));
return null;
}
int statusCode = statusLine.getStatusCode();
if (statusCode < 200 || statusCode > 299) {
this.callbackContext.error(createDownloadFileError(HTTP_REQUEST_ERROR, statusCode));
return null;
}
} catch (ClientProtocolException e) {
this.callbackContext.error(createDownloadFileError(CONNECTIVITY_ERROR));
return null;
} catch (IOException e) {
this.callbackContext.error(createDownloadFileError(CONNECTIVITY_ERROR));
return null;
}

HttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();

InputStream is;

Header contentHeader = entity.getContentEncoding();
if (contentHeader != null) {
if (contentHeader.getValue().contains("gzip")) {
Log.d(TAG, "GGGGGGGGGZIIIIIPPPPPED!");
try {
String contentHeaderValue = contentHeader != null ? contentHeader.getValue() : null;
if (contentHeaderValue != null && contentHeaderValue.contains("gzip")) {
is = new GZIPInputStream(entity.getContent());
} else {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
is = bufHttpEntity.getContent();
}
} else {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
is = bufHttpEntity.getContent();
if (is == null) {
this.callbackContext.error(createDownloadFileError(HTTP_REQUEST_CONTENT_ERROR));
return null;
}
} catch (IOException e) {
this.callbackContext.error(createDownloadFileError(HTTP_REQUEST_CONTENT_ERROR));
return null;
}

byte[] buffer = new byte[1024];

int len1 = 0;

FileOutputStream fos = new FileOutputStream(file);
FileOutputStream fos;
try {
fos = new FileOutputStream(file);

while ((len1 = is.read(buffer)) > 0 ) {
fos.write(buffer,0, len1);
}
while ((len1 = is.read(buffer)) > 0 ) {
fos.write(buffer, 0, len1);
}

fos.close();
is.close();
fos.close();
is.close();
} catch (FileNotFoundException e) {
this.callbackContext.error(createDownloadFileError(FILE_CREATION_ERROR));
return null;
} catch (IOException e) {
this.callbackContext.error(createDownloadFileError(FILE_CREATION_ERROR));
return null;
}

// Tell Asset Manager to register this download to asset database
String fileAbsolutePath = file.getAbsolutePath();
Log.d(TAG, "[Downloaded ] " + fileAbsolutePath);
wizAssetManager.downloadedAsset(this.uri, fileAbsolutePath);

this.callbackContext.success("file://" + fileAbsolutePath);
} catch (MalformedURLException e) {
Log.e("WizAssetsPlugin", "Bad url : ", e);
this.callbackContext.error("notFoundError");
} catch (Exception e) {
Log.e("WizAssetsPlugin", "Error : " + e);
e.printStackTrace();
this.callbackContext.error("unknownError");
} catch (JSONException e) {
this.callbackContext.error(JSON_CREATION_ERROR);
return null;
}

return null;
}
}
}

JSONObject createDownloadFileError(int code) throws JSONException {
return createDownloadFileError(code, -1, null);
}

JSONObject createDownloadFileError(int code, int status) throws JSONException {
return createDownloadFileError(code, status, null);
}

JSONObject createDownloadFileError(int code, String message) throws JSONException {
return createDownloadFileError(code, -1, message);
}

JSONObject createDownloadFileError(int code, int status, String message) throws JSONException {
JSONObject errorObject = new JSONObject();
errorObject.put("code", code);
if (status != -1) {
errorObject.put("status", status);
}
if (message != null) {
errorObject.put("message", message);
} else {
errorObject.put("message", "No description");
}
return errorObject;
}
}
2 changes: 1 addition & 1 deletion platforms/ios/HelloCordova.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
308D05391370CCF300D202BF /* [email protected] in Resources */ = {isa = PBXBuildFile; fileRef = 308D05301370CCF300D202BF /* [email protected] */; };
30A0434814DC770100060A13 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 30A0434314DC770100060A13 /* Localizable.strings */; };
30FC414916E50CA1004E6F35 /* [email protected] in Resources */ = {isa = PBXBuildFile; fileRef = 30FC414816E50CA1004E6F35 /* [email protected] */; };
419DE3071A1D838F005428C9 /* WizAssetsPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = 419DE3051A1D838F005428C9 /* WizAssetsPlugin.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; };
419DE3071A1D838F005428C9 /* WizAssetsPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = 419DE3051A1D838F005428C9 /* WizAssetsPlugin.m */; };
5B1594DD16A7569C00FEF299 /* AssetsLibrary.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5B1594DC16A7569C00FEF299 /* AssetsLibrary.framework */; };
7E7966DE1810823500FA85AD /* icon-40.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D41810823500FA85AD /* icon-40.png */; };
7E7966DF1810823500FA85AD /* [email protected] in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966D51810823500FA85AD /* [email protected] */; };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,22 @@
#import <UIKit/UIKit.h>
#import <Cordova/CDVPlugin.h>

enum CDVWizAssetsError {
NO_ERROR = 0,
ARGS_MISSING_ERROR = 1,
INVALID_URL_ERROR = 2,
CONNECTIVITY_ERROR = 3,
HTTP_REQUEST_ERROR = 4,
HTTP_REQUEST_CONTENT_ERROR = 5,
DIRECTORY_CREATION_ERROR = 6,
FILE_CREATION_ERROR = 7,
JSON_CREATION_ERROR = 8
};
typedef int CDVWizAssetsError;

@interface WizAssetsPlugin : CDVPlugin <UIWebViewDelegate> {
NSString *_cachePath;
NSURLSession *_session;
}

- (void)pluginInitialize;
Expand All @@ -25,5 +39,6 @@
- (void)deleteFiles:(CDVInvokedUrlCommand *)command;

@property (nonatomic, retain) NSString *cachePath;
@property (nonatomic, retain) NSURLSession *session;

@end
Loading

0 comments on commit 84e121c

Please sign in to comment.