Пример #1
0
 def search(self, text: tk.Text, tag: str, master: tk.Frame) -> None:
     """
     Search the document for a certain string and mark it
     :param text: The text field to search
     :param tag: The tag to highlight the text with
     :param master: The main window
     :type text: tk.Text
     :type tag: str
     :type master: tk.Frame
     """
     dialog = search_dialog.SearchDialog(master)
     master.wait_window(dialog.top)
     keyword = master.received_data
     pos = '1.0'
     while True:
         countVar = tk.StringVar()
         idx = text.search(keyword,
                           pos,
                           tk.END,
                           regexp=master.search_with_regex,
                           count=countVar,
                           nocase=master.ignore_case)
         if not idx:
             break
         pos = f'{idx}+{countVar.get()}c'
         text.tag_add(tag, idx, pos)
Пример #2
0
 def help(self, master: tk.Frame) -> None:
     """
     Show the help menu
     :param master: The main window of which the help window is a child
     :type master: tk.Frame
     """
     window = help.HelpWindow(master)
     master.wait_window(window.top)
Пример #3
0
 def settings(self, master: tk.Frame) -> None:
     """
     Show the settings menu
     :param master: The main window of which the settings window is a child
     :type master: tk.Frame
     """
     window = settings.SettingsMenu(master)
     master.wait_window(window.top)
Пример #4
0
class Config:
    config_file = './config.yml'
    server = 'login.somewhere.some_uni.de'
    username = '******'
    file_path = ''

    version = 1.0
    key_file = ''
    _tkinter_vars = {}
    file_encoding = 'utf-8'
    file_name = '.vacation.txt'
    module_version = '0.1.5'
    github_api = "https://api.github.com/"
    github_url = "https://github.com/"
    github_api_repo = github_api + "repos/trigrab/tf-vacation-manager/"
    github_repo = github_url + "trigrab/tf-vacation-manager/"

    def __init__(self):
        self.config_file = self.find_config_file()
        self.working_directory = os.path.dirname(self.config_file)
        self.file_name_path = os.path.join(self.working_directory,
                                           self.file_name)
        self.read()
        self.main = None
        self.root = None

    def create(self, tk_root=None):
        self._tkinter_vars['vars'] = {}

        self.root = Tk() if tk_root is None else Toplevel(tk_root)
        self.main = Frame(self.root, pady=15, padx=15)
        self.main.pack(expand=True, fill="both")

        for key in self.get_save_member_list():
            value = getattr(self, key)
            Label(self.main, justify="left", text=key).pack(anchor="w",
                                                            pady=(15, 0))
            self._tkinter_vars['vars'][key] = StringVar()
            self._tkinter_vars['vars'][key].set(value)
            ttk.Entry(self.main,
                      textvariable=self._tkinter_vars['vars'][key],
                      width=100).pack(anchor="w")

        ttk.Button(self.main, text='Save',
                   command=self.save).pack(anchor="w", pady=(15, 0))

        self.main.wait_window(self.main)

    def get_save_member_list(self, for_saving=False):
        member_list = []
        for key in dir(Config):
            if key in static_parameters:
                continue
            if hasattr(self, key):
                if not key.startswith('_') and not callable(getattr(self, key)) and \
                        key is not None and getattr(self, key) is not None:
                    if key == 'vars' or key == 'config_file':
                        continue
                    if not for_saving and key == 'version':
                        continue
                    member_list.append(key)
        return member_list

    def save(self):
        for key in self.get_save_member_list():
            value = self._tkinter_vars['vars'][key].get()
            # if isinstance(value, str):
            # if value[:2] == './':
            #     value = os.getcwd() + value
            if hasattr(self, key):
                setattr(self, key, value)

        if self.key_file is None or self.key_file == '':
            self.key_file = os.path.join(os.path.expanduser('~'), '.ssh',
                                         'id_rsa')

        print('write config to:', self.config_file)

        with open(self.config_file, 'w',
                  encoding=self.file_encoding) as config_file:
            yml_dict = {}
            for key in self.get_save_member_list(for_saving=True):
                yml_dict[key] = getattr(self, key)
                if yml_dict[key] == '':
                    yml_dict[key] = None
            dump(yml_dict, config_file)

        self.main.destroy()
        self.root.destroy()

    def find_config_file(self):
        if os.path.exists(self.config_file):
            return self.config_file

        app_data = os.getenv('APPDATA')
        home_dir = os.path.expanduser('~')
        if app_data is not None and os.path.exists(app_data):
            #app_data += '/.tf-vacation-manager/config.yml'
            app_data = os.path.join(app_data, '.tf-vacation-manager',
                                    'config.yml')
            if os.path.exists(app_data):
                return app_data
            elif home_dir is None or not os.path.exists(
                    os.path.join(home_dir, '.tf-vacation-manager')):
                os.mkdir(os.path.dirname(app_data))
                return app_data
        else:
            if home_dir is not None:
                if not os.path.exists(
                        os.path.join(home_dir, '.tf-vacation-manager')):
                    os.mkdir(os.path.join(home_dir, '.tf-vacation-manager'))
                return os.path.join(home_dir, '.tf-vacation-manager',
                                    'config.yml')

        return self.config_file

    def read(self):
        if os.path.exists(self.config_file):
            with open(self.config_file, 'r+') as config_file:
                config_yml = load(config_file)

                for key, value in config_yml.items():
                    if key == 'version':
                        continue
                    if hasattr(self, key):
                        setattr(self, key, value)

                if config_yml['version'] != self.version:
                    self.create()
        else:
            self.create()
class FileNetworkManager:

    def __init__(self, server, username, tk_root, key_filename=None, password=None):
        self.tk_root = tk_root
        self.root = None
        self.server = server
        self.username = username
        self.key_filename = key_filename
        self.password = password
        self.password_field = StringVar()
        self.main_frame = None

    def close_password_input_window(self):
        self.main_frame.destroy()
        self.root.destroy()
        self.password = self.password_field.get()
        self.key_filename = None
        self.connect_to_server()

    def close_and_upload_key(self):
        public_keyfile_name = self.key_filename
        self.close_password_input_window()
        self.key_filename = public_keyfile_name
        public_keyfile_name += ".pub"
        with open(public_keyfile_name, 'r') as key:
            key = key.readline()
            # print('echo "' + key + '" >> .ssh/authorized_keys')
            if self.ssh is None:
                return
            self.ssh.exec_command('echo "' + key + '" >> .ssh/authorized_keys')


    def window_closed(self):
        self.main_frame.destroy()
        self.root.destroy()
        self.ssh = None

    def create(self):

        self.root = Toplevel(self.tk_root)
        self.main_frame = Frame(self.root, pady=15, padx=15)
        self.main_frame.pack(expand=True, fill="both")

        Label(self.main_frame, justify="left", text="Password").pack(anchor="w", pady=(15, 0))
        ttk.Entry(self.main_frame,
                  textvariable=self.password_field,
                  width=100, show='*').pack(anchor="w")

        ttk.Button(self.main_frame, text='Connect', command=self.close_password_input_window).pack(side=LEFT, pady=(15, 0))
        ttk.Button(self.main_frame, text='Connect and upload Key', command=self.close_and_upload_key).pack(side=RIGHT,
                                                                                                   pady=(15, 0))
        self.root.protocol("WM_DELETE_WINDOW", self.window_closed)
        self.main_frame.wait_window(self.main_frame)


    def connect_to_server(self):
        self.ssh = SSHClient()

        self.ssh.set_missing_host_key_policy(AutoAddPolicy())
        # print("Load key file:", os.path.abspath(self.key_filename))
        if self.key_filename is not None and not os.path.isfile(self.key_filename):
            generate_key(self.key_filename)
        # ssh.load_system_host_keys()
        try:
            self.ssh.connect(self.server, username=self.username, key_filename=self.key_filename,
                             password=self.password, look_for_keys=False)
        except AuthenticationException as e:
            print("Could not connect to server")
            print(e)
            self.create()
        except SSHException as e:
            print("Could not connect to server")
            print(e)
            self.create()
        except FileNotFoundError as e:
            print('No keyfile')
            print(e)
            self.create()
        except NoValidConnectionsError as e:
            print("No valid connection")
            self.create()

    def upload_vacation_file(self, filename):
        self.connect_to_server()
        if self.ssh is None:
            return False

        scp = SCPClient(self.ssh.get_transport())
        scp.put(filename)
        scp.close()
        return True

    def delete_vacation_file(self, filename):
        self.connect_to_server()

        if self.ssh is None:
            return False
        # ssh.set_missing_host_key_policy(AutoAddPolicy())
        self.ssh.exec_command('rm ' + filename)

        return not self.check_if_vacation_exists(filename)

    def check_if_vacation_exists(self, filename):
        self.connect_to_server()
        if self.ssh is None:
            return False
        _, stdout, error = self.ssh.exec_command('test -f "' + filename + '" && echo "True"')
        response = stdout.read()
        # print(response)
        if response != b'':
            return True
        else:
            return False