Skip to content

Commit

Permalink
added download capability for basic authentication urls
Browse files Browse the repository at this point in the history
  • Loading branch information
aogilvie committed Aug 21, 2013
1 parent 3fbfd47 commit a81b90e
Show file tree
Hide file tree
Showing 2 changed files with 292 additions and 314 deletions.
303 changes: 146 additions & 157 deletions android/jp/wizcorp/phonegap/plugin/WizAssets/WizAssetsPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@
import java.net.URL;
import java.util.zip.GZIPInputStream;

import android.net.Uri;
import android.os.AsyncTask;
import android.util.Base64;
import org.apache.cordova.api.PluginResult;
import org.apache.http.Header;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Expand All @@ -40,138 +43,138 @@

public class WizAssetsPlugin extends CordovaPlugin {

private String TAG = "WizAssetsPlugin";
private WizAssetManager wizAssetMan = null;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (wizAssetMan == null) {
wizAssetMan = new WizAssetManager(cordova.getActivity().getApplicationContext());
}
if ("downloadFile".equals(action)) {
Log.d(TAG, "[downloadFile] *********** "+args.toString() );
try {
// Split by "/"
String[] splitURL = args.getString(1).split("/");
// Last element is name
String fileName = splitURL[splitURL.length-1];

// Build directory
Resources appR = cordova.getActivity().getApplicationContext().getResources();
// Dir name includes game/application name as folder root.. ie. "cordovaExample"
CharSequence txt = appR.getText(appR.getIdentifier("app_name", "string", cordova.getActivity().getApplicationContext().getPackageName()))+"/";

String dirName = ""+txt;
private String TAG = "WizAssetsPlugin";
private WizAssetManager wizAssetMan = null;

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

if (wizAssetMan == null) {
wizAssetMan = new WizAssetManager(cordova.getActivity().getApplicationContext());
}

if ("downloadFile".equals(action)) {
Log.d(TAG, "[downloadFile] *********** "+args.toString() );
try {
// Split by "/"
String[] splitURL = args.getString(1).split("/");

// Last element is name
String fileName = splitURL[splitURL.length-1];

// Build directory
Resources appR = cordova.getActivity().getApplicationContext().getResources();
// Dir name includes game/application name as folder root.. ie. "cordovaExample"
CharSequence txt = appR.getText(appR.getIdentifier("app_name", "string", cordova.getActivity().getApplicationContext().getPackageName()))+"/";

String dirName = ""+txt;
dirName = "";
for (int i=0; i<splitURL.length-1; i++) {
dirName = dirName+splitURL[i]+"/";
}
for (int i=0; i<splitURL.length-1; i++) {
dirName = dirName+splitURL[i]+"/";
}
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
downloadUrl(args.getString(0), dirName, fileName, "true", callbackContext);
downloadUrl(args.getString(0), dirName, fileName, "true", callbackContext);
return true;
} catch (JSONException e) {
callbackContext.error("Param errrors");
return true;
}

} else if ("getFileURI".equals(action)) {
Log.d(TAG, "[getFileURI] search full file path for: "+ args.toString() );
String asset = null;
String relpath = null;
// Get application / game name to prefix relpath
Resources appR = cordova.getActivity().getApplicationContext().getResources();
// Dir name includes game/application name as folder root.. ie. "cordovaExample"
CharSequence txt = appR.getText(appR.getIdentifier("app_name", "string", cordova.getActivity().getApplicationContext().getPackageName()))+"/";

String dirName = ""+txt;
try {
relpath = args.getString(0);
asset = wizAssetMan.getFile(dirName + relpath);
} catch (JSONException e) {
Log.d(TAG, "[getFileURI] error: " + e.toString());
callbackContext.error(e.toString() );
}
if (asset == "" || asset == null || asset.contains("NotFoundError")) {
callbackContext.error("NotFoundError");
} else {
Log.d(TAG, "[getFileURI] Returning full path: " + asset);
callbackContext.success(asset);
}
return true;

} else if ("getFileURIs".equals(action)) {
// Return all assets as asset map object
Log.d(TAG, "[getFileURIs] *********** >>>>>>> ");
JSONObject assetObject = wizAssetMan.getAllAssets();
Log.d(TAG, "[getFileURIs] RETURN *********** >>>>>>> " + assetObject.toString());
callbackContext.success(assetObject);
return true;
} else if ("deleteFiles".equals(action)) {
// Delete all files from array given
Log.d(TAG, "[deleteFiles] *********** ");
try {
for (int i = 0; i<args.length(); i++) {
String filepath = args.getString(i);
// If file is in bundle we cannot delete so ignore
if (!filepath.contains("www/assets")) {
// Delete the file, we do not care success or fail
// If you want to check file is deleted, delete() returns boolean
// so you can implement a check after delete() if necessary
File file = new File(filepath);
file.delete();
// Delete from database
wizAssetMan.deleteFile(filepath);
}
}
} catch (JSONException e) {
Log.d(TAG, "failed to parse download strings *********** "+e);
}
// We do not care about success or fail...
callbackContext.success();
return true;
} else if (action.equals("deleteFile")) {
Log.d(TAG, "[deleteFile] *********** " + args.getString(0));
String filepath = args.getString(0);
// If file is in bundle we cannot delete so ignore
if (!filepath.contains("www/assets")) {
// Delete the file, we do not care success or fail
// If you want to check file is deleted, delete() returns boolean
// so you can implement a check after delete() if necessary
File file = new File(filepath);
file.delete();
// Delete from database
wizAssetMan.deleteFile(filepath);
}
// Callback success for any outcome.
callbackContext.success();
return true;
}

return false; // Returning false results in a "MethodNotFound" error.
}

private void downloadUrl(String fileUrl, String dirName, String fileName, String overwrite, CallbackContext callbackContext){
// Download files to sdcard, or phone if sdcard not exists
Log.d(TAG, "file URL: " + fileUrl);
new asyncDownload(fileUrl, dirName, fileName, overwrite, callbackContext).execute();
}
} catch (JSONException e) {
callbackContext.error("Param errrors");
return true;
}

} else if ("getFileURI".equals(action)) {

Log.d(TAG, "[getFileURI] search full file path for: "+ args.toString() );
String asset = null;
String relpath = null;

// Get application / game name to prefix relpath
Resources appR = cordova.getActivity().getApplicationContext().getResources();
// Dir name includes game/application name as folder root.. ie. "cordovaExample"
CharSequence txt = appR.getText(appR.getIdentifier("app_name", "string", cordova.getActivity().getApplicationContext().getPackageName()))+"/";

String dirName = ""+txt;
try {
relpath = args.getString(0);
asset = wizAssetMan.getFile(dirName + relpath);
} catch (JSONException e) {
Log.d(TAG, "[getFileURI] error: " + e.toString());
callbackContext.error(e.toString() );
}

if (asset == "" || asset == null || asset.contains("NotFoundError")) {
callbackContext.error("NotFoundError");
} else {
Log.d(TAG, "[getFileURI] Returning full path: " + asset);
callbackContext.success(asset);
}
return true;

} else if ("getFileURIs".equals(action)) {

// Return all assets as asset map object
Log.d(TAG, "[getFileURIs] *********** >>>>>>> ");
JSONObject assetObject = wizAssetMan.getAllAssets();
Log.d(TAG, "[getFileURIs] RETURN *********** >>>>>>> " + assetObject.toString());
callbackContext.success(assetObject);
return true;

} else if ("deleteFiles".equals(action)) {

// Delete all files from array given
Log.d(TAG, "[deleteFiles] *********** ");
try {
for (int i = 0; i<args.length(); i++) {

String filepath = args.getString(i);
// If file is in bundle we cannot delete so ignore
if (!filepath.contains("www/assets")) {
// Delete the file, we do not care success or fail
// If you want to check file is deleted, delete() returns boolean
// so you can implement a check after delete() if necessary
File file = new File(filepath);
file.delete();
// Delete from database
wizAssetMan.deleteFile(filepath);
}
}
} catch (JSONException e) {
Log.d(TAG, "failed to parse download strings *********** "+e);
}

// We do not care about success or fail...
callbackContext.success();
return true;

} else if (action.equals("deleteFile")) {

Log.d(TAG, "[deleteFile] *********** " + args.getString(0));
String filepath = args.getString(0);

// If file is in bundle we cannot delete so ignore
if (!filepath.contains("www/assets")) {
// Delete the file, we do not care success or fail
// If you want to check file is deleted, delete() returns boolean
// so you can implement a check after delete() if necessary
File file = new File(filepath);
file.delete();
// Delete from database
wizAssetMan.deleteFile(filepath);
}

// Callback success for any outcome.
callbackContext.success();
return true;
}

return false; // Returning false results in a "MethodNotFound" error.
}

private void downloadUrl(String fileUrl, String dirName, String fileName, String overwrite, CallbackContext callbackContext){
// Download files to sdcard, or phone if sdcard not exists
Log.d(TAG, "file URL: " + fileUrl);
new asyncDownload(fileUrl, dirName, fileName, overwrite, callbackContext).execute();
}

private class asyncDownload extends AsyncTask<File, String , String> {

Expand Down Expand Up @@ -218,15 +221,28 @@ protected String doInBackground(File... params) {
httpRequest = new HttpGet(url.toURI());

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));
}

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

InputStream is;

Header contentHeader = entity.getContentEncoding();
if (contentHeader.getValue().contains("gzip")) {
Log.d(TAG, "GGGGGGGGGZIIIIIPPPPPED!");
is = new GZIPInputStream(entity.getContent());
if (contentHeader != null) {
if (contentHeader.getValue().contains("gzip")) {
Log.d(TAG, "GGGGGGGGGZIIIIIPPPPPED!");
is = new GZIPInputStream(entity.getContent());
} else {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
is = bufHttpEntity.getContent();
}
} else {
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
is = bufHttpEntity.getContent();
Expand Down Expand Up @@ -263,32 +279,5 @@ protected String doInBackground(File... params) {
return null;
}
}
/*
private String decompress(String zipText) throws IOException {
byte[] compressed = Base64.decode(zipText);
if (compressed.length > 4)
{
GZIPInputStream gzipInputStream = new GZIPInputStream(
new ByteArrayInputStream(compressed, 4,
compressed.length - 4));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int value = 0; value != -1;) {
value = gzipInputStream.read();
if (value != -1) {
baos.write(value);
}
}
gzipInputStream.close();
baos.close();
String sReturn = new String(baos.toByteArray(), "UTF-8");
return sReturn;
}
else
{
return "";
}
}
*/
}

Loading

0 comments on commit a81b90e

Please sign in to comment.