diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml index a3a8fea9d..1a86bb0c6 100644 --- a/.github/workflows/trigger_docker.yml +++ b/.github/workflows/trigger_docker.yml @@ -12,7 +12,7 @@ on: jobs: dispatch_releases: runs-on: ubuntu-latest - if: github.event_name != 'push' + if: github.repository == 'OctoPrint/OctoPrint' && github.event_name != 'push' steps: - name: ๐Ÿš€ Repository Dispatch uses: peter-evans/repository-dispatch@v1 @@ -24,7 +24,7 @@ jobs: dispatch_canary: runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/maintenance' + if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/maintenance' steps: - name: ๐Ÿš€ Repository Dispatch uses: peter-evans/repository-dispatch@v1 @@ -36,7 +36,7 @@ jobs: dispatch_bleeding: runs-on: ubuntu-latest - if: github.event_name == 'push' && github.ref == 'refs/heads/devel' + if: github.repository == 'OctoPrint/OctoPrint' && github.event_name == 'push' && github.ref == 'refs/heads/devel' steps: - name: ๐Ÿš€ Repository Dispatch uses: peter-evans/repository-dispatch@v1 diff --git a/.github/workflows/trigger_docs.yml b/.github/workflows/trigger_docs.yml index 6a4fc565c..492d5ef5b 100644 --- a/.github/workflows/trigger_docs.yml +++ b/.github/workflows/trigger_docs.yml @@ -9,6 +9,7 @@ on: jobs: trigger: runs-on: ubuntu-latest + if: github.repository == 'OctoPrint/OctoPrint' steps: - name: ๐Ÿš€ Repository Dispatch uses: peter-evans/repository-dispatch@v1 diff --git a/.versioneer-lookup b/.versioneer-lookup index d6191b42b..6f5e25bb4 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,11 +18,11 @@ prerelease HEAD \(detached.* -# maintenance is currently the branch for preparation of maintenance release 1.5.0 +# maintenance is currently the branch for preparation of maintenance release 1.6.0 # so are any fix/... and improve/... branches -maintenance 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev -fix/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev -improve/.* 1.5.0 42769dad7dda3bc0c6c94e0e8ce832af9b14a565 pep440-dev +maintenance 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev +fix/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev +improve/.* 1.6.0 b7a45b79bf86339f0b28177ac1eaebb56d00ea37 pep440-dev # staging/bugfix is the branch for preparation of the 1.5.3 hotfix release # so are any bug/... branches diff --git a/AUTHORS.md b/AUTHORS.md index 97c7d96cb..1f20a1b5f 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -131,6 +131,11 @@ date of first contribution): * [Manuel McLure](https://github.com/ManuelMcLure) * ["j7126"](https://github.com/j7126) * ["coliss86"](https://github.com/coliss86) + * ["MichaIng"](https://github.com/MichaIng) + * ["jasonbcox"](https://github.com/jasonbcox) + * ["shadycuz"](https://github.com/shadycuz) + * [David Rifkind](https://github.com/drifkind) + * [Nils Hofmann](https://github.com/Master92) * [Miroslav ล edivรฝ](https://github.com/eumiro) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by diff --git a/docs/api/job.rst b/docs/api/job.rst index 2679a9b51..e95729459 100644 --- a/docs/api/job.rst +++ b/docs/api/job.rst @@ -251,5 +251,10 @@ Job information response * - ``state`` - 1 - String - - A textual representation of the current state of the job, i.e. "Operational", "Printing", "Pausing", "Paused", - "Cancelling", "Error" or "Offline". + - A textual representation of the current state of the job or connection, e.g. "Operational", "Printing", "Pausing", "Paused", + "Cancelling", "Error", "Offline", "Offline after error", "Opening serial connection", ... -- please note + that this list is not exhaustive! + * - ``error`` + - 0..1 + - String + - Any error message for the job or connection, only set if there has been an error. diff --git a/docs/bundledplugins/backup.rst b/docs/bundledplugins/backup.rst index e11c149c4..24be587e1 100644 --- a/docs/bundledplugins/backup.rst +++ b/docs/bundledplugins/backup.rst @@ -177,6 +177,30 @@ octoprint.plugin.backup.additional_excludes :return: A list of paths to exclude, relative to your plugin's data folder :rtype: list +Helpers +------- + +.. _sec-bundledplugins-backup-helpers: + +The Backup plugin exports two helpers that can be used by other plugins or internal methods +from within OctoPrint, without going via the API. + +.. _sec-bundledplugins-backup-helpers-create_backup: + +create_backup ++++++++++++++ + +.. autofunction:: octoprint.plugins.backup.BackupPlugin.create_backup_helper + + +.. _sec-bundledplugins-backup-helpers-delete_backup: + +delete_backup ++++++++++++++ + +.. autofunction:: octoprint.plugins.backup.BackupPlugin.delete_backup_helper + + .. _sec-bundledplugins-backup-sourcecode: Source code diff --git a/docs/events/index.rst b/docs/events/index.rst index 7fa5e733e..71a55d68e 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -539,6 +539,34 @@ PrintResumed .. versionchanged:: 1.4.0 +GcodeScript${ScriptName}Running + A custom :ref:`GCODE script ` has started running. + + Payload: + + * ``name``: the file's name + * ``path``: the file's path within its storage location + * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the time needed for the print, in seconds (float) + + .. versionadded:: 1.6.0 + +GcodeScript${ScriptName}Finished + A custom :ref:`GCODE script ` has finished running. + + Payload: + + * ``name``: the file's name + * ``path``: the file's path within its storage location + * ``origin``: the origin storage location of the file, either ``local`` or ``sdcard`` + * ``size``: the file's size in bytes (if available) + * ``owner``: the user who started the print job (if available) + * ``time``: the time needed for the print, in seconds (float) + + .. versionadded:: 1.6.0 + .. _sec-events-available_events-gcode_processing: GCODE processing diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index dbd84ef0d..d836d3fad 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -43,6 +43,15 @@ The following GCODE scripts are sent by OctoPrint automatically: Plugins may extend these scripts through :ref:`a hook `. +.. _sec-features-gcode_scripts-events: + +Events +------ + +Every GCODE script that is executed will emit two events. The event name will start with 'GcodeScript' followed by the capitalized name +of the script. When ``afterPrintDone`` has started the event will be ``GcodeScriptAfterPrintDoneRunning`` and once it has completed the last event +will be ``GcodeScriptAfterPrintDoneFinished``. You can find more details in the :ref:`Events ` documentation. + .. _sec-features-gcode_scripts-snippets: Snippets diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index dc8d9cace..91759647f 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -259,6 +259,10 @@ onUserSettingsShown() onUserSettingsHidden() Called when the user settings dialog is hidden. +onUserSettingsBeforeSave() + Called just before the user settings view model is sent to the server. This is useful, for example, if your plugin + needs to compute persisted settings from a custom view model. + onWizardDetails(response) Called with the response from the wizard detail API call initiated before opening the wizard dialog. Will contain the data from all :class:`~octoprint.plugin.WizardPlugin` implementations returned by their :meth:`~octoprint.plugin.WizardPlugin.get_wizard_details` diff --git a/scripts/octoprint.service b/scripts/octoprint.service index 14f5d7f4b..ae5405c34 100644 --- a/scripts/octoprint.service +++ b/scripts/octoprint.service @@ -6,7 +6,7 @@ Wants=network-online.target [Service] Environment="LC_ALL=C.UTF-8" Environment="LANG=C.UTF-8" -Type=simple +Type=exec User=pi ExecStart=/home/pi/OctoPrint/venv/bin/octoprint diff --git a/setup.py b/setup.py index 70c64ab12..33c12b9b9 100644 --- a/setup.py +++ b/setup.py @@ -62,6 +62,7 @@ INSTALL_REQUIRES = [ "frozendict>=1.2,<2", "sentry-sdk>=0.15.1,<1", "filetype>=1.0.7,<2", + "zipstream-new>=1.1.8,<1.2", # vendor bundled dependencies "unidecode>=0.04.14,<0.05", # dependency of awesome-slugify "blinker>=1.4,<2", # dependency of flask_principal diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index de9bd4d30..a85d74ce5 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -86,6 +86,7 @@ class FatalStartupError(Exception): def init_platform( basedir, configfile, + overlays=None, use_logging_file=True, logging_file=None, logging_config=None, @@ -117,7 +118,7 @@ def init_platform( after_preinit_logging(**kwargs) try: - settings = init_settings(basedir, configfile) + settings = init_settings(basedir, configfile, overlays=overlays) except Exception as ex: raise FatalStartupError("Could not initialize settings manager", cause=ex) kwargs["settings"] = settings @@ -220,13 +221,15 @@ def init_platform( ) -def init_settings(basedir, configfile): +def init_settings(basedir, configfile, overlays=None): """Inits the settings instance based on basedir and configfile to use.""" from octoprint.settings import InvalidSettings, settings try: - return settings(init=True, basedir=basedir, configfile=configfile) + return settings( + init=True, basedir=basedir, configfile=configfile, overlays=overlays + ) except InvalidSettings as e: raise FatalStartupError(str(e)) @@ -619,16 +622,17 @@ def init_pluginsystem( ) plugin_validators = [] + if safe_mode: - def validator(phase, plugin_info): + def safe_mode_validator(phase, plugin_info): if phase in ("before_import", "before_load", "before_enable"): plugin_info.safe_mode_victim = not plugin_info.bundled if not plugin_info.bundled: return False return True - plugin_validators.append(validator) + plugin_validators.append(safe_mode_validator) compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index e12b12199..2dc21ae62 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -62,6 +62,7 @@ def init_platform_for_cli(ctx): components = init_platform( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), + overlays=get_ctx_obj_option(ctx, "overlays", None), safe_mode=True, ) @@ -180,8 +181,7 @@ def standard_options(hidden=False): """ Decorator to add the standard options shared among all "octoprint" commands. - Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden`` - is set to ``True``, the options will be available on the command but not + If ``hidden`` is set to ``True``, the options will be available on the command but not listed in its help page. """ @@ -209,6 +209,16 @@ def standard_options(hidden=False): expose_value=False, help="Specify the config file to use.", ), + factory( + "--overlay", + "overlays", + type=click.Path(), + callback=set_ctx_obj_option, + is_eager=True, + multiple=True, + expose_value=False, + help="Specify additional config overlays to use.", + ), factory( "--verbose", "-v", diff --git a/src/octoprint/cli/config.py b/src/octoprint/cli/config.py index fb7c960e5..c45e56394 100644 --- a/src/octoprint/cli/config.py +++ b/src/octoprint/cli/config.py @@ -40,7 +40,7 @@ def _set_helper(settings, path, value, data_type=None): if name is not None: method = getattr(settings, name) - method(path, value) + method(path, value, force=True) settings.save() @@ -65,6 +65,7 @@ def config(ctx): ctx.obj.settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), + overlays=get_ctx_obj_option(ctx, "overlays", None), ) except FatalStartupError as e: click.echo(str(e), err=True) diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index e5e283110..09b86c06e 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -84,6 +84,7 @@ class OctoPrintPluginCommands(click.MultiCommand): self.settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), + overlays=get_ctx_obj_option(ctx, "overlays", None), ) self.plugin_manager = init_pluginsystem( self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 39f7fab3b..eff6f5c19 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -33,6 +33,7 @@ def run_server( safe_mode, ignore_blacklist, octoprint_daemon=None, + overlays=None, ): """Initializes the environment and starts up the server.""" @@ -113,6 +114,7 @@ def run_server( components = init_platform( basedir, configfile, + overlays=overlays, logging_file=logging_config, debug=debug, verbosity=verbosity, @@ -260,6 +262,7 @@ def enable_safemode(ctx, **kwargs): settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), + overlays=get_ctx_obj_option(ctx, "overlays", None), ) except FatalStartupError as e: click.echo(str(e), err=True) @@ -297,6 +300,7 @@ def serve_command(ctx, **kwargs): verbosity = get_value("verbosity") safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") + overlays = get_value("overlays") if v4 and not host: host = "0.0.0.0" @@ -313,6 +317,7 @@ def serve_command(ctx, **kwargs): verbosity, safe_mode, ignore_blacklist, + overlays=overlays, ) @@ -350,6 +355,7 @@ if sys.platform != "win32" and sys.platform != "darwin": basedir = get_value("basedir") configfile = get_value("configfile") + overlays = get_value("overlays") verbosity = get_value("verbosity") safe_mode = "flag" if get_value("safe_mode") else None ignore_blacklist = get_value("ignore_blacklist") @@ -369,6 +375,7 @@ if sys.platform != "win32" and sys.platform != "darwin": pidfile, basedir, configfile, + overlays, host, port, v6_only, @@ -383,6 +390,7 @@ if sys.platform != "win32" and sys.platform != "darwin": self._basedir = basedir self._configfile = configfile + self._overlays = overlays self._host = host self._port = port self._v6_only = v6_only @@ -407,12 +415,14 @@ if sys.platform != "win32" and sys.platform != "darwin": self._safe_mode, self._ignore_blacklist, octoprint_daemon=self, + overlays=self._overlays, ) octoprint_daemon = OctoPrintDaemon( pid, basedir, configfile, + overlays, host, port, v6, diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 548fd88bb..724d9cf60 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -48,6 +48,7 @@ def user(ctx): settings = init_settings( get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None), + overlays=get_ctx_obj_option(ctx, "overlays", None), ) group_manager_name = settings.get(["accessControl", "groupManager"]) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 76c7afbf2..c4378c0a3 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -9,7 +9,6 @@ import copy import io import logging import os -import re import shutil import pylru @@ -21,12 +20,11 @@ except ImportError: from contextlib import contextmanager -from emoji import demojize from past.builtins import basestring import octoprint.filemanager from octoprint.util import atomic_write, is_hidden_path, time_this, to_bytes, to_unicode -from octoprint.vendor.awesome_slugify import Slugify +from octoprint.util.text import sanitize class StorageInterface(object): @@ -468,22 +466,6 @@ class LocalFileStorage(StorageInterface): This storage type implements :func:`path_on_disk`. """ - _UNICODE_VARIATIONS = re.compile("[\uFE00-\uFE0F]", re.U) - - @classmethod - def _no_unicode_variations(cls, text): - return cls._UNICODE_VARIATIONS.sub("", text) - - _SLUGIFY = Slugify() - _SLUGIFY.safe_chars = "-_.()[] " - - @classmethod - def _slugify(cls, text): - text = to_unicode(text) - text = cls._no_unicode_variations(text) - text = demojize(text, delimiters=("", "")) - return cls._SLUGIFY(text) - def __init__(self, basefolder, create=False): """ Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder @@ -1192,7 +1174,7 @@ class LocalFileStorage(StorageInterface): if "/" in name or "\\" in name: raise ValueError("name must not contain / or \\") - result = self._slugify(name).replace(" ", "_") + result = sanitize(name, safe_chars="-_.()[] ").replace(" ", "_") if result and result != "." and result != ".." and result[0] == ".": # hidden files under *nix result = result[1:] diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index b3010b1ec..c7ce091a6 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -207,35 +207,12 @@ class PluginInfo(object): attr_implementation = "__plugin_implementation__" """ Module attribute from which to retrieve the plugin's provided mixin implementation. """ - attr_implementations = "__plugin_implementations__" - """ - Module attribute from which to retrieve the plugin's provided implementations. - - This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_implementation`. Only the - first entry will be evaluated. - - .. deprecated:: 1.2.0-dev-694 - - Use :attr:`attr_implementation` instead. - """ - attr_helpers = "__plugin_helpers__" """ Module attribute from which to retrieve the plugin's provided helpers. """ attr_check = "__plugin_check__" """ Module attribute which to call to determine if the plugin can be loaded. """ - attr_init = "__plugin_init__" - """ - Module attribute which to call when loading the plugin. - - This deprecated attribute will only be used if a plugin does not yet offer :attr:`attr_load`. - - .. deprecated:: 1.2.0-dev-720 - - Use :attr:`attr_load` instead. - """ - attr_load = "__plugin_load__" """ Module attribute which to call when loading the plugin. """ @@ -323,7 +300,8 @@ class PluginInfo(object): if phase == "before_import": result = ( - not self.forced_disabled + self.looks_like_plugin + and not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax @@ -331,54 +309,10 @@ class PluginInfo(object): ) elif phase == "before_load": - # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ - if hasattr(self.instance, self.__class__.attr_init): - if not hasattr(self.instance, self.__class__.attr_load): - # deprecation warning - import warnings - - warnings.warn( - "{name} uses deprecated control property __plugin_init__, use __plugin_load__ instead".format( - name=self.key - ), - DeprecationWarning, - ) - - # move it - init = getattr(self.instance, self.__class__.attr_init) - setattr(self.instance, self.__class__.attr_load, init) - - # delete __plugin_init__ - delattr(self.instance, self.__class__.attr_init) + pass elif phase == "after_load": - # if the plugin still uses __plugin_implementations__, log a deprecation warning and put the first - # item into __plugin_implementation__ - if hasattr(self.instance, self.__class__.attr_implementations): - if not hasattr(self.instance, self.__class__.attr_implementation): - # deprecation warning - import warnings - - warnings.warn( - "{name} uses deprecated control property __plugin_implementations__, use __plugin_implementation__ instead - only the first implementation of {name} will be recognized".format( - name=self.key - ), - DeprecationWarning, - ) - - # put first item into __plugin_implementation__ - implementations = getattr( - self.instance, self.__class__.attr_implementations - ) - if len(implementations) > 0: - setattr( - self.instance, - self.__class__.attr_implementation, - implementations[0], - ) - - # delete __plugin_implementations__ - delattr(self.instance, self.__class__.attr_implementations) + pass if additional_validators is not None: for validator in additional_validators: @@ -731,9 +665,24 @@ class PluginInfo(object): @property def parsed_metadata(self): - """The plugin metadata parsed from the plugin ``__init__.py``'s AST.""" + """The plugin metadata parsed from the plugin's AST.""" return self._cached_parsed_metadata + @property + def control_properties(self): + return [ + getattr(self.__class__, key) + for key in dir(self.__class__) + if key.startswith("attr_") + ] + + @property + def looks_like_plugin(self): + """ + Returns whether the plugin actually looks like a plugin (has control properties) or not. + """ + return self.parsed_metadata.get("has_control_properties", False) + def _parse_metadata(self): result = {} @@ -764,6 +713,10 @@ class PluginInfo(object): assignments = list( filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body) ) + function_defs = list( + filter(lambda x: isinstance(x, ast.FunctionDef) and x.name, root.body) + ) + all_relevant = assignments + function_defs def extract_target_ids(node): return list( @@ -773,6 +726,16 @@ class PluginInfo(object): ) ) + def extract_names(node): + if isinstance(node, ast.Assign): + return extract_target_ids(node) + elif isinstance(node, ast.FunctionDef): + return [ + node.name, + ] + else: + return [] + for key in ( self.__class__.attr_name, self.__class__.attr_version, @@ -811,6 +774,12 @@ class PluginInfo(object): break + for a in reversed(all_relevant): + targets = extract_names(a) + if any(map(lambda x: x in targets, self.control_properties)): + result["has_control_properties"] = True + break + except SyntaxError: self._logger.exception( "Invalid syntax in {} for plugin {}".format(path, self.key) @@ -1015,11 +984,8 @@ class PluginManager(object): try: if entry.is_dir(): init_py = os.path.join(entry.path, "__init__.py") - init_pyc = os.path.join(entry.path, "__init__.pyc") - if not os.path.isfile(init_py) and not os.path.isfile( - init_pyc - ): + if not os.path.isfile(init_py): # neither does exist, we ignore this continue @@ -1027,8 +993,8 @@ class PluginManager(object): elif entry.is_file(): key, ext = os.path.splitext(entry.name) - if ext not in (".py", ".pyc") or key.startswith("__"): - # neither py nor pyc, or starts with __ (like __init__), we ignore this + if ext not in (".py",) or key.startswith("__"): + # not py, or starts with __ (like __init__), we ignore this continue else: @@ -1405,7 +1371,8 @@ class PluginManager(object): for name, plugin in added.items(): try: if ( - not plugin.blacklisted + plugin.looks_like_plugin + and not plugin.blacklisted and not plugin.forced_disabled and not plugin.incompatible ): @@ -1431,6 +1398,7 @@ class PluginManager(object): try: if ( plugin.loaded + and plugin.looks_like_plugin and not plugin.forced_disabled and not plugin.incompatible ): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 6012549b9..c724b9c35 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -792,7 +792,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): list: A list of paths to additional files whose modification to track for (in)validating the cache. Ignored if ``None`` is returned. - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return None @@ -807,7 +807,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): list: A list of paths representing the only files whose modification to track for (in)validating the cache. Ignored if ``None`` is returned. - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return None @@ -820,7 +820,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): Returns: str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return None @@ -838,7 +838,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): Returns: (list): A list of additional fields for the ETag generation, or None - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return default_additional @@ -851,7 +851,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): Returns: int: An alternatively calculated LastModified value. Ignored if ``None`` is returned (default). - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return None @@ -877,7 +877,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): Returns: dict: Additional data to persist in the preemptive cache configuration. - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return None @@ -895,7 +895,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): dict: Additional request data to persist in the preemptive cache configuration and to use for request environment construction. - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return None @@ -911,7 +911,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): Returns: bool: Whether to suppress a record (True) or not (False, default) - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return False @@ -933,7 +933,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): and returning ``True`` to keep it and ``False`` to filter it out. If ``None`` is returned, no filtering will take place. - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ return default_template_filter @@ -953,7 +953,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): (list) A list of permissions which to check the current user session against. May be empty to indicate that no permission checks should be made by OctoPrint. - ..versionadded: 1.5.0 + .. versionadded: 1.5.0 """ from octoprint.access.permissions import Permissions @@ -1381,7 +1381,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): and `the documentation for flask.Flask.errorhandler `_ for more information. - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ from collections import defaultdict @@ -1580,7 +1580,7 @@ class SettingsPlugin(OctoPrintPlugin): from flask_login import current_user - from octoprint.access.permissions import Permissions + from octoprint.access.permissions import OctoPrintPermission, Permissions data = copy.deepcopy(self._settings.get_all_data(merged=True)) if self.config_version_key in data: @@ -1632,9 +1632,15 @@ class SettingsPlugin(OctoPrintPlugin): "never": lambda: False, } - for level, condition in conditions.items(): - paths_for_level = restricted_paths.get(level, []) - for path in paths_for_level: + for level, paths in restricted_paths.items(): + if isinstance(level, OctoPrintPermission): + condition = lambda: ( + current_user is not None and current_user.has_permission(level) + ) + else: + condition = conditions.get(level, lambda: False) + + for path in paths: restrict_path_unless(data, path, condition) return data @@ -1708,12 +1714,15 @@ class SettingsPlugin(OctoPrintPlugin): Retrieves the list of paths in the plugin's settings which be restricted on the REST API. Override this in your plugin's implementation to restrict whether a path should only be returned to users with - the SETTINGS permission, any logged in users, or never on the REST API. + certain permissions, or never on the REST API. - Return a ``dict`` with the keys ``admin``, ``user``, ``never`` mapping to a list of paths (as tuples or lists of - the path elements) for which to restrict access via the REST API accordingly. Paths returned for the ``admin`` - key will only be available on the REST API when access with admin rights, ``user`` will only be available when accessed - as a logged in user. ``never`` will never be returned on the API. + Return a ``dict`` with one of the following keys, mapping to a list of paths (as tuples or lists of + the path elements) for which to restrict access via the REST API accordingly. + + * An :py:class:`~octoprint.access.permissions.OctoPrintPermission` instance: Paths will only be available on the REST API for users with the permission + * ``admin``: Paths will only be available on the REST API for users with admin rights (any user with the SETTINGS permission) + * ``user``: Paths will only be available on the REST API when accessed as a logged in user + * ``never``: Paths will never be returned on the API Example: @@ -1724,12 +1733,15 @@ class SettingsPlugin(OctoPrintPlugin): user_only=dict(path="path", bar="bar")), another=dict(admin_only=dict(path="path"), field="field"), - path=dict(to=dict(never=dict(return="return")))) + path=dict(to=dict(never=dict(return="return"))), + the=dict(webcam=dict(data="webcam"))) def get_settings_restricted_paths(self): - return dict(admin=[["some", "admin_only", "path"], ["another", "admin_only", "path"],], - user=[["some", "user_only", "path"],], - never=[["path", "to", "never", "return"],]) + from octoprint.access.permissions import Permissions + return {'admin':[["some", "admin_only", "path"], ["another", "admin_only", "path"],], + 'user':[["some", "user_only", "path"],], + 'never':[["path", "to", "never", "return"],], + Permissions.WEBCAM:[["the", "webcam", "data"],]} # this will make the plugin return settings on the REST API like this for an anonymous user # @@ -1737,15 +1749,26 @@ class SettingsPlugin(OctoPrintPlugin): # user_only=dict(path=None, bar="bar")), # another=dict(admin_only=dict(path=None), # field="field"), - # path=dict(to=dict(never=dict(return=None)))) + # path=dict(to=dict(never=dict(return=None))), + # the=dict(webcam=dict(data=None))) # - # like this for a logged in user + # like this for a logged in user without the webcam permission # # dict(some=dict(admin_only=dict(path=None, foo="foo"), # user_only=dict(path="path", bar="bar")), # another=dict(admin_only=dict(path=None), # field="field"), - # path=dict(to=dict(never=dict(return=None)))) + # path=dict(to=dict(never=dict(return=None))), + # the=dict(webcam=dict(data=None))) + # + # like this for a logged in user with the webcam permission + # + # dict(some=dict(admin_only=dict(path=None, foo="foo"), + # user_only=dict(path="path", bar="bar")), + # another=dict(admin_only=dict(path=None), + # field="field"), + # path=dict(to=dict(never=dict(return=None))), + # the=dict(webcam=dict(data="webcam"))) # # and like this for an admin user # @@ -1753,9 +1776,10 @@ class SettingsPlugin(OctoPrintPlugin): # user_only=dict(path="path", bar="bar")), # another=dict(admin_only=dict(path="path"), # field="field"), - # path=dict(to=dict(never=dict(return=None)))) + # path=dict(to=dict(never=dict(return=None))), + # the=dict(webcam=dict(data="webcam"))) - ..versionadded:: 1.2.17 + .. versionadded:: 1.2.17 """ return {} @@ -1793,7 +1817,7 @@ class SettingsPlugin(OctoPrintPlugin): Returns: (dict, dict): A tuple consisting of two dictionaries, the first being the plugin's preprocessors for - getters, the second the preprocessors for setters + getters, the second the preprocessors for setters """ return {}, {} @@ -1807,8 +1831,8 @@ class SettingsPlugin(OctoPrintPlugin): Returns: int or None: an int signifying the current settings format, should be incremented by plugins whenever there - are backwards incompatible changes. Returning None here disables the version tracking for the - plugin's configuration. + are backwards incompatible changes. Returning None here disables the version tracking for the + plugin's configuration. """ return None @@ -1844,7 +1868,7 @@ class SettingsPlugin(OctoPrintPlugin): the differences to the defaults (in case the current data was persisted with an older version of OctoPrint that still duplicated default data). - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ import octoprint.util from octoprint.settings import NoSuchSettingsPath @@ -1987,7 +2011,7 @@ class SlicerPlugin(OctoPrintPlugin): Returns: (dict) a dictionary containing a valid extension subtree. - ..versionadded:: 1.3.11 + .. versionadded:: 1.3.11 """ from octoprint.filemanager import ContentTypeMapping @@ -2004,7 +2028,7 @@ class SlicerPlugin(OctoPrintPlugin): Arguments: profile_path (str): The base folder where OctoPrint stores this slicer plugin's profiles - ..versionadded:: 1.3.7 + .. versionadded:: 1.3.7 """ try: @@ -2029,7 +2053,7 @@ class SlicerPlugin(OctoPrintPlugin): # noinspection PyMethodMayBeStatic def get_slicer_profiles_lastmodified(self, profile_path): """ - ..versionadded:: 1.3.0 + .. versionadded:: 1.3.0 """ import os diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 index 0a9d041e5..c9f903f73 100644 --- a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_navbar.jinja2 @@ -1,3 +1,3 @@ diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 7f05a23f1..7c320d4b8 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -29,6 +29,7 @@ from octoprint.server.util.flask import ( with_revalidation_checking, ) from octoprint.util import count, monotonic_time, utmify +from octoprint.util.text import sanitize PY2 = sys.version_info[0] < 3 @@ -47,11 +48,6 @@ class AnnouncementPlugin( self._cached_channel_configs = None self._cached_channel_configs_mutex = threading.RLock() - from octoprint.vendor.awesome_slugify import Slugify - - self._slugify = Slugify() - self._slugify.safe_chars = "-_." - # Additional permissions hook def get_additional_permissions(self): @@ -366,14 +362,14 @@ class AnnouncementPlugin( if config is None or "url" not in config or "name" not in config: # strip invalid entries continue - result[self._slugify(key)] = config + result[sanitize(key)] = config self._cached_channel_configs = result return self._cached_channel_configs def _get_channel_config(self, key, force=False): """Retrieve specific channel config for channel.""" - safe_key = self._slugify(key) + safe_key = sanitize(key) return self._get_channel_configs(force=force).get(safe_key) def _fetch_all_channels_async(self, force=False): @@ -524,7 +520,7 @@ class AnnouncementPlugin( def _get_channel_cache_path(self, key): """Retrieve cache path for channel key.""" - safe_key = self._slugify(key) + safe_key = sanitize(key) return os.path.join(self.get_plugin_data_folder(), "{}.cache".format(safe_key)) diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index 2e015853f..75720f39a 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -31,7 +31,7 @@ $(function () { 5 ); - self.unread = ko.observable(); + self.unread = ko.observable(false); self.hiddenChannels = []; self.channelNotifications = {}; diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 066d20799..366e03883 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -8,7 +8,6 @@ import octoprint.plugin from octoprint.access import ADMIN_GROUP from octoprint.access.permissions import Permissions from octoprint.events import Events -from octoprint.plugin.core import FolderOrigin from octoprint.server import NO_CONTENT from octoprint.server.util.flask import no_firstrun_access from octoprint.settings import default_settings @@ -51,18 +50,13 @@ import sarge from flask_babel import gettext from octoprint.settings import valid_boolean_trues +from octoprint.util.text import sanitize UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json" -BACKUP_FILE_PREFIX = "octoprint-backup" - BACKUP_DATE_TIME_FMT = "%Y%m%d-%H%M%S" -def build_backup_filename(): - return "{}-{}.zip".format(BACKUP_FILE_PREFIX, time.strftime(BACKUP_DATE_TIME_FMT)) - - class BackupPlugin( octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, @@ -174,65 +168,14 @@ class BackupPlugin( @no_firstrun_access @Permissions.PLUGIN_BACKUP_ACCESS.require(403) def create_backup(self): - backup_file = build_backup_filename() data = flask.request.json exclude = data.get("exclude", []) + filename = self._build_backup_filename(settings=self._settings) - def on_backup_start(name, temporary_path, exclude): - self._logger.info( - "Creating backup zip at {} (excluded: {})...".format( - temporary_path, ",".join(exclude) if len(exclude) else "-" - ) - ) + self._start_backup(exclude, filename) - with self._in_progress_lock: - self._in_progress.append(name) - self._send_client_message("backup_started", payload={"name": name}) - - def on_backup_done(name, final_path, exclude): - with self._in_progress_lock: - self._in_progress.remove(name) - self._send_client_message("backup_done", payload={"name": name}) - - self._logger.info("... done creating backup zip.") - - self._event_bus.fire( - Events.PLUGIN_BACKUP_BACKUP_CREATED, - {"name": name, "path": final_path, "excludes": exclude}, - ) - - def on_backup_error(name, exc_info): - with self._in_progress_lock: - try: - self._in_progress.remove(name) - except ValueError: - # we'll ignore that - pass - - self._send_client_message( - "backup_error", payload={"name": name, "error": "{}".format(exc_info[1])} - ) - self._logger.error("Error while creating backup zip", exc_info=exc_info) - - thread = threading.Thread( - target=self._create_backup, - args=(backup_file,), - kwargs={ - "exclude": exclude, - "settings": self._settings, - "plugin_manager": self._plugin_manager, - "logger": self._logger, - "datafolder": self.get_plugin_data_folder(), - "on_backup_start": on_backup_start, - "on_backup_done": on_backup_done, - "on_backup_error": on_backup_error, - }, - ) - thread.daemon = True - thread.start() - - response = flask.jsonify(started=True, name=backup_file) + response = flask.jsonify(started=True, name=filename) response.status_code = 201 return response @@ -240,18 +183,8 @@ class BackupPlugin( @no_firstrun_access @Permissions.PLUGIN_BACKUP_ACCESS.require(403) def delete_backup(self, filename): - backup_folder = self.get_plugin_data_folder() - full_path = os.path.realpath(os.path.join(backup_folder, filename)) - if ( - full_path.startswith(backup_folder) - and os.path.exists(full_path) - and not is_hidden_path(full_path) - ): - try: - os.remove(full_path) - except Exception: - self._logger.exception("Could not delete {}".format(filename)) - raise + self._delete_backup(filename) + return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) @@ -460,6 +393,76 @@ class BackupPlugin( # max upload size of 1GB for the restore endpoint return [("POST", r"/restore", 1024 * 1024 * 1024)] + # Exported plugin helpers + def create_backup_helper(self, exclude=None, filename=None): + """ + .. versionadded:: 1.6.0 + + Create a backup from a plugin or other internal call + + This helper is exported as ``create_backup`` and can be used from the plugin + manager's ``get_helpers`` method. + + **Example** + + The following code snippet can be used from within a plugin, and will create a backup + excluding two folders (``timelapse`` and ``uploads``) + + .. code-block:: python + + helpers = self._plugin_manager.get_helpers("backup", "create_backup") + + if helpers and "create_backup" in helpers: + helpers["create_backup"](exclude=["timelapse", "uploads"]) + + By using the ``if helpers [...]`` clause, plugins can fall back to other methods + when they are running under versions where these helpers did not exist. + + + :param list exclude: Names of data folders to exclude, defaults to None + :param str filename: Name of backup to be created, if None (default) the backup + name will be auto-generated. This should use a ``.zip`` extension. + """ + if exclude is None: + exclude = [] + if not isinstance(exclude, list): + exclude = list(exclude) + + self._start_backup(exclude, filename=filename) + + def delete_backup_helper(self, filename): + """ + .. versionadded:: 1.6.0 + + Delete the specified backup from a plugin or other internal call + + This helper is exported as ``delete_backup`` and can be used through the plugin + manager's ``get_helpers`` method. + + **Example** + The following code snippet can be used from within a plugin, and will attempt to + delete the backup named ``ExampleBackup.zip``. + + .. code-block:: python + + helpers = self._plugin_manager.get_helpers("backup", "delete_backup") + + if helpers and "delete_backup" in helpers: + helpers["delete_backup"]("ExampleBackup.zip") + + By using the ``if helpers [...]`` clause, plugins can fall back to other methods + when they are running under versions where these helpers did not exist. + + .. warning:: + + This method will fail silently if the backup does not exist, and so + it is recommended that you make sure the name comes from a verified source, + for example the name from the events or other helpers. + + :param str filename: The name of the backup to delete + """ + self._delete_backup(filename) + ##~~ CLI hook def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs): @@ -488,26 +491,24 @@ class BackupPlugin( ) if path is not None: - datafolder, backup_file = os.path.split(os.path.abspath(path)) + datafolder, filename = os.path.split(os.path.abspath(path)) else: - backup_file = build_backup_filename() + filename = self._build_backup_filename(settings=settings) datafolder = os.path.join(settings.getBaseFolder("data"), "backup") if not os.path.isdir(datafolder): os.makedirs(datafolder) - click.echo("Creating backup at {}, please wait...".format(backup_file)) + click.echo("Creating backup at {}, please wait...".format(filename)) self._create_backup( - backup_file, + filename, exclude=exclude, settings=settings, plugin_manager=cli_group.plugin_manager, datafolder=datafolder, ) click.echo("Done.") - click.echo( - "Backup located at {}".format(os.path.join(datafolder, backup_file)) - ) + click.echo("Backup located at {}".format(os.path.join(datafolder, filename))) @click.command("restore") @click.argument("path") @@ -644,6 +645,82 @@ class BackupPlugin( ##~~ helpers + def _start_backup(self, exclude, filename=None): + if filename is None: + filename = self._build_backup_filename(settings=self._settings) + + def on_backup_start(name, temporary_path, exclude): + self._logger.info( + "Creating backup zip at {} (excluded: {})...".format( + temporary_path, ",".join(exclude) if len(exclude) else "-" + ) + ) + + with self._in_progress_lock: + self._in_progress.append(name) + self._send_client_message("backup_started", payload={"name": name}) + + def on_backup_done(name, final_path, exclude): + with self._in_progress_lock: + self._in_progress.remove(name) + self._send_client_message("backup_done", payload={"name": name}) + + self._logger.info("... done creating backup zip.") + + self._event_bus.fire( + Events.PLUGIN_BACKUP_BACKUP_CREATED, + {"name": name, "path": final_path, "excludes": exclude}, + ) + + def on_backup_error(name, exc_info): + with self._in_progress_lock: + try: + self._in_progress.remove(name) + except ValueError: + # we'll ignore that + pass + + self._send_client_message( + "backup_error", payload={"name": name, "error": "{}".format(exc_info[1])} + ) + self._logger.error("Error while creating backup zip", exc_info=exc_info) + + thread = threading.Thread( + target=self._create_backup, + args=(filename,), + kwargs={ + "exclude": exclude, + "settings": self._settings, + "plugin_manager": self._plugin_manager, + "logger": self._logger, + "datafolder": self.get_plugin_data_folder(), + "on_backup_start": on_backup_start, + "on_backup_done": on_backup_done, + "on_backup_error": on_backup_error, + }, + ) + thread.daemon = True + thread.start() + + def _delete_backup(self, filename): + """ + Delete the backup specified + Args: + filename (str): Name of backup to delete + """ + backup_folder = self.get_plugin_data_folder() + full_path = os.path.realpath(os.path.join(backup_folder, filename)) + if ( + full_path.startswith(backup_folder) + and os.path.exists(full_path) + and not is_hidden_path(full_path) + ): + try: + os.remove(full_path) + except Exception: + self._logger.exception("Could not delete {}".format(filename)) + raise + def _get_backups(self): backups = [] for entry in scandir(self.get_plugin_data_folder()): @@ -985,22 +1062,16 @@ class BackupPlugin( ) # add list of installed plugins - plugins = [] - plugin_folder = settings.global_get_basefolder("plugins") - for plugin in plugin_manager.plugins.values(): - if plugin.bundled or ( - isinstance(plugin.origin, FolderOrigin) - and plugin.origin.folder == plugin_folder - ): - # ignore anything bundled or from the plugins folder we already include in the backup - continue - - plugins.append( - {"key": plugin.key, "name": plugin.name, "url": plugin.url} + helpers = plugin_manager.get_helpers( + "pluginmanager", "generate_plugins_json" + ) + if helpers and "generate_plugins_json" in helpers: + plugins = helpers["generate_plugins_json"]( + settings=settings, plugin_manager=plugin_manager ) - if len(plugins): - zip.writestr("plugin_list.json", json.dumps(plugins)) + if len(plugins): + zip.writestr("plugin_list.json", json.dumps(plugins)) shutil.move(temporary_path, final_path) @@ -1290,6 +1361,17 @@ class BackupPlugin( return True + @classmethod + def _build_backup_filename(cls, settings): + if settings.global_get(["appearance", "name"]) == "": + backup_prefix = "octoprint" + else: + backup_prefix = settings.global_get(["appearance", "name"]) + backup_prefix = sanitize(backup_prefix) + return "{}-backup-{}.zip".format( + backup_prefix, time.strftime(BACKUP_DATE_TIME_FMT) + ) + @classmethod def _restore_supported(cls, settings): return ( @@ -1332,3 +1414,7 @@ __plugin_hooks__ = { "octoprint.events.register_custom_events": _register_custom_events, "octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_hook, } +__plugin_helpers__ = { + "create_backup": __plugin_implementation__.create_backup_helper, + "delete_backup": __plugin_implementation__.delete_backup_helper, +} diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 index 6d8a71898..d8715540e 100644 --- a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 +++ b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 @@ -11,7 +11,7 @@ OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here. {% endtrans %}

-
+ {% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %}
@@ -21,7 +21,7 @@ trust and that has a high availability. {% endtrans %}

-
+ {% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckTestConnectivity.jinja2" %} @@ -34,7 +34,7 @@ side with the general connectivity check, leave the field empty. {% endtrans %}

- +
{% include "snippets/settings/server/serverOnlineCheckName.jinja2" %} {% include "snippets/settings/server/serverOnlineCheckTestResolution.jinja2" %} @@ -47,8 +47,12 @@ {% endtrans %}