from ftplib import FTP
import sys, os, os.path, operator, getpass
def upload(handle,filename):
	f = open(filename,"rb")
	(base,ext) = os.path.splitext(filename)
	picext = ".bmp .jpg .jpeg .dib .tif .tiff .gif .png"
	if(operator.contains(picext,ext)):
		try:
			handle.storbinary("STOR " + filename,f,1)
		except Exception:
			print("Successful upload.")
		else:
			print("Successful upload.")
		f.close()
		return

	try:
		handle.storbinary("STOR " + filename,f)
	except Exception:
		print("Successful upload.")
	else:
		print("Successful upload.")
	f.close()
	return


def download(handle,filename):
	f2 = open(filename,"wb")
	try:
		handle.retrbinary("RETR " + filename,f2.write)
	except Exception:
		print("Error in downloading the remote file.")
		return
	else:
		print("Successful download!")
	f2.close()
	return

print("FTP Client, made by Alexander Hochwimmer")
host_name = input("Enter website name to connect to, exclude ftp notation:  ")
if "http://" in host_name:
	host_name = host_name.replace("http://","")
host_name = host_name.replace("\n","")
if "ftp://" in host_name:
        host_name = host_name.replace("ftp://","")
user = input("Enter username: ")
print("(The password is hidden for security reasons, but is still there so don't worry)")
pwd = getpass.getpass("Enter password: ")
os.system("clear")
try: ftph = FTP(host_name)
except:
	print("Host could not be resolved, please check your internet connection, press Enter to exit")
	input()
	sys.exit()
else: pass
try:
	ftph.login(user,pwd)
except Exception:
	if user == "anonymous" or user == "Anonymous" and pwd == "anonymous" or pwd == "Anonymous":
		print("The server does not accept anonymous requests.")
		input()
		sys.exit()
	else:
		print("Invalid login combination.")
		input()
		sys.exit()
else:
	print("Successfully connected!\n")
print(ftph.getwelcome())
flag = 1
count = 0
path = ftph.pwd()
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*()-_=+[{]};:\|/?.>,<"
print("Type help at any time to see proper usage.\n")
while flag:
	command = input("FTP: ")
	if "get " in command:
		rf = command.replace("get ","")
		rf = rf.replace("\n","")
		download(ftph,rf)
		continue
	elif "put " in command:
		lf = command.replace("put ","")
		lf = lf.replace("\n","")
		upload(ftph,lf)
		ftph.close()
		ftph = FTP(host_name)
		ftph.login(user,pwd)
		continue
	elif "mkdir " in command:
		mkdirname = command.replace("mkdir ","")
		mkdirname = mkdirname.replace("\n","")
		try: ftph.mkd(mkdirname)
		except:
			print("A Problem occured.")
			print("Please make sure you have write access on the server.")
			continue
		else:
			print("Directory created.")
			continue
	elif "rmdir " in command:
		rmdirname = command.replace("rmdir ","")
		rmdirname = rmdirname.replace("\n","")
		current = ftph.pwd()
		ftph.cwd(rmdirname)
		allfiles = ftph.nlst()
		for file in allfiles:
			try:
				ftph.delete(file)  
			except Exception:
				pass
			else:
				pass
		ftph.cwd(current)
		try:
			ftph.rmd(rmdirname)
		except Exception:
			print("All files within the directory have been deleted, but there is still another directory inside.  As deleting this directory automatically goes against true FTP protocol, you must manually delete it, before you can delete the entire directory.")
		else:
			print("Directory deleted.")
		continue
	elif command == "ls":
		print(ftph.dir())
		continue
	elif command == "pwd":
		print(ftph.pwd())
		continue
	elif "cd " in command:
		dirpath = command.replace("cd ","")
		dirpath = dirpath.replace("\n","")
		ftph.cwd(dirpath)
		print("Directory changed to " + dirpath)
		continue
	elif command == "version":
		print("FTP Client version 0.94 BETA")
		continue	
	elif command == "up":
		dir = ftph.pwd()
		temp = dir
		index = len(dir) - 1
		for i in range(index,0,-1):
			if temp[i] == "/" and i != len(dir):
				ftph.cwd(temp)
				print("One directory back.")
				continue
			if(operator.contains(charset,dir[i])):
				temp = temp[:-1]
				if temp=="/":
					ftph.cwd(temp)
					print("One directory back.")
	elif command == "rename":
		fromname = input("Current file name: ")
		toname = input("To be changed to: ")
		ftph.rename(fromname,toname)
		print("Successfully renamed.")
		continue
	elif "rm " in command:
		delfile = command.replace("rm ","")
		delfile = delfile.replace("\n","")
		ftph.delete(delfile)
		print("File successfully deleted.")
		continue
	elif command == "exit":
		ftph.close()
		print("Session ended.")
		sys.exit()
	elif "size " in command:
		szfile = command.replace("size ","")
		szfile = szfile.replace("\n","")
		print("The file is " + str(ftph.size(szfile)) + "bytes.")
		continue		
	elif command == "debug -b":
		ftph.set_debuglevel(1)
		print("Debug mode set to base.")
		continue
	elif command == "debug -v":
		ftph.set_debuglevel(2)
		print("Debug mode set to verbose.")
		continue
	elif command == "debug -o":
		ftph.set_debuglevel(0)
		print("Debug mode turned off.")
		continue
	elif command == "help":
		print("debug -o - Turns off debug output")
		print("debug -v - Turns the debug output to verbose mode")
		print("debug -b - Turns the debug output to base")
		print("size [filename] - Returns the size in bytes of the specified file")
		print("exit - Exit the ftp session")
		print("rm [filename] - Delete a file")
		print("rename - Rename a file")
		print("up - Navigate 1 directory up")
		print("cd [path] - Change which directory you're in")
		print("pwd - Prints the path of the directory you are currently in")
		print("ls - Lists the contents of the directory")
		print("rmdir [directory path] - Removes/deletes an entire directory")
		print("mkdir [directory path] - Creates a new directory")
		print("put [filename] - Stores a local file onto the server")
		print("get [filename] - Download a remote file onto your computer")
		print("version - Displays current version of FTP Client\n")
		continue
	else:
		print("Sorry, invalid command.  Check 'help' for proper usage.")
		continue
	

