예제 #1
0
 def register_to_server(self, IP, name):
     self.unionpath.connected = self.unionpath.client.connect(IP)
     if self.unionpath.connected:
         server = self.unionpath.edit_mount_list("get",
                                                 property="servers").get(IP)
         if server:
             if server == name:
                 self.unionpath.edit_mount_list("add_server",
                                                IP=IP,
                                                servername=name)
             else:
                 while True:
                     anwser = input(
                         color.yellow(
                             "Server at IP: {} already registered. Rename {} -> {}? [y/n] -> "
                             .format(IP, server, name))).lower()
                     if anwser.__eq__("y") or anwser.__eq__("yes"):
                         self.unionpath.edit_mount_list("add_server",
                                                        IP=IP,
                                                        servername=name)
                         break
                     elif anwser.__eq__("n") or anwser.__eq__("no"):
                         break
         else:
             self.unionpath.edit_mount_list("add_server",
                                            IP=IP,
                                            servername=name)
     else:
         print(color.red("Connection to {} no established".format(IP)))
         return
예제 #2
0
 def handle_duplicates(self, matches, name):
     msg = "{} duplicates of {} have been found. Select one by entering the corresponding number:".format(
         len(matches), name)
     str = ""
     cnt = 0
     for info in matches:
         str += "\r\n[{}] {}: Fingerprint -> {}".format(
             cnt + 1, info[0], info[1])
         cnt += 1
     msg += str
     print(color.yellow(msg))
     while True:
         try:
             choice = input(color.bold(color.purple("{} -> ".format(name))))
             choice = int(choice)
             if choice >= 1 and choice <= len(matches):
                 choice -= 1
                 return choice
             else:
                 print(
                     color.red(
                         "Please enter a number between {} and {}.".format(
                             1, len(matches))))
         except:
             print(
                 color.red(
                     "Please enter a number between {} and {}.".format(
                         1, len(matches))))
예제 #3
0
파일: create.py 프로젝트: Kyrus1999/BACnet
def welcome():

    msg = color.cyan("############################################################################\n")
    msg += color.cyan("#                      ~ {}{}\n").format(
        color.purple("Redecentralised Filesystem"), color.cyan(" ~                      #"))
    msg += color.cyan("#                                                                          #\n")
    msg += color.cyan("#   - Establish connection with to file server with {}   {}\n").format(
        color.yellow("register <IP> <Name>"), color.cyan("#"))
    msg += color.cyan("#   - Enter {} {}\n").format(color.yellow("name"), color.cyan(
        "of known server                   	                   #"))
    msg += color.cyan("#   - List names of all known servers with {}           	   {}\n").format(
        color.yellow("serverlist"), color.cyan("#"))
    msg += color.cyan("#   - Exit program with {}                     	             	   {}\n").format(
        color.yellow("quit"), color.cyan("#"))
    msg += color.cyan("############################################################################\n")
    return msg
예제 #4
0
 def upload_mount_partition(self, name):
     if not self.unionpath.connected:
         print(color.red("Please connect to a sever in order to mount."))
         return
     hashdir = self.unionpath.translate_to_hash(
         name, self.unionpath.filesystem_root_dir)
     if not hashdir:
         while True:
             response = input(
                 color.yellow(
                     "{} does not exist. Do you want to create an empty partition? [y/n] -> "
                     .format(name))).lower()
             if response == "y" or response == "yes":
                 tmp = self.unionpath.current_folder
                 self.unionpath.current_folder = self.unionpath.filesystem_root_dir
                 hashdir = self.make_directory(name)
                 self.unionpath.current_folder = tmp
                 break
             elif response == "n" or response == "no":
                 return
     else:
         while True:
             response = input(
                 color.yellow("Mount {} to {}? [y/n] -> ".format(
                     name, self.unionpath.client.IP))).lower()
             if response == "y" or response == "yes":
                 break
             elif response == "n" or response == "no":
                 return
     self.unionpath.edit_dictionary(hash=hashdir,
                                    op='edit',
                                    name=name,
                                    property='mount')
     self.unionpath.edit_mount_list(op="add_mount",
                                    mounthash=hashdir,
                                    mountname=name)
     mountpath = os.path.join(self.unionpath.filesystem_root_dir, hashdir)
     if not os.listdir(mountpath):
         return "mnt {} {} {} {}".format("upload", hashdir, name, "True")
     else:
         files = help_functions.get_all_files_from_dir(mountpath)
         for file in files:
             self.unionpath.edit_dictionary(hash=file,
                                            op='edit',
                                            name=hashdir,
                                            property='mount')
         return "mnt {} {} {} {}".format("upload", hashdir, name, "False")
예제 #5
0
	def reg(self, cmds):
		if len(cmds) == 3:
			if re.match("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", cmds[1]):
				self.executions.register_to_server(cmds[1], cmds[2])
				return "reg"
			else:
				print(color.yellow("{} is not a valid IP-address.".format(cmds[1])))
		else:
			print(help.helping(cmds))
예제 #6
0
파일: create.py 프로젝트: Kyrus1999/BACnet
def thank():
    names = ['Ken Rotaris', 'Tunahan Erbay', 'Leonardo Salsi']
    random.shuffle(names)  # names in random order
    names[0] = color.bold(color.red(names[0]))
    names[1] = color.bold(color.greenDark(names[1]))
    names[2] = color.bold(color.yellow(names[2]))
    random.shuffle(names)
    msg = '\n   Thanks for using our Application!\n   Made with ' + color.bold(
            color.redLight('❤')) + ' by: {0}, {1}, {2}\n'.format(names[0], names[1], names[2])
    return msg
예제 #7
0
 def terminate_program(self):
     while True:
         terminate = input(
             color.yellow("Terminate Uniondir? [y/n] -> ")).lower()
         if terminate.__eq__("y") or terminate.__eq__("yes"):
             terminate = True
             break
         elif terminate.__eq__("n") or terminate.__eq__("no"):
             terminate = False
             break
     if not terminate:
         return
     if self.unionpath.connected:
         self.unionpath.client.disconnect()
     print(create.thank())
     return "END"
예제 #8
0
 def connect_to_server(self, name):
     servers = self.unionpath.edit_mount_list("get", property="servers")
     candidates = []
     IP = None
     for server in servers:
         if name == servers.get(server):
             candidates.append(server)
     if len(candidates) == 0:
         print(
             color.red(
                 "No server under the name {} registered".format(name)))
         return
     elif len(candidates) == 1:
         IP = candidates[0]
     else:
         print(
             color.yellow(
                 "Multiple servers under the name {} registered: ".format(
                     name)))
         for i in range(len(candidates)):
             print("[{}] -> {}".format(i + 1, candidates[i]))
         while True:
             try:
                 choice = input(
                     color.bold(color.purple("{} -> ".format(name))))
                 choice = int(choice)
                 if choice >= 1 and choice <= len(candidates):
                     choice -= 1
                     break
                 else:
                     print(
                         color.red(
                             "Please enter a number between {} and {}.".
                             format(1, len(candidates))))
             except:
                 print(
                     color.red(
                         "Please enter a number between {} and {}.".format(
                             1, len(candidates))))
         IP = candidates[choice]
     self.unionpath.connected = self.unionpath.client.connect(IP)
     if not self.unionpath.connected:
         print(color.red("Unable to connect to {}({}).".format(name, IP)))
예제 #9
0
	def mount(self, cmds):
		if len(cmds) == 2:
			while True:
				response = input(color.yellow("Do you want to upload or download a partition? [u/d/stop] -> ")).lower()
				if response == "d" or response == "download":
					return self.executions.download_mount_partition(cmds[1])
				elif response == "u" or response == "upload":
					return self.executions.upload_mount_partition(cmds[1])
				elif response == "stop":
					return
		elif len(cmds) == 3:
			response = cmds[2]
			if response == "d" or response == "download":
				return self.executions.download_mount_partition(cmds[1])
			elif response == "u" or response == "upload":
				return self.executions.upload_mount_partition(cmds[1])
			else:
				print(help.helping(cmds))
		else:
			print(help.helping(cmds))
예제 #10
0
def help():
    '''
	USE: help.help()
	
	Description:
	returns the '--help' text
	
	Notes:
	if you add extra operators, make sure to add them here ad well as in help.spfc_opr() and the error.get() dictionary and the help.dct() dictionary.
	'''
    css_1 = '\n\n   '
    css_2 = '\n      '
    commands = [
        'reg', 'con', 'cd', 'open', 'ls', 'srv', 'mk', 'add', 'rm', 'mt', 'mv',
        'cp', 'rn', 'f', '--help', 'quit', 'clear', 'exp'
    ]
    help = color.green('this is the --help section:')
    for cmd in commands:
        help += css_1 + '» ' + color.bold(str(
            spfc_opr(cmd, True))) + color.cyan(css_2 + 'aliases: ' + str(
                spfc_opr(cmd))) + css_2 + '' + color.yellow(
                    dct(cmd)[0]) + css_2 + '' + color.grey(dct(cmd)[1])
    return help
예제 #11
0
    def client_thread(self):
        try:
            while True:
                message = self.conn.recv(2048)
                if message:
                    resp = self.handle_message(message)
                    if resp:
                        print(color.yellow(resp))
                        if resp == "DMNT":
                            continue
                        else:
                            self.conn.send(str.encode(resp))
                        if resp == 'DEN':
                            break
                        if resp == 'CQUIT':
                            self.conn.close()
                            break

        except:
            print(
                color.red("Connection to {}@{} lost".format(
                    self.hash, self.IP)))
            self.conn.close()
            return
예제 #12
0
파일: error.py 프로젝트: Kyrus1999/BACnet
def get(cmds, typ, add_attr=None):
    '''
	USE:
	error.get(cmds, type, [optional:add_attr]) where add_attr must be < 3
	
	Description:
	Returns a correctly colored message according to declared "typ"
	'''
    #---------------------------------------------------------------
    if not add_attr:
        add_attr = [None, None, None]
    elif len(add_attr) < 3:
        for i in range(3 - len(add_attr)):
            add_attr.append(None)
    if len(cmds) < 2:
        cmds.append(None)

    operator = help.spfc_opr(cmds[0], True)
    names = [None, None, None]
    if operator == 'q':
        names = ['Ken Rotaris', 'Tunahan Erbay', 'Leonardo Salsi']
        random.shuffle(names)  #names in random order
        names[0] = color.bold(color.red(names[0]))
        names[1] = color.bold(color.greenDark(names[1]))
        names[2] = color.bold(color.yellow(names[2]))
        random.shuffle(names)

    dictionary = {
        #command   | messages #TODO: blank messages are not being used yet/ have not ben set yet.
        'cd': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('The directory does not exist')
        },
        'open': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('unable to open file')
        },
        'ls': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('given directory doesn\'t exist'),
            'unknown': color.red('Unknown option \'{}\''.format(cmds[1]))
        },
        'cat': {
            'success':
            color.greenDark(''),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('file doesn\'t exist at \'{1}\''.format(
                cmds[0], add_attr)),
            'nt_supp':
            color.red(
                'file type currently not supported by \'{}\' command'.format(
                    cmds[0])),
            'hint':
            color.grey(
                'tip: use \'{}\' followed by an integer to display a range.'.
                format(cmds[0]))
        },
        'mk': {
            'success':
            color.greenDark('folder {0} created'.format(
                add_attr[0])),  #add_attr = [name, path]
            'warning':
            color.yellow('wrong argument format'),
            'file_error':
            color.red(
                'name cannot contain a dot'),  #add_attr = [name, typ, path]
            'format_error':
            color.red('please use command as follows: mk <dir_name>'),
            'path_error':
            color.red('the path the folder is to be created in does not exist'.
                      format(add_attr))
        },
        'add': {
            'success':
            color.greenDark('File added to the filesystem.'),
            # add_attr = [name, path]
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('{0} "{1}" already exists at {2}'.format(
                add_attr[1], add_attr[0], add_attr[2])),
            # add_attr = [name, typ, path]
            'path_error':
            color.red('The source does not exist'.format(add_attr)),
            'format_error':
            color.red(
                '\'{}\' either outside of the filesystem or not an existing directory'
                .format(add_attr[2])),
            'nodstdir':
            color.red('Destination folder does not exist.'),
            'fs_error':
            color.red('Cannot add files from within the filesystem.')
        },
        'rm': {
            'success':
            color.greenDark('deleted {0} from {1}'.format(
                add_attr[0], add_attr[1])),  #add_attr = [name, path]
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('{0} "{1}" does not exists at {2}'.format(
                add_attr[1], add_attr[0],
                add_attr[2])),  #add_attr = [name, typ, path]
            'path_error':
            color.red('\'{}\' doesn\'t exist'.format(add_attr))
        },
        'mount': {
            'success':
            color.greenDark('Filesystem mounted successfully.'),
            'warning':
            color.yellow(
                'Mount a filesystem of an other user with mnt <user> <filesystem_name> [<path>]'
            ),
            'error':
            color.red('Unable to mount filesystem.'),
            'nodst':
            color.red('Destination path does not exist.')
        },
        'umt': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('')
        },
        'exp': {
            'success':
            color.greenDark('Filesystem has been successfully exported!'),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red(
                'No root_mockup folder found at current location or its super folders \'{}\'.'
                .format(add_attr[0]))
        },
        'mkp': {
            'success':
            color.greenDark(''),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('folder \'{0}\' already exists at \'{1}\''.format(
                add_attr[0], add_attr[1]))
        },
        'pwd': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('')
        },
        'img': {
            'success':
            color.greenDark(
                'sucessfully created image \'{0}\' at \'{1}\''.format(
                    add_attr[0], add_attr[1])),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('')
        },
        'txt': {
            'success':
            color.greenDark(
                'sucessfully created text \'{0}\' at \'{1}\''.format(
                    add_attr[0], add_attr[1])),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('')
        },
        'mv': {
            'success':
            color.greenDark('sucessfully moved file \'{0}\' to \'{1}\''.format(
                add_attr[0], add_attr[1])),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('the {0} path \'{1}\' doen\'s exist'.format(
                add_attr[0], add_attr[1])),
            'sameDir':
            color.grey(
                'Information: you moving a file/folder within the same directory.'
            ),
            'nodstdir':
            color.red('The destination directory does not exist.'),
            'nosrcdir':
            color.red('The source file or directory does not exist.')
        },
        'cp': {
            'success':
            color.greenDark(
                'sucessfully copied file \'{0}\' to \'{1}\''.format(
                    add_attr[0], add_attr[1])),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('the {0} path \'{1}\' doen\'s exist'.format(
                add_attr[0], add_attr[1]))
        },
        'rn': {
            'success':
            color.greenDark(
                'sucessfully renamed file \'{0}\' to \'{1}\''.format(
                    add_attr[0], add_attr[1])),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('the given path \'{0}\' doen\'s exist'.format(
                add_attr[0])),
            'nosrcdir':
            color.red('The source file or directory does not exist.')
        },
        'f': {
            'success':
            color.greenDark('\'{0}\' found at {1}'.format(
                add_attr[0], add_attr[1])),
            'warning':
            color.yellow('wrong argument format'),
            'error':
            color.red('\'{0}\' not found in \'{1}\''.format(
                add_attr[0], add_attr[1]))
        },
        '--help': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('')
        },
        'quit': {
            'success':
            '\n   Thanks for using our Application!\n   Made with ' +
            color.bold(color.redLight('<3')) +
            ' by: {0}, {1}, {2}\n'.format(names[0], names[1], names[2]),
            'warning':
            color.yellow(
                'If you want to terminate program, enter q without further arguments.'
            ),
            'error':
            color.red(
                'If you want to terminate the program, enter q without further arguments.'
            )
        },
        'clear': {
            'success': color.greenDark(''),
            'warning': color.yellow('wrong argument format'),
            'error': color.red('')
        }
    }

    return dictionary[operator][typ]
예제 #13
0
 def warning(word, debug_print=True):
     msg = "[!] %s\n" % color.yellow(log.beauty(word))
     if not debug_print:
         return
     log.my_log(msg, word)
예제 #14
0
 def remove_object(self, name, suppress=False):
     try:
         obj_hash, os_obj_path = self.unionpath.get_full_path(name)
     except:
         return
     hashes = [obj_hash]
     if os.path.isfile(os_obj_path):
         os.remove(os_obj_path)
         filehashes = [obj_hash]
         return hashes, filehashes
     elif os.path.isdir(os_obj_path):
         filehashes = []
         if len(os.listdir(os_obj_path)) == 0:
             empty = True
         else:
             empty = False
         if not empty:
             tmp = self.unionpath.current_folder
             os.chdir(os_obj_path)
             self.unionpath.current_folder = os.getcwd()
             files = help_functions.get_files_from_current_dir(
                 self.unionpath)
             os.chdir(tmp)
             self.unionpath.current_folder = tmp
             if not suppress:
                 while True:
                     show_content = input(
                         color.yellow(
                             "Folder {} is not empty. Display content? [y/n/stop]"
                             .format(name)))
                     if show_content.lower() == "y" or show_content.lower(
                     ) == "yes":
                         self.list_folder_content(files)
                         break
                     elif show_content.lower() == "n" or show_content.lower(
                     ) == "no":
                         break
                     elif show_content.lower() == "stop":
                         return
                     else:
                         print(
                             color.red(
                                 "Please enter [y/n], if you want to stop the deletion enter [stop]."
                             ))
                 while True:
                     show_content = input(
                         color.yellow(
                             "Delete all content of {}? [y/n]".format(
                                 name)))
                     if show_content.lower() == "y" or show_content.lower(
                     ) == "yes":
                         for (dirpath, dirnames,
                              filenames) in os.walk(os_obj_path):
                             hashes.extend(filenames)
                             filehashes.extend(filenames)
                             hashes.extend(dirnames)
                         shutil.rmtree(os_obj_path)
                         return hashes, filehashes
                     elif show_content.lower() == "n" or show_content.lower(
                     ) == "no":
                         return
             else:
                 for (dirpath, dirnames, filenames) in os.walk(os_obj_path):
                     hashes.extend(filenames)
                     filehashes.extend(filenames)
                     hashes.extend(dirnames)
                 shutil.rmtree(os_obj_path)
                 return hashes, filehashes
         else:
             shutil.rmtree(os_obj_path)
             return hashes, filehashes
예제 #15
0
def mount(client, user, fs_name, dst):
    try:
        msg = "MNT_USER {} {} {}".format(user, client.filesystem_hash, fs_name)
        client.send(msg)
        user_matches = client.server_socket.recv(2048)
        user_matches = ast.literal_eval(user_matches.decode("utf-8"))
        #print(user_matches)
        if user_matches == "DMNT":
            return False
        if len(user_matches) == 0:
            user_choice = "None"
        elif len(user_matches) == 1:
            user_choice = user_matches[0][0]
        else:
            msg = ""
            #print(color.yellow("Multiple possibilities found:"))
            for i in range(len(user_matches) - 1):
                msg += color.yellow("[{}] {}@{} -> {} [{}]\n".format(
                    i + 1, user_matches[i][1], user_matches[i][2],
                    user_matches[i][0], fs_name))
            msg += color.yellow("[{}] {}@{} -> {} [{}]".format(
                len(user_matches) - 1 + 1,
                user_matches[len(user_matches) - 1][1],
                user_matches[len(user_matches) - 1][2],
                user_matches[len(user_matches) - 1][0], fs_name))
            while True:
                print(msg)
                try:
                    choice = input(
                        color.bold(
                            color.green('● ' + client.user +
                                        "@{}".format(client.IP))) +
                        color.purple(":{} -> ".format(user)))
                    choice = int(choice)
                    if choice >= 1 and choice <= len(user_matches):
                        choice -= 1
                        break
                    else:
                        print(
                            color.red(
                                "Please enter a number between {} and {}.".
                                format(1, len(user_matches))))
                except:
                    print(
                        color.red(
                            "Please enter a number between {} and {}.".format(
                                1, len(user_matches))))
            user_choice = user_matches[choice][0]
        if user_choice in client.get_mounts():
            print(color.yellow("This filesystem is already mounted"))
            return False
        client.send(user_choice)
        root_mount = client.server_socket.recv(2048)
        root_mount = root_mount.decode("utf-8").split()
        if not root_mount[0] == "DIR":
            return False
        root_dir_hash, time = root_mount[1], root_mount[2]
        client.add_to_dict(root_dir_hash,
                           fs_name,
                           "directory",
                           dst,
                           timestamp=time)
        path = client.mk(dst, root_dir_hash)
        client.send("DIR_DONE")
        dir_batch = []
        fs_path_root = fs_name
        while True:
            dir_info = client.server_socket.recv(2048)
            dir_info = dir_info.decode("utf-8").split()
            if dir_info[0] == "DIR":
                dir_batch.append([
                    dir_info[1][1:], dir_info[2], dir_info[3], dir_info[4],
                    dir_info[5]
                ])
                client.send("DONE")
            elif dir_info[0] == "DIR_DONE":
                #print(color.green("GOT ALL"))
                break
        hashdict = {}
        for i in range(len(dir_batch)):
            dir_path, dir_hash, name, time, type = dir_batch[i]
            #print("DIR {} {} {} {} {} ".format(dir_path, dir_hash, name, time, type))
            hashdict.update({dir_hash: name})
            client.mk(path, dir_path)
            if os.sep not in dir_path:
                dir_path = dir_path.replace(dir_hash, "")
            else:
                dir_path = dir_path.replace(dir_hash + os.sep, "")
            if not dir_path:  # hash, name, type, location, extension="", fs_path = "", timestamp=None
                client.add_to_dict(dir_hash,
                                   name,
                                   type,
                                   path,
                                   fs_path=fs_path_root,
                                   timestamp=time)
            else:
                fs_path = dir_path
                dirs = dir_path.split(os.sep)
                #print(color.purple(fs_path))
                #print(hashdict)
                for dir in dirs:
                    fs_path = fs_path.replace(dir, hashdict.get(dir))
                fs_path = fs_path.replace(os.sep + name, "")
                client.add_to_dict(dir_hash,
                                   name,
                                   type,
                                   os.path.join(
                                       path,
                                       dir_path.replace(os.sep + dir_hash,
                                                        "")),
                                   fs_path=os.path.join(fs_path_root, fs_path),
                                   timestamp=time)
        client.send("DIRS_DONE")
        #print(color.green("DIRS_DONE SENT"))
        filehashes = []
        while True:
            file_info = client.server_socket.recv(2048)
            file_info = file_info.decode("utf-8").split()
            if file_info[0] == "CMNT":
                return True, hashdict, filehashes, root_dir_hash
            elif len(file_info) != 7:
                continue
            #print(file_info)
            file_fs_path, file_hash, name, time, type, extension = file_info[
                1], file_info[2], file_info[3], file_info[4], file_info[
                    5], file_info[6]
            if file_info[0] == "FILE":
                #print(color.green("SEND CFILE"))
                client.send("CFILE")
            filepath = os.path.join(path, file_fs_path)
            with open(filepath, "wb") as file:
                while True:
                    bytes = client.server_socket.recv(BUFFER_SIZE)
                    file.write(bytes)
                    if bytes.strip()[-3:] == b'EOF':
                        break
                    elif bytes.strip()[-3:] == b'INT':
                        return False
                file.close()
            if extension == "None":
                extension = ""
            abs_path = os.path.join(path,
                                    file_fs_path.replace(
                                        root_dir_hash, "")).replace(
                                            os.sep + file_hash + extension, "")
            file_fs_path = os.path.join(fs_path_root, file_fs_path).replace(
                os.sep + file_hash + extension, "")
            client.add_to_dict(file_hash,
                               name,
                               type,
                               abs_path,
                               fs_path=file_fs_path,
                               timestamp=time,
                               extension=extension)
            #print(color.green("SEND CCFILE"))
            filehashes.append(file_hash)
            client.send("CCFILE")
    except:
        return False
예제 #16
0
 def send_mount_instruction(self, info):
     info = info.split()
     if info[1] == "upload":
         self.client.send("MNT-U {} {} {}".format(info[2], info[3],
                                                  info[4]))
         answer = self.client.get()
         print(
             color.green("{} has been successfully upladed.".format(
                 info[2])))
         if answer == "DONE":
             return
         elif answer == "GIVE":
             self.filehandler.send_all_files_of_dir(
                 os.path.join(self.unionpath.filesystem_root_dir, info[2]))
             self.client.send("DONE")
     elif info[1] == "download":
         self.client.send("MNT-D {}".format(info[2]))
         answer = self.client.get()
         if answer == "NONE":
             print(
                 color.yellow(
                     "There are no mounts named {} on the server.".format(
                         info[2])))
             return
         elif answer == "ONE":
             self.client.send("OK")
             mount = self.client.get().split()[1]
             mountpath = os.path.join(self.unionpath.filesystem_root_dir,
                                      mount)
             os.mkdir(mountpath)
             self.unionpath.add_to_dictionary(
                 mount,
                 info[2],
                 "directory",
                 self.unionpath.filesystem_root_dir,
                 "",
                 timestamp=None,
                 extension=None,
                 mount=mount)
             self.client.send("GIVE")
             while (True):
                 message = self.client.get()
                 if message == "DONE":
                     break
                 elif message == "\EOF":
                     continue
                 self.filehandler.get_file(message +
                                           " {}".format(mountpath),
                                           dir=mount)
         elif answer == "MORE":
             self.client.send("OK")
             mounts = self.client.get().split(".")
             msg = "{} duplicates of {} have been found. Select one by entering the corresponding number:".format(
                 len(mounts), info[2])
             str = ""
             cnt = 0
             for mount in mounts:
                 str += "\r\n[{}] {}: Identifier -> {}".format(
                     cnt + 1, info[2], mount)
                 cnt += 1
             msg += str
             print(color.yellow(msg))
             while True:
                 try:
                     choice = input(
                         color.bold(color.purple("{} -> ".format(info[2]))))
                     choice = int(choice)
                     if choice >= 1 and choice <= len(mounts):
                         choice -= 1
                         break
                     else:
                         print(
                             color.red(
                                 "Please enter a number between {} and {}.".
                                 format(1, len(mounts))))
                 except:
                     print(
                         color.red(
                             "Please enter a number between {} and {}.".
                             format(1, len(mounts))))
             self.client.send("{}".format(choice))
             mount = self.client.get().split()[1]
             mountpath = os.path.join(self.unionpath.filesystem_root_dir,
                                      mount)
             os.mkdir(mountpath)
             self.unionpath.add_to_dictionary(
                 mount,
                 info[2],
                 "directory",
                 self.unionpath.filesystem_root_dir,
                 "",
                 timestamp=None,
                 extension=None,
                 mount=mount)
             self.client.send("GIVE")
             while (True):
                 message = self.client.get()
                 if message == "DONE":
                     break
                 elif message == "\EOF":
                     continue
                 self.filehandler.get_file(message +
                                           " {}".format(mountpath),
                                           dir=mount,
                                           mount=mount)
         self.unionpath.edit_mount_list(op="add_mount",
                                        mounthash=mount,
                                        mountname=info[2],
                                        IP=self.client.IP)
         self.unionpath.sort_files_in_dir(
             os.path.join(self.unionpath.filesystem_root_dir, mount),
             info[2])
예제 #17
0
 def send(self, msg):
     if msg:
         print(color.yellow("-> {}".format(msg)))
         self.socket.send(str.encode(msg))
예제 #18
0
 def send(self, msg):
     print(color.yellow("Sending {}".format(msg)))
     self.conn.send(str.encode(msg))