Exemplo n.º 1
0
class Save_Local_File():
    def __init__(self, local_path, name, folder=False, **kwargs):
        #super(Save_File, self).__init__()
        self.folder = folder
        self.path = local_path
        self.name = name
        self.files = roboprinter.printer_instance._file_manager.list_files(
            recursive=True)['local']
        layout = self.make_folder_screen(self.files)
        back_destination = str(roboprinter.robo_screen())
        Logger.info(back_destination)
        roboprinter.back_screen(
            name="local",
            title=roboprinter.lang.pack['Files']['Save_File']['Title'],
            back_destination=back_destination,
            content=layout,
            cta=self.save,
            icon='Icons/Slicer wizard icons/Save.png')

    def make_folder_screen(self, files):
        buttons = []
        folders = []

        for entry in files:
            if files[entry]['path'] != self.path:
                if files[entry]['type'] == 'folder':
                    #if the USB isn't mounted don't show it as an option
                    if entry == "USB":
                        if 'usb_mounted' in session_saver.saved:
                            if session_saver.saved['usb_mounted']:
                                folders.append(
                                    self.create_folder_button(
                                        entry, files[entry]['path']))
                    else:
                        folders.append(
                            self.create_folder_button(entry,
                                                      files[entry]['path']))

        return Scroll_Box_Even(folders)

    def create_folder_button(self, folder_name, path):
        # folder buttons need to be able to access their folders children
        split_path = path.split('/')
        return FolderButton(folder_name, split_path, self.folder_screen)

    def folder_screen(self, name, path):
        _name = name
        back_destination = str(roboprinter.robo_screen())
        Logger.info(back_destination)

        files = self._grab_files_in_folder(path)

        layout = self.make_folder_screen(files)

        roboprinter.back_screen(name="ROBOSAVE" + "/".join(path),
                                title=_name,
                                back_destination=back_destination,
                                content=layout,
                                cta=self.save,
                                icon='Icons/Slicer wizard icons/Save.png')

    #have to add *args and **kwargs because of the backbutton screen
    def save(self, *args, **kwargs):
        self.wp = Warning_Popup(
            roboprinter.lang.pack['Files']['Warning']['Title'],
            roboprinter.lang.pack['Files']['Warning']['Body'])
        self.wp.open()

        Clock.schedule_once(self._save, 0)

    def _save(self, dt):
        save_dir = roboprinter.robo_screen()
        save_dir = save_dir.replace("ROBOSAVE", "")

        if save_dir == 'local':
            save_dir = FILES_DIR
            short_dir = 'local/'
        else:
            short_dir = save_dir + "/"
            save_dir = roboprinter.printer_instance._file_manager.path_on_disk(
                'local', save_dir)

        file_path = roboprinter.printer_instance._file_manager.path_on_disk(
            'local', self.path)

        try:
            Logger.info(file_path + " " + save_dir)

            shutil.move(file_path, save_dir)

        except Exception as e:
            Logger.info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " + str(e))
            traceback.print_exc()

            ep = Error_Popup(
                roboprinter.lang.pack['Files']['Move_Error']['Title'],
                roboprinter.lang.pack['Files']['Move_Error']['Body'],
                callback=partial(roboprinter.robosm.go_back_to_main,
                                 tab='printer_status_tab'))
            ep.open()

        Logger.info('File Saved/Removed')
        roboprinter.robosm.go_back_to_main('files_tab')

        #add a 2 second delay for updating files
        Clock.schedule_once(self.update_files, 2)
        self.wp.dismiss()

    def update_files(self, dt):
        if 'file_callback' in session_saver.saved:
            session_saver.saved['file_callback']()

    def _grab_files_in_folder(self, path):
        folder = self.files

        # Every iteration makes the folder variable smaller
        for directory in path:
            folder = folder[directory]['children']

        return folder
Exemplo n.º 2
0
class UpdateScreen(FloatLayout):
    installed_version = StringProperty(roboprinter.lang.pack['Update_Printer']['Checking'])
    avail_version = StringProperty(roboprinter.lang.pack['Update_Printer']['Checking'])

    def __init__(self, populate=True, **kwargs):
        super(UpdateScreen, self).__init__()

        self.data_path = roboprinter.printer_instance.get_plugin_data_folder()

        self.repo_info_url = 'https://api.github.com/repos/mcecchi/Update_Script/releases'
        self.repo_local_path = self.data_path + '/Update_Script'
        self.updater_path = self.repo_local_path + '/Update_Checker/Update_Checker.py'
        self.repo_remote_path = 'https://github.com/mcecchi/Update_Script.git'
        self.versioning_path = self.data_path + '/roboOS.txt'

        self.printer_model = roboprinter.printer_instance._settings.get(['Model'])

        #populate version numbers when screen gets initiated
        self.populate = populate
        if self.populate:
            Clock.schedule_once(self.populate_values)

    def populate_values(self, *args):
        self.refresh_versions()
        self.refresh_button()

    def refresh_button(self, *args):
        if self.installed_version < self.avail_version and self.avail_version != roboprinter.lang.pack['Update_Printer']['Connection_Error']:
            self.enable_me()
        else:
            self.disable_me()

    def refresh_versions(self, *args):
        """populates self.installed_version && self.avail_version: values are rendered on the UpdateScreen."""
        self.installed_version = self.get_installed_version()
        self.avail_version = self.get_avail_version()
        if self.avail_version == roboprinter.lang.pack['Update_Printer']['Connection_Error'] and self.populate:
            Error_Popup(roboprinter.lang.pack['Update_Printer']['Connect_Error']['Title'], roboprinter.lang.pack['Update_Printer']['Connect_Error']['Body'],callback=partial(roboprinter.robosm.go_back_to_main, tab='printer_status_tab')).show()

    def get_installed_version(self):
        path = self.versioning_path
        if os.path.exists(path):
            with open(path, 'r') as f:
                v = f.readline().strip()
        else:
            with open(path, 'w') as f:
                v = '1.0.3'
                f.write(v)
        return v

    def get_avail_version(self):
        """queries github api for repo's latest release version"""
        try:
            r = requests.get(self.repo_info_url)
            code = r.status_code
        except Exception as e:
            r = None
            code = None
        if r and code is 200:
            return self._get_avail_version(r.json())
        else:
            return roboprinter.lang.pack['Update_Printer']['Connection_Error']

    def _get_avail_version(self, r):
        # parse json response for latest release version
        #model = 'r2' if self.printer_model == 'Robo R2' else 'c2'
        model = ''
        versions = map(lambda info: info.get('tag_name', '0'), r)
        m_versions = filter(lambda v: model in v, versions)
        if len(m_versions) > 1:
            m_versions.sort()
            avail = m_versions.pop()
        elif len(m_versions) == 1:
            avail = m_versions.pop()
        else:
            avail = self.installed_version
        return avail

    def update_updater(self, *args):
        #if self.printer_model == 'Robo R2':
        #    branch = 'r2'
        #else:
        #    branch = 'c2'
        branch = 'master'

        if os.path.exists(self.repo_local_path):
            def del_rw(action, name, exc):
                os.chmod(name, stat.S_IWRITE)
                os.remove(name)
            # start fresh every time to avoid potential corruptions or misconfigurations
            rmtree(self.repo_local_path, onerror=del_rw)
        Repo.clone_from(self.repo_remote_path, self.repo_local_path, branch=branch)

    def run_updater(self, *args):
        self.disable_me()
        self.warning = Warning_Popup(roboprinter.lang.pack['Update_Printer']['Loading']['Title'], roboprinter.lang.pack['Update_Printer']['Loading']['Body'])
        self.warning.show()
        execute = lambda funcs, dt: map(lambda f: f(), funcs)
        series = [self.update_updater, self._run_updater]
        Clock.schedule_once(partial(execute, series))

    def _run_updater(self):
        from multiprocessing import Process, Pipe
        import subprocess
        import time

        output_p, input_p = Pipe()
        Update_Checker = imp.load_source('Update_Checker', self.updater_path).Update_Checker
        Logger.info('!!!!UPDATING!!!!')
        p = Process(
            target=Update_Checker,
            args=(
                self.versioning_path,
                (output_p, input_p),
            )
        )
        p.start()
        input_p.close()
        # receive message from updater on update status
        while True:
            try:
                updating = output_p.recv()
                Logger.info('MESSAGE: {}'.format(updating))
            except EOFError:
                break
        if updating:
            # kill parent process Octoprint
            subprocess.call("sudo service octoprint stop".split(' '))
        else:
            p.join()
            self.populate_values()
            self.warning.dismiss()
            Error_Popup(roboprinter.lang.pack['Update_Printer']['No_Update']['Title'], roboprinter.lang.pack['Update_Printer']['No_Update']['Body'],callback=partial(roboprinter.robosm.go_back_to_main, tab='printer_status_tab')).show()

    def disable_me(self):
        self.ids.updatebtn.disabled = True
        self.ids.updatebtn.canvas.ask_update()
        # Clock.schedule_once(self.run_updater)
    def enable_me(self):
        self.ids.updatebtn.disabled = False
        self.ids.updatebtn.canvas.ask_update()