FTP

FTP

none

var EditText = Packages.android.widget.EditText;
var Intent = Packages.android.content.Intent;
var Uri = Packages.android.net.Uri
var MimeTypeMap = Packages.android.webkit.MimeTypeMap
var KeyEvent = Packages.android.view.KeyEvent;
var MotionEvent = Packages.android.view.MotionEvent;
var FileInputStream = Packages.java.io.FileInputStream;
var FileOutputStream = Packages.java.io.FileOutputStream;
var Log = Packages.android.util.Log;
var AbsLayoutParams = Packages.android.widget.AbsListView.LayoutParams;
var LayoutParams = Packages.android.widget.LinearLayout.LayoutParams;
var LinearLayout = Packages.android.widget.LinearLayout;
var TextView = Packages.android.widget.TextView;
var Gravity = Packages.android.view.Gravity;
var Method = Packages.java.lang.reflect.Method;
var Set = Packages.java.util.Set;
var Mode = Packages.android.graphics.PorterDuff.Mode;
var Color = Packages.android.graphics.Color;
var SimpleDateFormat = Packages.java.text.SimpleDateFormat
var FTP = Packages.org.apache.commons.net.ftp.FTP;
var FTPClient = Packages.org.apache.commons.net.ftp.FTPClient;
var FTPFile = Packages.org.apache.commons.net.ftp.FTPFile;
var FTPReply = Packages.org.apache.commons.net.ftp.FTPReply;

var Context = android.content.Context;
var Log = android.util.Log;
var ListView = Packages.android.widget.ListView;
var ArrayAdapter = Packages.android.widget.ArrayAdapter;
var Arrays = Packages.java.util.Arrays;
var Menu = Packages.android.view.Menu;

var Intent = Packages.android.content.Intent;
var Context = Packages.android.content.Context;
var Uri = Packages.android.net.Uri;
var Cursor = Packages.android.database.Cursor;
var MediaStore = Packages.android.provider.MediaStore;
var Typeface = Packages.android.graphics.Typeface;
var CustomAdapter = com.completeapps.jascript.adapters.CustomAdapter;
var File = Packages.java.io.File;
var AlertDialog = Packages.android.app.AlertDialog;
var host = "localhost"
var username = "titus"
var pass = "passpass";
var port = 51611;
var p = "/";
var n ="";
var current = "/";
var currentLocalPath = pkg.Globals.externalPath;
var accounts = [
{
title:"mycode",hostname:"localhost",username:"titus",password:1234,portnum:11111
},
{
title:"mycode2",hostname:"mycode.coolpage.biz",username:"mycode.coolpage.biz",password:"34titus78",portnum:21
}
];
var accounts = [];

var adapter;
var ftpList = {
imageArray:[],
fileArray:[],
detailsArray:[],
sizeArray:[]
};
var localList = {
imageArray:[],
fileArray:[],
detailsArray:[]
};
var inHome = true;
var inFtp = true;
var actionBarColor = Color.parseColor("#22567c");
var notInFtpColor = Color.parseColor("#ebebeb");


var typeface = Typeface.createFromAsset(ctx.getResources().getAssets(),"fonts/icofont.ttf");

var fileTypes = ["Binary","Text"];
var file_types = [FTP.BINARY_FILE_TYPE,FTP.ASCII_FILE_TYPE];
var charsets = ["US-ASCII","ISO-8859-1","UTF-8","UTF-16BE","UTF-16LE","UTF-16"];
var passiveMode = true;
var current_encoding = 2;
var current_filetype = 0;

var menuOptions = ["Back","New Account","New Directory","Upload","Passive Mode","Encoding("+charsets[current_encoding]+")","Transfer("+fileTypes[current_filetype]+")","Exit"];
var menuActions = [
function(){ ftpBack();},
function(){ addAccount();},
function() { fastMakeDir();},
function() { uploadFile();},
function() { passiveMode = passiveMode?false:true;},
function() { selectEncoding();},
function() { selectFileType();},
function() { ctx.finish();}
];


var listview;
var path = "/sdcard/ftp.json";
var filePath = new File(path);
if(! filePath.exists())saveAccounts();
var ftp;
ftp = new MyFtpClient();
function onPreCreate(){
ctx.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
function onCreate(b){
ctx.setTitle("Ftp Client");
setTaskDescription("Ftp",null,actionBarColor);
setStatusBarBackgroundColor(actionBarColor);
setActionBarBackgroundColor(actionBarColor);
lay = new LinearLayout(ctx);
lay.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1));


lst = new ListView(ctx);
lst.setBackgroundColor(Color.WHITE);
lst.setOnTouchListener(function(v,event){
if(event.getAction()===MotionEvent.ACTION_DOWN){
inFtp = true;
v.setBackgroundColor(Color.WHITE);
lst2.setBackgroundColor(notInFtpColor);
v.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,0.4));
lst2.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,0.6));
}
return false;
});
lst.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,0.4));
lst.setFastScrollEnabled( true );
adapter = new pkg.adapters.CustomListAdapter(ctx);
adapter.setOnGetView( function (position,convertView,parent)
{
var ld;
if (convertView== null )
{
ld = new LinearLayout(ctx);
ld.setTag("ld");
ld2 = new LinearLayout(ctx);
ld.setTag("ld2");
td = new TextView(ctx);
td.setTag("td");
td1 = new TextView(ctx);
td1.setTag("td1");
td2 = new TextView(ctx);
td2.setTag("td2");
ld.setLayoutParams( new AbsLayoutParams(AbsLayoutParams.FILL_PARENT,AbsLayoutParams.FILL_PARENT,10));
td.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,8));
ld2.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,2));
ld2.setOrientation(1);
ld.addView(td);
ld.addView(ld2);
td1.setTextColor(Color.parseColor("#323246"));
td1.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,1));
td2.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,1));
ld2.addView(td1);
ld2.addView(td2);
td.setGravity(Gravity.CENTER);
td.setTypeface(typeface);
td.setTextSize(32);
td.setPadding(10,20,10,20);
td1.setTextSize(16);
td1.setPadding(10,10,10,10);
td2.setTextSize(12);
td2.setPadding(10,10,10,10);
}
else
{
ld = convertView;
}
td = ld.findViewWithTag("td");
td1 = ld.findViewWithTag("td1");
td2 = ld.findViewWithTag("td2");
if (ftpList.imageArray[position]!= undefined )td.setText(String(ftpList.imageArray[position]));
else td.setText("");
if (ftpList.fileArray[position]!= undefined )td1.setText(String(ftpList.fileArray[position]));
else td1.setText("");
if (ftpList.detailsArray[position]!= undefined )td2.setText(String(ftpList.detailsArray[position]));
else td2.setText("");
return ld;
}
);
lst.setAdapter(adapter);
lst.setOnItemClickListener( function (p,v,pos,id)
{
clickListItem(pos);
return true ;
}
);
lst.setOnItemLongClickListener( function (p,v,pos,id)
{
longClickListItem(pos,true);
return true ;
}
);

lst2 = new ListView(ctx);
lst2.setOnTouchListener(function(v,event){
if(event.getAction()===MotionEvent.ACTION_DOWN){
inFtp = false;
v.setBackgroundColor(Color.WHITE);
lst.setBackgroundColor(notInFtpColor);
v.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,0.4));
lst.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,0.6));
}
return false;
});
lst2.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,0.6));
lst2.setBackgroundColor(notInFtpColor);
lst2.setFastScrollEnabled( true );
adapter2 = new pkg.adapters.CustomListAdapter(ctx);
adapter2.setOnGetView( function (position,convertView,parent)
{
var ld;
if (convertView== null )
{
ld = new LinearLayout(ctx);
ld.setTag("ld");
ld2 = new LinearLayout(ctx);
ld.setTag("ld2");
td = new TextView(ctx);
td.setTag("td");
td1 = new TextView(ctx);
td1.setTag("td1");
td2 = new TextView(ctx);
td2.setTag("td2");
ld.setLayoutParams( new AbsLayoutParams(AbsLayoutParams.FILL_PARENT,AbsLayoutParams.FILL_PARENT,10));
td.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,8));
ld2.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,2));
ld2.setOrientation(1);
ld.addView(td);
ld.addView(ld2);
td1.setTextColor(Color.parseColor("#323246"));
td1.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,1));
td2.setLayoutParams( new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT,1));
ld2.addView(td1);
ld2.addView(td2);
td.setGravity(Gravity.CENTER);
td.setTypeface(typeface);
td.setTextSize(32);
td.setPadding(10,20,10,20);
td1.setTextSize(16);
td1.setPadding(10,10,10,10);
td2.setTextSize(12);
td2.setPadding(10,10,10,10);
}
else
{
ld = convertView;
}
td = ld.findViewWithTag("td");
td1 = ld.findViewWithTag("td1");
td2 = ld.findViewWithTag("td2");
if (localList.imageArray[position]!= undefined )td.setText(String(localList.imageArray[position]));
else td.setText("");
if (localList.fileArray[position]!= undefined )td1.setText(String(localList.fileArray[position]));
else td1.setText("");
if (localList.detailsArray[position]!= undefined )td2.setText(String(localList.detailsArray[position]));
else td2.setText("");
return ld;
}
);
lst2.setAdapter(adapter2);
lst2.setOnItemClickListener( function (p,v,pos,id)
{ var file = new File(currentLocalPath+"/"+localList.fileArray[pos]);
if(file.isDirectory()){
loadFolder(String(file.getPath()));
}else{
openFile(file.getName());
}
bThread(function(){
ftp.sendNoOp();
});
//clickListItem(pos);
return true ;
}
);
lst2.setOnItemLongClickListener( function (p,v,pos,id)
{
longClickListItem(pos,false);
return true ;
}
);



lay.addView(lst);
lay.addView(lst2);

ctx.setContentView(lay);
loadAccounts();
listAccounts();
loadCurrentFolder();
}


function home(){
//var lst = read(path);
var lst = "{}";
var ftplist = JSON.parse(lst)||{};
var flist = []
for(x in ftplist){
flist.push("Acc: "+x);
}

}

function refresh(){
adapter.notifyDatasetChanged();
}


function loadFolder(path){
currentLocalPath = path;
loadCurrentFolder();
}

function loadCurrentFolder(){
localList.fileArray = [];
localList.imageArray = [];
localList.detailsArray = [];
var cn = 0;
var lst = new File(currentLocalPath).list().sort().forEach(function(item){
var file = new File(currentLocalPath+"/"+item);
if(file.isDirectory()){
localList.fileArray.splice(cn,1,item);
localList.detailsArray.splice(cn,1,formatDate(file.lastModified()));
localList.imageArray.splice(cn,1,"");
cn++;
}else{
localList.fileArray.push(item);
localList.detailsArray.push(formatSize(file.length())+" "+formatDate(file.lastModified()));
localList.imageArray.push("");
}
});
runOnUIThread(function(){
adapter2.setList(localList.fileArray,localList.imageArray,localList.detailsArray);
});
}





function init(pos){

var obj = accounts; //JSON.parse(read(path))
var host = obj[pos].hostname;
var username = obj[pos].username;
var pass = obj[pos].password;
var port = obj[pos].port;
//alert(host+"\n"+username+"\n"+pass+"\n"+port);
connect(host,username,pass,port);
//getDir(current);
}




function addAccount(){
/*
bUIThread(function(){

var name = prompt("name");
var host = prompt("host");
var user = prompt("username");
var pass = prompt("password");
var port = prompt("port");

var items = prompt("Add a FTP Account","name|host|username|password|port");
if(items){
var arr = String(items).split("|");
//alert(arr)
var name = arr[0];
var host = arr[1];
var user = arr[2];
var pass = arr[3];
var port = arr[4];
addUser(name,host,user,pass,port);
}
});
*/

multiPrompt(["Enter title","Enter host","Enter username","Enter password","Enter port"],"Add Ftp Account",["Yes","No"],function(arr,btn){
if(btn==0){
var name = arr[0];
var host = arr[1];
var user = arr[2];
var pass = arr[3];
var port = Number(arr[4]);
if(!isNaN(arr[4])){
addUser(name,host,user,pass,port);
}else{
pkg.Utils.popup(ctx,"Enter a valid port");
}
}
});


}



function addUser(name,host,user,pass,port){
//var a = (new File(path).exists())?JSON.parse(read(path)):{}
//alert(port);
var b = {
title:name,
hostname:host,
username:user,
password:pass,
port:port
}
accounts.push(b);
saveAccounts();
listAccounts();
}


function renameAccount(pos){
bUIThread(function(){
var nm = prompt("Enter name",accounts[pos].title);
if(nm){
accounts[pos].title = String(nm);
saveAccounts();
listAccounts();
}
});
}

function loadAccounts(){
var s = ctx.readFile(path);
accounts = JSON.parse(String(s));
}


function saveAccounts(){
var d = JSON.stringify(accounts);
pkg.Utils.writeFile(new File(path),d );
}



function editAccount(pos){
//bUIThread(function(){

var acc = accounts[pos];
var name = acc.title;
var host = acc.hostname;
var user = acc.username;
var pass = acc.password;
var port = acc.port;
/*
var items = prompt("Edit a FTP Account",host+"|"+user+"|"+pass+"|"+port);
if(items){
var arr = String(items).split("|");
//alert(arr)
host = arr[0];
user = arr[1];
pass = arr[2];
port = arr[3];

acc.hostname = host;
acc.username = user;
acc.password = pass;
acc.portnum = port;
listAccounts();
}
});
*/

multiPrompt(["Enter title","Enter host","Enter username","Enter password","Enter port"],"Edit Ftp Account",["Yes","No"],function(arr,btn){
if(btn==0){
var name = arr[0];
var host = arr[1];
var user = arr[2];
var pass = arr[3];
var port = Number(arr[4]);
if(!isNaN(arr[4])){
acc.title = name;
acc.hostname = host;
acc.username = user;
acc.password = pass;
acc.port = port;
saveAccounts();
listAccounts();
}else{
pkg.Utils.popup(ctx,"Enter a valid port");
}
}
},[name,host,user,pass,String(port)]);




}

function deleteAccount(pos){
bUIThread(function(){
var cf = confirm("Do you really want to delete "+accounts[pos].title);
if(cf){
accounts.splice(pos,1);
saveAccounts();
listAccounts();
}
});
}


function listAccounts(){
//var lst = read(path);
//JSON.parse(lst)||{};
var flist = [];
var dlist = [];
var ilist = [];
for(x in accounts){
flist.push(accounts[x].title);
dlist.push("Host: "+accounts[x].hostname+"\nUsername: "+accounts[x].username+" \nPassword: ****");
ilist.push("");
}
ftpList.fileArray = flist;
ftpList.imageArray = ilist;
ftpList.detailsArray = dlist;
loadList();
}

function loadList(){
runOnUIThread(function(){
adapter.setList(ftpList.fileArray,ftpList.imageArray,ftpList.detailsArray);
});
}


function clickListItem(pos){
var file = ftpList.fileArray[pos];
var img = ftpList.imageArray[pos];
if(img.slice(0,1)==""){
init(pos);
}
else{
if(img.slice(0,1)==""){
if(current=="/"){
current+= file;
}else{
current += "/"+file;
}

cnt = 0;
getDir(current);
}
else{
alert(file);
}
}

}


function longClickListItem(pos,inFTP){
if(inHome&&inFTP)
accountOptions(pos);
else
options(pos,inFTP);

}

function connect(host,username,pass,port){
runOnUIThread(function(){
pkg.Utils.showProgress(ctx,"Loading",false);
});
bTask(function(){
var status = ftp.ftpConnect(host,username,pass,port);
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
if(status){
runOnUIThread(function(){
getDir(current);
});
}
},function(){

});
}


function getDir(path){
runOnUIThread(function(){
pkg.Utils.showProgress(ctx,"Loading files...",false);
});
bThread(function(){
var list = ftp.ftpPrintFilesList(path);
list.sort(function(a,b){
return a.getName()>b.getName();
});
ftpList.fileArray = [];
ftpList.imageArray = [];
ftpList.detailsArray = [];
ftpList.sizeArray = [];
var length = list.length;
var cn = 0;
//print(props(list[0]));
for (var i = 0; i < length; i++) {
var name = list[i].getName();
var size = list[i].getSize();
var tm = list[i].getTimestamp();
var isFile = list[i].isFile();
var listing = list[i].getRawListing();

if(isFile){
ftpList.fileArray.push(name);
ftpList.imageArray.push(""); ftpList.detailsArray.push(formatSize(size)+" "+formatDate(tm.getTimeInMillis()));
ftpList.sizeArray.push(size);
}else{
ftpList.fileArray.splice(cn,1,name);
ftpList.imageArray.splice(cn,1,"");
ftpList.detailsArray.splice(cn,1,formatDate(tm.getTimeInMillis()));
ftpList.sizeArray.splice(cn,1,size);
cn++;
}
}
inHome = false;
loadList();
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
});
}



function rename(from,to){
pkg.Utils.showProgress(ctx,"Renaming...",false);
bThread(function(){
ftp.ftpRenameFile(from,to);
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
getDir(current);
});
}


function makeDir(name){
popup(name);
pkg.Utils.showProgress(ctx,"Making directory...",false);
bThread(function(){
ftp.ftpMakeDirectory(name);
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
getDir(current);
});
}

function deleteDir(name){
pkg.Utils.showProgress(ctx,"Deleting directory...",false);
bThread(function(){
ftp.ftpRemoveDirectory(name);
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
getDir(current);
});
}


function deleteFile(name){
pkg.Utils.showProgress(ctx,"Deleting file",false);
bThread(function(){
ftp.ftpRemoveFile(name);
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
getDir(current);
});
}


function download(from,to,sz){
bThread(function(){
ftp.ftpDownload(from,to,sz);
loadCurrentFolder();
});
}


function upload(from,to){
bThread(function(){
ftp.ftpUpload(from,to);
getDir(current);
});
}

function uploadDir(file){
makeDir(current+"/"+file.getName());
var fl = file.listFiles();
for (var f in fl)
{
var chld = fl[f];
if (chld.isDirectory())
{
makeDir(current+"/"+file.getName());
uploadDir(chld);

}
else
{
//upload(
}

}

}




function ftpDisconnect(){
pkg.Utils.showProgress(ctx,"Disconnecting",false);
bThread(function(){
var status = ftp.ftpDisconnect();
runOnUIThread(function(){
pkg.Utils.hideProgress();
});
});
}

function uploadFile(){
var fc = new pkg.utils.FileChooser();
fc.setTitle("Select file to upload");
fc.explore(ctx,currentLocalPath);
fc.setOnSelectionListener( function (mpath)
{
currentLocalPath = String(new File(mpath).getParent());
upload(mpath,current);
}
);
}





var cnt = 0;
function ftpBack(){
if(inFtp){
if(inHome)return false;
var path = current;
var npath = path.slice(0,path.lastIndexOf("/"));
if(npath.length==0){
cnt++;
current = npath+"/";
if(cnt == 2){
inHome = true;
ftpDisconnect();
listAccounts();
cnt = 0;
}else{
getDir(current);
}

}else{
current = npath;
getDir(current);
cnt = 0;
}
return true;
}else{
tmpLocalFile = new File(currentLocalPath).getParentFile();
if(tmpLocalFile!=null&&tmpLocalFile.exists()&&tmpLocalFile.canRead()){
currentLocalPath = tmpLocalFile.getPath();
loadCurrentFolder();
return true;
}
}
return false;
};




function options(pos,inFTP)
{
var builder = new android.app.AlertDialog.Builder(ctx)
.setCancelable(true)
.setItems(["Rename","Copy","Delete"], new android.content.DialogInterface.OnClickListener(){
onClick:function(dinterface,position)
{

switch(position){
case 0: fastRename(pos,inFTP); break;
case 1: fastCopy(pos,inFTP); break;
case 2: fastDelete(pos,inFTP); break;
default:;
}
return true;
//bTask(function(){},function(){pkg.Utils.hideProgress()});
}

});
alertbld = builder.create();
alertbld.setTitle("Options");
alertbld.show();

}





function accountOptions(pos){
var builder = new android.app.AlertDialog.Builder(ctx)
.setCancelable(true)
.setItems(["Edit","Rename","Delete"], new android.content.DialogInterface.OnClickListener(){
onClick:function(dinterface,position)
{
switch(position){
case 0: editAccount(pos); break;
case 1: renameAccount(pos); break;
case 2: deleteAccount(pos); break;
default:;
}
return true;
}

});
alertbld = builder.create();
alertbld.setTitle("Account Options");
alertbld.show();
}

function fastCopy(pos,inFTP){
if(inFTP){
var file = ftpList.fileArray[pos];
var img = ftpList.imageArray[pos];
var sz = ftpList.sizeArray[pos];
if(img.slice(0,1)!=""){
download(current+"/"+file,currentLocalPath+"/"+file,sz);
}
}else{
var file = localList.fileArray[pos];
var img = localList.imageArray[pos];
if(img.slice(0,1)!=""){
if(!inHome){
upload(currentLocalPath+"/"+file,current);
}else{
popup("Login to ftp first");
}
}
}

/*
var fc = new pkg.utils.FileChooser();
fc.setTitle("Select folder to download to");
fc.setSelectFolder(true); fc.explore(ctx,currentLocalPath);
fc.setOnSelectionListener( function (mpath)
{

}
);
*/
}



function fastRename(pos,inFTP){
var file = inFTP?ftpList.fileArray[pos]:localList.fileArray[pos];
var img = inFTP?ftpList.imageArray[pos]:localList.imageArray[pos];
var ttle = "Rename";
if(img.slice(0,1)==""){
ttle += " directory";
}else{
ttle += " file";
}
bUIThread(function(){
var txt = prompt(ttle,file);
//popup(txt);
if(txt){
if(inFTP){
var from = current +"/"+file;
var to = current+"/"+ txt;
//popup(from+"\n"+to);
rename(from,to);
}else{
new File(currentLocalPath+"/"+file).renameTo(new File(currentLocalPath+"/"+txt));
loadCurrentFolder();
}
}
});
}
function fastDelete(pos,inFTP){
var file = inFTP?ftpList.fileArray[pos]:localList.fileArray[pos];
var img = inFTP?ftpList.imageArray[pos]:localList.imageArray[pos];
bUIThread(function(){
if(confirm("Do you really want to delete "+file)){
if(inFTP){
if(img.slice(0,1)==""){
var name = current +"/"+file;
deleteDir(name);
}
else{
var name = current +"/"+file;
deleteFile(name);
}
}else{
var fpath = currentLocalPath+"/"+file;
deleteFiles(new File(fpath));
loadCurrentFolder();
}
}
});
}



function deleteFiles(file)
{
if(!file.isDirectory()){ file.delete();return; }
var fl = file.listFiles();
for (var f in fl)
{
var chld = fl[f];
if (chld.isDirectory())
{
deleteFiles(chld);
chld. delete();


}
else
{
chld. delete ();


}

}
file.delete();
}




function fastMakeDir(){
bUIThread(function(){
var name = prompt("Enter Name","");
if(name){
if(inFtp){
if(!inHome){
makeDir(current+"/"+name);
}else{
popup("Connect to ftp first");
}
}else{
new File(currentLocalPath+"/"+name).mkdir();
loadCurrentFolder();
}
}
});
}

function MyFtpClient(){

// Now, declare a public FTP client object.

var mFTPClient = null;
mFTPClient = new FTPClient();

// Method to connect to FTP server:
this.ftpConnect = function(host, username,password,port) {
try {

// connecting to the host
if(port){
mFTPClient.connect(host, port);
}else{
mFTPClient.connect(host);
}

// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {



// login using username & password
status = mFTPClient.login(username, password);
/*
* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE for
* transferring text, image, and compressed files.
*/

mFTPClient.setControlEncoding( charsets[current_encoding] );
mFTPClient.setAutodetectUTF8(true);
mFTPClient.setListHiddenFiles(true); if(passiveMode)mFTPClient.enterLocalPassiveMode();
mFTPClient.setFileType(file_types[current_filetype]);
return status;
}
} catch ( e) {
popup(e);
}

return false;
}

// Method to disconnect from FTP server:

this.ftpDisconnect = function() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch ( e) {
popup(e);
}

return false;
}

// Method to get current working directory:

this.ftpGetCurrentWorkingDirectory = function() {
try {
var workingDir = mFTPClient.printWorkingDirectory();
return workingDir;
} catch ( e) {
popup(e);
}

return null;
}

// Method to change working directory:

function ftpChangeDirectory(directory_path) {
try {
mFTPClient.changeWorkingDirectory(directory_path);
} catch (e) {
popup(e);
}

return false;
}

// Method to list all files in a directory:

this.sendNoOp = function(){
try{
mFTPClient.sendNoOp();
}catch(e){

}
}



this.ftpPrintFilesList = function(dir_path) {
try {
var ftpFiles = [];
ftpFiles = mFTPClient.listFiles(dir_path);
return ftpFiles;
} catch ( e) {
popup(e);
}
return [];
}

// Method to create new directory:

this.ftpMakeDirectory = function(new_dir_path) {
try {
var status = mFTPClient.makeDirectory(new_dir_path);
return status;
} catch (e) {
popup(e);
}

return false;
}

// Method to delete/remove a directory:

this.ftpRemoveDirectory = function(dir_path) {
try {
var status = mFTPClient.removeDirectory(dir_path);
return status;
} catch ( e) {
Log.d(TAG, "Error: could not remove directory named " + dir_path);
}

return false;
}

// Method to delete a file:

this.ftpRemoveFile= function(filePath) {
try {
var status = mFTPClient.deleteFile(filePath);
return status;
} catch (e) {
popup(e)
}

return false;
}

// Method to rename a file:

this.ftpRenameFile = function( from, to) {
try {
var status = mFTPClient.rename(from, to);
return status;
} catch (e) {
popup(e);
}

return false;
}

// Method to download a file from FTP server:

/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: path to the source file in FTP server desFilePath: path to
* the destination file to be saved in sdcard
*/
this.ftpDownload = function(srcFilePath, desFilePath,size) {
mFTPClient.setFileType(file_types[current_filetype]);
var status = false;
runOnUIThread(function(){ pkg.Utils.showProgress(ctx,"Downloading",size/1024,false);
});
try {
desFileStream = new FileOutputStream(desFilePath);
;
inputStream = mFTPClient.retrieveFileStream(srcFilePath);
var bufferLength = 1024*4;
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE,bufferLength);
var read;
var len = 0;
while ((read = inputStream.read(buffer)) != - 1)
{

desFileStream .write(buffer, 0 , read);
len += bufferLength;
runOnUIThread(function(){
pkg.Utils.updateProgress(len/1024);
});
}


desFileStream.close();
inputStream.close();
runOnUIThread(function(){
pkg.Utils.hideProgress();
});

return mFTPClient.completePendingCommand();
} catch ( e) {
pkg.Utils.hideProgress();
popup(e);
}

return status;
}

// Method to upload a file to FTP server:

/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: source file path in sdcard desFileName: file name to be
* stored in FTP server desDirectory: directory path where the file should
* be upload to
*/
this.ftpUpload = function( srcFilePath, desDirectory /*, context*/,size) {
mFTPClient.setFileType(file_types[current_filetype]);
var status = false;
runOnUIThread(function(){
pkg.Utils.showProgress(ctx,"Uploading",new File(srcFilePath).length()/1024,false);
});
try {
srcFileStream = new FileInputStream(srcFilePath);

// change working directory to the destination directory
mFTPClient.changeWorkingDirectory(desDirectory)

outputStream = mFTPClient.storeFileStream(srcFilePath.slice(srcFilePath.lastIndexOf("/")+1));
var bufferLength = 1024;
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE,bufferLength);
var read;
var len = 0;
while ((read = srcFileStream.read(buffer)) != - 1)
{

outputStream .write(buffer, 0 , read);
len += bufferLength;
runOnUIThread(function(){
pkg.Utils.updateProgress(len/1024);
});
}

outputStream.close();
srcFileStream.close();
runOnUIThread(function(){
pkg.Utils.hideProgress();
}); mFTPClient.changeWorkingDirectory("/");
return mFTPClient.completePendingCommand();
} catch ( e) {
pkg.Utils.hideProgress();
popup(e);
}

return status;
}
}

function selectEncoding(){
bUIThread( function ()
{
var p = choose(charsets,current_encoding,0,"Encoding");
if(p!=-1)current_encoding = p;

}
);

}

function selectFileType(){
bUIThread( function ()
{
var p = choose(fileTypes,current_filetype,0,"File Transfer Type");
if(p!=-1)current_filetype = p;
}
);
}




function openFile(pth)
{
var fpath = currentLocalPath+"/"+pth;
var i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile( new File(fpath)),MimeTypeMap.getSingleton().getMimeTypeFromExtension(fpath.slice(fpath.lastIndexOf(".")+1)));
ctx.startActivity(i);
}

function onPrepareOptionsMenu(menu)
{
menuOptions = ["Back","New Account","New Directory","Upload","Passive Mode","Encoding("+charsets[current_encoding]+")","Transfer("+fileTypes[current_filetype]+")","Exit"];
var cnt = 0;
menu.clear();
menuOptions.forEach(function(item){
if(cnt ===3){
menu.add(item).setEnabled(! inHome);
}else if(cnt ===5){
menu.add(item).setEnabled(inHome);
}else if(cnt===4){
menu.add(item).setCheckable(true).setChecked(passiveMode).setEnabled(inHome);
}else{
menu.add(item);
}
cnt++;
});

return true;
}

function onOptionsItemSelected(item)
{
menuActions[menuOptions.indexOf(String(item))]();

return true;
}

function write(a, b)
{
var str = new java.lang.String(b);
var buff = str.getBytes();
fiss = new java.io.FileOutputStream(a);
data = fiss.write(buff);
}

function formatDate(date)
{
return new SimpleDateFormat("HH:mm dd/MM/yyyy").format( new java.util.Date(date));
}

function formatSize(s){
var sz = Number(s); //new java.io.File(s).length// (1024*1024)).toFixed(4)+"MB"
var nsz = ""
if(sz<1024){
nsz=sz.toFixed(2)+"B"
}
else if(sz<Math.pow(1024,2)){
nsz=(sz/Math.pow(1024,1)).toFixed(2)+" k"
}
else if(sz<Math.pow(1024,3)){
nsz=(sz/Math.pow(1024,2)).toFixed(2)+" M"
}
else if(sz<Math.pow(1024,4)){
nsz=(sz/Math.pow(1024,3)).toFixed(2)+" G"
}
else if(sz<Math.pow(1024,5)){
nsz=(sz/Math.pow(1024,4)).toFixed(2)+" T"
}
else{
nsz=(sz/Math.pow(1024,4)).toFixed(2)+"TB"
}
return nsz
}

function onKeyDown(keycode,event)
{
// if (!event.isCanceled())
// {
if (keycode === KeyEvent.KEYCODE_BACK)
{
if(!ftpBack())ctx.finish();
return true ;
}
// }
return false ;
}


function multiPrompt(array,title,btns,callback,defaults){
var result = [];
var ab = new AlertDialog.Builder(ctx);
var lay = new LinearLayout(ctx);
lay.setPadding(5,10,5,10);
lay.setOrientation(1);
for(var i= 0;i<array.length;i++){
var txt = new TextView(ctx);
txt.setText(array[i]);
var edt = new EditText(ctx);
edt.setTag(String(i));
if(defaults)if(defaults[i])edt.setText(String(defaults[i]));
lay.addView(txt);
lay.addView(edt)
}
ab.setView(lay);
if(title)ab.setTitle(title);
if(btns){
if(btns[0])ab.setPositiveButton(btns[0],function(){
for(var i= 0;i<array.length;i++){
result[i] = String(lay.findViewWithTag(String(i)).getText().toString());
}
(callback)(result,0);
});
if(btns[1])ab.setNegativeButton(btns[1],
function(){
(callback)(result,1)
});
if(btns[2])ab.setNeutralButton(btns[2],function(){
(callback)(result,2)
});
}
ab.show();
}

Report Page