Exemplo n.º 1
0
class Cmd:
    def __init__(self):
        """Sets up the command line parameters. Needs to be ran with
        self.run(). Loads a file in the same directory with the name
        default_dictionary.txt."""
        self.in_text = ""
        self.out_text = ""
        self.variant = ""
        self.key = 0
        self.mode = ""
        self.cipher = 0
        self.active_dict = 0

        self.cmds = {
            "help": self.help,
            "open": self.open_file,
            "export": self.write_file,
            "add dict": self.add_dict,
            "change dict": self.change_dict,
            "start": self.start,
            "sayoonara": self.quit,
        }

        self.dicts = {}
        self._set_default_dictionary()

    def run(self):
        comm = input("--> ")
        while comm != "sayoonara":
            if comm in self.cmds:
                self.cmds[comm]()
            else:
                self.help()
            comm = input("--> ")

    def start(self):
        """Starts up a process to encrypt/decrypt/hack some shit."""

        self.variant = self.command_wrapper(
            ("Which encryption scheme do you want" "to use? (caesar or transpos) > "), 0, ["caesar", "transpos"]
        )

        self.mode = self.command_wrapper(
            ("Do you want to encrypt, decrypt or hack the" "source text? > "), 0, ["encrypt", "decrypt", "hack"]
        )

        if self.mode != "hack":
            self.key = self.command_wrapper("Please provide a key for the job. > ", 0, "isint")

        if self.in_text == "":
            self.open_file()

        self._setup_crypt()
        self._run_crypt()

        self.out_text = self.cipher.ret_out_text()
        self.write_file()

    def quit(self):
        sys.exit(0)

    def help(self):
        """Displays moderately useful help messages."""
        print(
            'You can quit this program with "sayoonara".\n'
            'You can get help, with "help".\n'
            'To start the encryption, type "start"\n'
            'You can export the last result with "export".\n'
            'Add a new dicionary with "add dict".\n'
            'Change the default via "change dict".\n'
        )

    def open_file(self):
        """Opens, and reads a file in a class variable for further
        use, if it exists."""
        path = self.command_wrapper("Please enter the file's path you want to open. > ", 0, "ospath")
        with open(path, "r") as content:
            self.in_text = content.read()
        print("File loaded.")

    def write_file(self):
        """Opens and writes to a user provided file the contents
        current of the current outfile buffer."""
        path = input("Please enter the file's path you want to write. > ")
        if os.path.exists(path):
            ans = input("This file already exist, do you want to" "overwrite it (y, n or quit)? > ")
            if ans[0].upper() == "Y":
                with open(path, "w") as output_file:
                    output_file.write(self.out_text)
                print("Done.")
            elif ans[0].upper() == "N":
                self.write_file()
            else:
                return
        else:
            output_file = open(path, "w")
            output_file.write(self.out_text)
            output_file.close()
            print("Done.")

    def add_dict(self):
        name = input("Please provide a name for your dictionary. > ")
        path = input("Please provide a path to your dictionary. > ")
        if os.path.exists(path):
            dict_name = "user_dict" + str(len(self.dicts) + 1)
            exec(dict_name + " = Dictionary(path)")
            self.dicts[name] = eval(dict_name)
            self.active_dict = self.dicts[name]
            print("Done.")
        else:
            if (
                input(
                    "No such file.\
            Do you want to try again? (y/N) >"
                ).upper
                == "Y"
            ):
                self.add_dict()

    def change_dict(self):
        print("These are the current dictionaries: ")
        for key in self.dicts.keys():
            print(key)
        if input("Do you want to add a new one? > ").upper == "Y":
            self.add_dict()
        else:
            user_choice = input("Which one would you like to use? > ")
            if user_choice in self.dicts:
                self.active_dict = self.dicts[user_choice]
            elif (
                input(
                    "I don't know that one.\
            Try again? (y/N) > "
                ).upper
                == "Y"
            ):
                self.change_dict()

    # Internal helpers
    # TODO: find out what's up with sys paths. It will work with my setup
    # but not with everyone else's.
    def _set_default_dictionary(self, path="/home/cs/Devel/hacking-secret-ciphers/dicts/dictionary.txt"):

        self.def_dict = path
        if os.path.exists(self.def_dict):
            self.english_def = Dictionary(self.def_dict)
            self.dicts["default"] = self.english_def
            self.active_dict = self.english_def
            print("Default dictionary set.")
        else:
            print("No default dictionary set.")

    def _print_dicts(self):
        for key in self.dicts.keys():
            print(key)

    def _setup_crypt(self):
        if self.variant == "caesar":
            self.cipher = Caesar(self.in_text, self.key)
        if self.variant == "transpos":
            self.cipher = Transpos(self.in_text, self.key, self.active_dict)

    def _run_crypt(self):
        if self.mode == "encrypt":
            self.cipher.encrypt()
        if self.mode == "decrypt":
            self.cipher.decrypt()
        if self.mode == "hack":
            self.cipher.hack()

    # TODO: tell user if it's a directory.
    def command_wrapper(self, input_text="", var=0, commands=0):
        if var == 0:
            var = input(input_text)
        if commands == 0:
            return var
        elif commands == "ospath":
            if os.path.exists(var):
                return var
            else:
                var = input("No such file. Want to try agatin, or (q)uit? > ")
                quit_seq(var)
                self.command_wrapper("", var, commands)
        elif commands == "isint":
            if isint(var):
                return var
            else:
                var = input("It's not an integer. Try again, or (q)uit? > ")
                quit_seq(var)
                self.command_wrapper("", var, "isint")
        else:
            if var != commands:
                var = input("Didn't quite catched that. Try again or (q)uit? > ")
                quit_seq(var)
                self.command_wrapper(input_text, var, commands)
Exemplo n.º 2
0
 def _setup_crypt(self):
     if self.variant == "caesar":
         self.cipher = Caesar(self.in_text, self.key)
     if self.variant == "transpos":
         self.cipher = Transpos(self.in_text, self.key, self.active_dict)