Exemplo n.º 1
0
 def remove(self, msg_spl):
     curr = msg_spl[1]
     hash = msg_spl[2]
     extension = msg_spl[3]
     if extension == "None":
         extension = ""
     print(color.purple(curr))
     print(color.purple(hash))
     if curr.__eq__("root"):
         loc = self.root_dir
     else:
         loc = self.root_dir + curr
     loc = os.path.join(loc, hash)
     if "." in extension:
         loc += extension
     if os.path.isfile(loc):
         print(loc)
         os.remove(loc)
         self.edit_content_file(hash, 'del')
         return "CREM"
     elif os.path.isdir(loc):
         shutil.rmtree(loc)
         return "CREM"
     else:
         print("NOT A FILE {}".format(loc))
         return "DREM"
Exemplo n.º 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))))
Exemplo n.º 3
0
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
Exemplo n.º 4
0
def logo():
    line = "                            `://///    ://///:                              \n"
    line += "                         `+dmmmmmms   `mmmmmmo   .`                         \n"
    line += "                        `dmmmmmmmm.   +mmmmmm-   od`                        \n"
    line += "                        smmmmmmmmy    dmmmmmm    hms                        \n"
    line += "                        hmmmmmmmm-   :mmmmmms   `mmh                        \n"
    line += "                        hmmmmmmm:   `mmmmmmm`   +mmh                        \n"
    line += "                        hmmmmmmm:   `mmmmmmm`   +mmh                        \n"
    line += "                        hmmmmmmh    +mmmmmmy    ymmh                        \n"
    line += "                        hmmmmmm+    ymmmmmm-   `mmmh                        \n"
    line += "                        hmmmmmm:    /mmmmd/    ommmh                        \n"
    line += "                        hmmmmmm/     .::-     :mmmmh                        \n"
    line += "                        smmmmmmd`            +mmmmms                        \n"
    line += "                        `hmmmmmmd/`       .+dmmmmmh`                        \n"
    line += "                          /hmmmmmmmhyssyhmmmmmmmh/                          \n"
    line += "                            `-://////////////:-`                            \n"
    line = color.purple(line)
    return line
Exemplo 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)))
Exemplo n.º 6
0
 def get_file(self, msg_spl):
     flag = False
     src = msg_spl[1]
     dst = msg_spl[2]
     print(color.purple("ADD {} {}".format(src, dst)))
     dir = self._get_dir(dst)
     filename = self._get_filename(src)
     extension = os.path.splitext(filename)[1]
     path = os.path.join(self.hash, dir)
     filepath = create.file_path_in_filesystem(os.path.join(path, filename))
     print(color.green(filename))
     with open(filepath, "wb") as file:
         while True:
             bytes = self.conn.recv(BUFFER_SIZE)
             file.write(bytes)
             if bytes.strip()[-3:] == b'EOF':
                 break
             elif bytes.strip()[-3:] == b'INT':
                 flag = True
                 break
         file.close()
     if flag:
         os.remove(filepath)
         return "NCADD"
     timestamp = math.trunc(datetime.timestamp(datetime.now()))
     hashname = hash_.get_hash_from_string(filepath + str(timestamp))
     new_filepath = filepath.replace(filename,
                                     "{}{}".format(hashname, extension))
     timestamp = self.add_to_dict(hashname,
                                  filename,
                                  "file",
                                  extension=extension,
                                  timestamp=timestamp)
     os.rename(filepath, new_filepath)
     try:
         os.remove(filepath)
     except:
         None
     return "CADD {} {}".format(hashname, timestamp)
Exemplo n.º 7
0
 def print_client_properties(self):
     print(color.purple(self.hash))
     print(color.purple(self.root_dir))
     print(Path.home())
     print(color.purple(self.fs_content_file))
Exemplo n.º 8
0
 def mount(self, msg_spl):
     try:
         user = msg_spl[1]
         user_hash = msg_spl[2]
         fs_name = msg_spl[3]
         clientlist = create.get_json_content(self.client_list_path)
         user_matches = ""
         for reg_hash in clientlist:
             if reg_hash != user_hash and clientlist.get(
                     reg_hash)['user'] == user:
                 user_matches += "[\"{}\",\"{}\",\"{}\"],".format(
                     reg_hash,
                     clientlist.get(reg_hash)['user'],
                     clientlist.get(reg_hash)['ip'])
         user_matches = "[" + user_matches + "]"
         user_matches = user_matches.replace("],]", "]]")
         self.send(user_matches)
         user = self.conn.recv(2014)
         user = user.decode("utf-8")
         serverlist = create.get_json_content(self.filesystem_list_path)
         fs_of_user = serverlist.get(user)
         json_loc = ""
         fs_root = ""
         if fs_of_user:
             fs = fs_of_user.get(fs_name)
             if fs:
                 json_loc = fs['content_json']
                 fs_root = fs['root']
                 fs = json_loc.split(os.sep)[-1].replace(".json", "")
                 fs = "{}".format(fs)
             else:
                 fs = "None"
         else:
             fs = "None"
         timestamp = math.trunc(datetime.timestamp(datetime.now()))
         info = "DIR {} {}".format(fs, timestamp)
         self.send(info)
         notification = self.conn.recv(2014)
         notification = notification.decode("utf-8")
         if notification != "DIR_DONE":
             self.send("DMNT")
             return "DMNT"
         dirs, files = self._get_dirs_and_files(fs_root, json_loc)
         if not dirs:
             self.send("DMNT")
             return "DMNT"
         file_hashes = [
             re.sub('[.][^.]+$', '',
                    x.split(os.sep)[-1]) for x in files
         ]
         if not dirs:
             self.send("DMNT")
             return "DMNT"
         content_info = create.get_json_content(json_loc)
         for dir in dirs:
             dir_hash = dir.split(os.sep)[-1]
             obj = content_info.get(dir_hash)
             name = obj['name']
             time = obj['time']
             type = obj['type']
             info = "DIR {} {} {} {} {} ".format(dir.replace(fs_root, ""),
                                                 dir_hash, name, time, type)
             self.send(info)
             notification = self.conn.recv(2014)
         print("SEND DIR_DONE")
         self.send("DIR_DONE")
         notification = self.conn.recv(2014)
         notification = notification.decode("utf-8")
         if not notification == "DIRS_DONE":
             self.send("DMNT")
             return "DMNT"
         for i in range(len(files)):
             obj = content_info.get(file_hashes[i])
             name = obj['name']
             time = obj['time']
             type = obj['type']
             extension = obj['extension']
             if extension == "":
                 extension = "None"
             info = "FILE {} {} {} {} {} {}".format(
                 files[i].replace(fs_root, "")[1:], file_hashes[i], name,
                 time, type, extension)
             print(color.purple(info))
             self.send(info)
             notification = self.conn.recv(5)
             notification = notification.decode("utf-8")
             if not notification == "CFILE":
                 self.send("DMNT")
                 return "DMNT"
             else:
                 self.send_file(files[i])
                 notification = self.conn.recv(6)
                 notification = notification.decode("utf-8")
                 if not notification == "CCFILE":
                     self.send("DMNT")
                     return "DMNT"
         self.send("CMNT")
         return "CMNT"
     except:
         self.send("DMNT")
         return "DMNT"
Exemplo n.º 9
0
 def success(word, debug_print=True):
     msg = "[+] %s\n" % color.purple(log.beauty(word))
     if not debug_print:
         return
     log.my_log(msg, word)
Exemplo n.º 10
0
 def list_folder_content(self, paths, arg=None, additional=False):
     dir_icon = "📁"
     file_icon = "📄"
     mount_icon = "💾"
     img_icon = "🖼"
     music_icon = "🎵"
     movie_icon = "🎥"
     name, time, type, location, hash, extension, fs_path, mount = 0, 1, 2, 3, 4, 5, 6, 7
     f_list = []
     d_list = []
     mounts = self.unionpath.edit_mount_list(op='get', property='mounts')
     for p in paths:
         if p[type] == 'file':
             f_list.append(p)
         elif p[type] == 'directory':
             d_list.append(p)
     paths = f_list + d_list
     if arg:
         print('\n-------------------')
     if not additional:
         for p in paths:
             if p[type] == 'file':
                 icon = file_icon
                 if p[extension] in [
                         ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".eps"
                 ]:
                     icon = img_icon
                 elif p[extension] in [".mp3", ".wav", ".flac", ".aac"]:
                     icon = music_icon
                 elif p[extension] in [".mp4", ".mov", ".avi", ".wmv"]:
                     icon = movie_icon
                 if extension != "":
                     print("{}  ".format(icon) +
                           color.purple(p[name] + p[extension]))
                 else:
                     print("{}  ".format(icon) + color.purple(p[name]))
             elif p[type] == 'directory':
                 icon = dir_icon
                 if p[hash] in mounts:
                     icon = mount_icon
                 print("{}  ".format(icon) + color.blue(p[name]))
     else:
         for p in paths:
             date = datetime.datetime.fromtimestamp(int(
                 p[time])).strftime('%m/%d/%Y %H:%M:%S')
             if p[type] == 'file':
                 if p[type] == 'file':
                     icon = file_icon
                     if p[extension] in [
                             ".png", ".jpg", ".jpeg", ".bmp", ".gif", ".eps"
                     ]:
                         icon = img_icon
                     elif p[extension] in [".mp3", ".wav", ".flac", ".aac"]:
                         icon = music_icon
                     elif p[extension] in [".mp4", ".mov", ".avi", ".wmv"]:
                         icon = movie_icon
                 if not str(p[extension]):
                     add_info = color.cyan(
                         " \tDate: {}  \tFingerprint: {}".format(
                             date, p[time]))
                 else:
                     add_info = color.cyan(
                         " \tType: {}  \tDate: {}  \tFingerprint: {}".
                         format(p[extension], date, p[time]))
                 if extension != "":
                     print("{}  ".format(icon) +
                           color.purple(p[name] + p[extension]) + add_info)
                 else:
                     print("{}  ".format(icon) + color.purple(p[name]) +
                           add_info)
             elif p[type] == 'directory':
                 icon = dir_icon
                 if p[hash] in mounts:
                     icon = mount_icon
                 add_info = color.cyan(
                     " \tDate: {}  \tFingerprint: {}".format(date, p[time]))
                 print("{}  ".format(icon) + color.blue(p[name]) + add_info)
     if arg:
         print('\n-------------------')
Exemplo n.º 11
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
Exemplo n.º 12
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])