コード例 #1
0
ファイル: host.py プロジェクト: rlguarino/PyShare
def handleSearch(IPDatabase, localData, ms, addr):
	user = IPDatabase.table[addr[0]]
	c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	c.bind(('', 0))
	port = str(c.getsockname()[1])
	utils.throw(ms, port)
	c.listen(1)
	s, addr = c.accept()
	
	term = encrypt.refract( utils.catch(s) , user.key)
	master=''
	for key in localData.files.keys():
		try:
			if term.lower() in localData.files[key].lower() or term.lower() in key.lower():
				master= master+localData.files[key]+','+key+"|"
		except UnicodeEncodeError:
			pass
	if len(master) >0:
		master=master[:-1]
	
	master=encrypt.encrypt(master, user.key)
	packetSize=1024
	segments = math.ceil(len(master)/packetSize)
	s.send(utils.formatNumber(segments).encode())
	position=0
	index=0
	while index<segments:
		segment=master[position:position+packetSize]
		s.send(segment.encode())
		position+=packetSize
		index+=1
コード例 #2
0
ファイル: host.py プロジェクト: rlguarino/PyShare
def handleConnection(IPDatabase, localData, ms, addr):
	try:
		c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		c.bind(('', 0))
		
		port = str(c.getsockname()[1])
		utils.throw(ms, port)
		c.listen(1)
		s, addr = c.accept()
		
		key = encrypt.genKey(s, 'RECV')
		
		#print('receiving nickname')
		data=utils.catch(s)
		nick=encrypt.refract(data, key)
		
		myNick = encrypt.encrypt(localData.nickName,key)
		utils.throw(s, myNick)
		#print('sending connected nodes')
		master, connections = IPDatabase.currentConnections()
		s.send(utils.formatNumber(len(connections)).encode())
		for ip in connections:
			element = encrypt.encrypt( connections[ip], key)
			utils.throw(s , element)
		
		IPDatabase.addIP(addr[0], key, nick)
		
	except(socket.error):
		pass
コード例 #3
0
ファイル: user.py プロジェクト: rlguarino/PyShare
def runCommand(IPDatabase, localData, command, arg1, arg2):
		if command == None and arg1 ==None and arg2 == None:
			print('invalid Command or arguments')
		if command == 'connect': #Connect
			if arg1 == None:
				arg1 = input('Enter the IP of the peer you would like to connect to: ')
			setUpConnection(IPDatabase, localData, arg1)
		elif command == 'settings':
			if arg1 == 'changedownload' or arg1 == 'download':
				if arg2 == None:
					arg2 = input("What directory would you like to set the download to? ")
					if arg2 == '' or arg2 =='0':
						return
				if os.path.exsts(os.path.dirname(arg2)):
					localData.downloadLocation = arg2
			if arg1 == None:
				print("-Current Configuration:")
				print("---NickName: "+str(localData.nickName))
				print("---Directories: "+str(localData.directoriesShared()))
				print("---Download: "+localData.downloadLocation)
		elif command == 'disconnect': #Disconnect
			"""
			Disconenct:
			command = 2
			arg1 = 0 -> diconnect from all
			arg1 = str(ip) -> disconnect from just that IP address
			arg1 = -all -> disconnect with everyone
			arg1 = None -> get an index from the user. then use thet index to get an IP and pass that into the function
			"""
			string, connections = IPDatabase.currentConnections()
			if arg1 == None:
				#Ther awas no argument passed
				print(string)
				arg1 = input('Enter the index of the node that you would like to disconenct from: ')
				
				if arg1 == '0':
					return

				elif arg1 == '':
					#disconnect with all
					for id in connections:
						removeConnection( IPDatabase, connections[id])
				
				else:
					try:
						arg1 = int(arg1)
					except(ValueError):
						print('Invalid input please ener an Int')
						return
					
					if arg1 in connections:
						#disconnect with only one
						removeConnection( IPDatabase, connections[arg1])
					else:
						#invalid input
						print("ERROR: IndexError[Index not valid]")
				
			elif arg1 == 'all':
				#the argument was '-all' which means disconnect all
				for id in connections:
					removeConnection(connections[id])
			else:
				if arg1 in connections:
					removeConnections(arg1)
				else:
					print('No such connected IP')
		
		elif command == 'reconnect': #Reconnect
			"""
			reconnect:
			command = 3
			arg1 = str(ip) -> reconnect with just that IP
			arg1 = -all -> reconenct with everone
			arg1 = None -> get an index from the user. reconnect with that IP
			"""
			string, connections = IPDatabase.currentConnections()
			if arg1 == None:
				#passed no arguments
				print(string)
				arg1 = input("ener the index of the peer that you would like to reconnect to: ")
				if arg1  == '':
					#entered empty string -> reconnect all
					for id in connections:
						removeConnection(IPDatabase, connections[id])
						setUpConnection(IPDatabase, localData, connections[id], True)
				
				elif int(arg1) in connections: #need to handle user errors here
					#entered a index
					removeConnection( IPDatabase, connections[int(arg1)])
					setUpConnection(IPDatabase, localData, connections[int(arg1)], True)
				else:
					#did not enter a valid anything
					print("ERROR: IndexError[Index not valid]")
			
	
			elif arg1 == 'all':
				#argument pass was '-all' reconnect all!
				for id in connections:
					removeConnection(IPDatabase, connections[id])
					setUpConnection(IPDatabase, localData, connections[id], True)
			else:
				#they pass an aggument
				removeConnection(IPDatabase, arg1)
				setUpConnection(IPDatabase, localData, arg1, True)

		elif command == 'search': #Search
			"""
			Search:
			Command = 4
			arg1 = str(searchterm) -> search with this search term 
			arg1 = None -> ask the user for a search term 
			"""
			if arg1 == None:
				arg1 = str(input("enter a term to search with: "))
				if len(arg1) < 3:
					print('You much enter a term larger than 3 characters')
					return
				
			
			
			results = search(IPDatabase, arg1)
			totalRes =len(results)
			if totalRes == 0:
				print("There were no results to you search")
				return
			elif totalRes > 50:
				choice=input("There #:]are "+ str(totalRes)+ " total results would you like to display all of them[y/n]")
				if choice == 'y' or choice == 'Y' or choice == "yes":
					printResults(IPDatabase, results, totalRes)
				else: 
					pass 
			
			else:
				printResults(IPDatabase, results, totalRes)
				
		elif command == 'download': #Download
			"""
			Download:
			arg1 = str(search term) -> search with this term
			arg1 = None -> ask the user for a search term
			"""
			
			if arg1 == None:
				arg1 = str(input("Enter a term to search for: "))
				if len(arg1) < 3:
					print('You much enter a term larger than 3 characters')
					return
			
			results = search(IPDatabase, arg1)
			totalRes = len(results)
			if totalRes == 0:
				print("There were no results to you search")
				return
			elif totalRes > 50:
				choice=input("There There "+ str(totalRes)+ " total results would you like to display all of them[y/n]")
				if choice == 'y' or choice == 'Y' or choice == "yes":
					printResults(IPDatabase, results, totalRes)
				else:
					return
					pass 
			
			else:
				printResults(IPDatabase, results, totalRes)
				
			
			index= input("enter the index of the file that you would like to download: ")
			
			if index.lower == 'exit':
				return
			
			try:
				index = int(index)
			except(ValueError):
				print("ERROR: [Index Error] Index not valid")
				return
			if index == 0:
				return
			if index > totalRes:
				print("ERROR: [Index Error] Index out of range")
			
			if results[index][0][:3] == '[D]':
				threading.Thread(target=directoryManager, name='Download manager', args=(IPDatabase, localData, results, index)).start()
			
			else:
				threading.Thread(target=download, name='Download Thread', args=(IPDatabase, localData, results[index])).start()
			#download(IPDatabase, localData, results[index])
		elif command == 'downloads':
			print(localData.currentDownloads())

		elif command == 'info': #Info
			print('PyShare [Version'+str(localData.currentVersion)+']')
			print('Nick : '+localData.nickName)	
			print('Directory shared: '+ str(localData.directoriesShared()))
			print("Files & Directories shared: "+ str(len(localData.files.keys())))
			string, connections = IPDatabase.currentConnections()
			print(string)

		elif command == 'clear': #Clear
			if os.system('clear') == 1:
				os.system('cls')

		elif command == 'help': #Help
			localData.helpPrint()

		elif command == 'exit': #Exit
			print('EXITING...')
			localData.exit(IPDatabase)
			massDisconnect(IPDatabase)
			localData.kill = True
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.connect(('127.0.0.1', 44450))
			temp='--'
			s.send(utils.formatNumber(len(temp)).encode())
			s.send(temp.encode())
			sys.exit()
			
		else:
			print('ERROR: [\'' +command+ '\']  is not a recognized command')
			print(">>> Commands: \'Connect\' , \'Disconnect\' , \'Search\' \n>>> \'Help\' for help.")