Ejemplo n.º 1
0
    def get_input(self):
        path_short_form = self.unionpath.create_short_cwd(True)

        if self.unionpath.connected:
            message = color.bold(
                color.green('● ' + self.unionpath.user_name +
                            "@{}".format(self.unionpath.client.IP))
            ) + ":" + color.bold(color.blue(path_short_form) + '$ ')
        else:
            message = color.bold(
                color.grey('● ') + color.green(self.unionpath.user_name)
            ) + ":" + color.bold(color.blue(path_short_form) + '$ ')

        message = input(message)
        cmds = message.split()
        result = self._handle(cmds)
        if result:
            if (isinstance(result, tuple)):
                if len(result) == 2:
                    self.protocol.handle(result[0], additional=result[1])
            else:
                if len([result]) == 1:
                    result = self.protocol.handle(result)
                    if result == "END":
                        return result
                elif len([result]) == 2:
                    self.protocol.handle(result[0], additional=result[1])
Ejemplo n.º 2
0
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
Ejemplo n.º 3
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))))
Ejemplo n.º 4
0
    def get_input(self):
        path_short_form = self.unionpath.create_short_cwd(True)

        if self.unionpath.connected:
            message = color.bold(color.green('● ' + self.unionpath.user_name + "@{}".format(self.unionpath.client.IP))) + ":" + color.bold(
                color.blue(path_short_form) + '$ ')
        else:
            message = color.bold(color.grey('● ') + color.green(self.unionpath.user_name)) + ":" + color.bold(
            color.blue(path_short_form) + '$ ')

        message = input(message)
        cmds = message.split()
        result = self._handle(cmds)
        if result:
            result = self.protocol.handle(result)
        if result == "END":
            return result
Ejemplo n.º 5
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)))
Ejemplo n.º 6
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
Ejemplo n.º 7
0
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]
Ejemplo n.º 8
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
Ejemplo n.º 9
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])