コード例 #1
0
 def rename_object(self, path, name):
     if os.sep in name:
         print(
             color.red("The name cannot contain the character {}.".format(
                 os.sep)))
         return
     if "." in name:
         name = name.split(".")[0]
     if os.sep in path:
         if "." in path.split(os.sep)[1]:
             dirs = path.split(os.sep)
             dirs[-1] = dirs[-1].split(".")[0]
             path = ""
             for i in range(len(dirs) - 1):
                 path = os.path.join(path, dirs[i])
     else:
         if "." in path:
             path = path.split(".")[0]
     curr = self.unionpath.current_folder
     if os.sep in path:
         dirs = path.split(os.sep)
         for i in range(len(dirs)):
             dirs[i] = self.unionpath.translate_to_hash(
                 dirs[i], curr, False)
             if not dirs[i]:
                 print(color.red("Location does not exist."))
                 return
             curr = os.path.join(curr, dirs[i])
     else:
         hash_name = self.unionpath.translate_to_hash(path, curr, False)
         curr = os.path.join(curr, hash_name)
     self.unionpath.edit_dictionary(hash=curr.split(os.sep)[-1],
                                    op='ren-name',
                                    name=name)
コード例 #2
0
ファイル: unionpath.py プロジェクト: Kyrus1999/BACnet
 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
 def add_directory_to_filesystem(self, source, destination=None):
     tmp = self.unionpath.current_folder
     if ".uniondir" in source:
         print(color.red("Cannot add object from within the filesystem."))
         return
     if not destination:
         destination = self.unionpath.current_folder
     else:
         curr = self.unionpath.current_folder
         dirs = destination.split(os.sep)
         for dir in dirs:
             curr = os.path.join(
                 curr, self.unionpath.translate_to_hash(dir, curr))
         destination = curr
     os.chdir(destination)
     fs_loc = self.unionpath.hashpath_to_fspath(os.getcwd())
     os.chdir(self.unionpath.current_folder)
     dir_name = source.split(os.sep)[-1]
     dir_hashname = self.unionpath.create_hash(source)
     destination = os.path.join(destination, dir_hashname)
     dst_dir = shutil.copytree(source, destination)
     self.unionpath.add_to_dictionary(dir_hashname,
                                      dir_name,
                                      "directory",
                                      os.getcwd(),
                                      fs_loc,
                                      mount=self.unionpath.current_mount)
     help_functions.hashify_entire_dir(dst_dir, self.unionpath)
     os.chdir(tmp)
     self.unionpath.current_folder = tmp
     return
コード例 #4
0
 def add_file_to_filesystem(self, source, destination=None):
     if ".uniondir" in source:
         print(color.red("Cannot add object from within the filesystem."))
         return
     if not destination:
         destination = self.unionpath.current_folder
     else:
         curr = self.unionpath.current_folder
         dirs = destination.split(os.sep)
         for dir in dirs:
             dir_hash = self.unionpath.translate_to_hash(dir, curr)
             if not dir_hash:
                 print("{} does not exist".format(destination))
                 return
             curr = os.path.join(curr, dir_hash)
         destination = curr
     filename, extension = self.unionpath.get_filename(source)
     hashname = self.unionpath.create_hash(source)
     path = shutil.copy2(source, destination)
     os.rename(path, path.replace(filename + extension, hashname))
     fs_loc = self.unionpath.hashpath_to_fspath(destination)
     print(color.cyan("{} {}".format(filename, extension)))
     self.unionpath.add_to_dictionary(hashname,
                                      filename,
                                      "file",
                                      destination,
                                      fs_loc,
                                      timestamp=None,
                                      extension=extension,
                                      mount=self.unionpath.current_mount)
     return "add {}".format(hashname)
コード例 #5
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
コード例 #6
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)))
コード例 #7
0
ファイル: operators.py プロジェクト: Kyrus1999/BACnet
    def unknown(self, cmds=None):
        '''
		USE:
		operators.unknown([optional: cmds_from_terminal])

		Description:
		when entered command is not known, this should be printed
		'''
        print(color.red("Unknown command"))
        print(color.grey("type --help to view the help section."))
コード例 #8
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
コード例 #9
0
ファイル: client.py プロジェクト: Kyrus1999/BACnet
 def client_thread(self):
     try:
         while True:
             message = self.conn.recv(2048)
             if message:
                 resp = self.protocol.handle(message.decode('utf-8'))
     except:
         print(
             color.red("Connection to {}@{} lost".format(
                 self.hash, self.IP)))
         self.conn.close()
         return
コード例 #10
0
 def send_file(self, src):
     try:
         with open(src, 'rb') as file:
             while True:
                 bytes = file.read()
                 if not bytes:
                     break
                 self.send_bytes(bytes)
             self.send_bytes(b'\EOF')
         return
     except:
         self.send_bytes(b'\INT')
         print(color.red("{} was not found.".format(src)))
         return
コード例 #11
0
 def open_file(self, file):
     if "." in file:
         file = file.split(".")[0]
     filehash = self.unionpath.translate_to_hash(
         file, self.unionpath.current_folder)
     if not filehash:
         print(color.red("The file {} does not exist".format(file)))
         return
     path = os.path.join(self.unionpath.current_folder, filehash)
     if os.path.isfile(path):
         self.unionpath.edit_dictionary(filehash, "timestamp")
         FNULL = open(os.devnull, 'w')
         subprocess.call(["xdg-open", path], stdout=FNULL, stderr=FNULL)
     else:
         self.change_directory(file)
コード例 #12
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")
コード例 #13
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
コード例 #14
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]
コード例 #15
0
ファイル: logger.py プロジェクト: zhl2008/blockchain-ex
 def error(word, debug_print=True):
     msg = "[-] %s\n" % color.red(log.beauty(word))
     if not debug_print:
         return
     log.my_log(msg, word)
コード例 #16
0
 def download_mount_partition(self, name):
     if not self.unionpath.connected:
         print(color.red("Please connect to a sever in order to mount."))
         return
     return "mnt {} {}".format("download", name)
コード例 #17
0
 def copy_within_filesystem(self, source, destination, keep=False):
     curr = self.unionpath.current_folder
     new_fs = []
     if os.sep in source:
         dirs = source.split(os.sep)
         source = curr
         for i in range(len(dirs)):
             dirs[i] = self.unionpath.translate_to_hash(
                 dirs[i], source, False)
             if not dirs[i]:
                 print(color.red("Location does not exist."))
                 return
             source = os.path.join(source, dirs[i])
     else:
         source = os.path.join(
             curr, self.unionpath.translate_to_hash(source, curr, False))
     if os.sep in destination:
         dirs = destination.split(os.sep)
         destination = curr
         for i in range(len(dirs)):
             dirs[i] = self.unionpath.translate_to_hash(
                 dirs[i], destination, False)
             if not dirs[i]:
                 print(color.red("Location does not exist."))
                 return
             destination = os.path.join(destination, dirs[i])
     else:
         destination = os.path.join(
             curr, self.unionpath.translate_to_hash(destination, curr,
                                                    False))
     if os.path.isdir(source):
         src_info = self.unionpath.translate_from_hash(
             source.split(os.sep)[-1])
         src_name, src_type = src_info[0], src_info[2]
         self.unionpath.current_folder = destination
         root_cpy_hash = self.unionpath.create_hash(
             os.path.join(curr, src_name))
         dst_path = shutil.copytree(
             source, os.path.join(destination, root_cpy_hash))
         fs_loc = self.unionpath.hashpath_to_fspath(destination)
         self.unionpath.add_to_dictionary(root_cpy_hash, src_name,
                                          "directory", destination, fs_loc)
         new_fs = help_functions.assign_new_hashes_dir(
             dst_path, self.unionpath)
         if not keep:
             hashes = [source.split(os.sep)[-1]]
             for (dirpath, dirnames, filenames) in os.walk(source):
                 hashes.extend(filenames)
                 hashes.extend(dirnames)
             shutil.rmtree(source)
             if hashes:
                 for file in hashes:
                     self.unionpath.edit_dictionary(file, 'del')
     elif os.path.isfile(source):
         src_info = self.unionpath.translate_from_hash(
             source.split(os.sep)[-1])
         src_hash, src_name, src_type, src_extension = src_info[
             4], src_info[0], src_info[2], src_info[5]
         self.unionpath.current_folder = destination
         file_path = shutil.copy2(source, destination)
         hashname = self.unionpath.create_hash(file_path)
         fs_loc = self.unionpath.hashpath_to_fspath(destination)
         os.rename(file_path, file_path.replace(src_hash, hashname))
         self.unionpath.add_to_dictionary(hashname, src_name, "file",
                                          destination, fs_loc,
                                          src_extension)
         new_fs.append("{} {} {}".format(src_hash, hashname, fs_loc))
         if not keep:
             self.unionpath.edit_dictionary(src_hash, 'del')
             os.remove(source)
     if keep:
         keep = "COPY "
         prepenc = "cp"
     else:
         keep = "MOVE "
         prepend = "mv"
     for i in range(len(new_fs)):
         new_fs[i] = keep + new_fs[i]
     self.unionpath.current_folder = curr
     os.chdir(self.unionpath.current_folder)
     return prepend, new_fs
コード例 #18
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
コード例 #19
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])
コード例 #20
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
コード例 #21
0
def failure_handler(request_type, name, response_time, response_length,
                    exception, **kw):
    if "DEBUG" not in os.environ or os.environ["DEBUG"] != "yes":
        return
    msg = f"Request {name} ({request_type}) failed: {exception}"
    print(color.red(msg), flush=True)