From 0afa8547636ae272f0d8033bb985388db1381e58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 25 Oct 2017 17:16:40 +0200 Subject: [PATCH 1/9] Support a centralized plugin blacklist (opt-in) A centralized plugin blacklist read from plugins.octoprint.org on server start now allows us to stop plugins from being loaded that are known to cause severe issues with OctoPrint's regular operation. Blacklist entries can be restricted for specific plugin versions & OctoPrint versions, allowing for very granular control of any kind of blocking. Additionally users may disable blacklist processing in general (an opt-in wizard and a new section in the settings have been added) and at server start via the new --ignore-blacklist parameter available for "octoprint serve" and "octoprint daemon". If a plugin is blacklisted, OctoPrint will not even import the plugin module in question (if only a plugin key is specified OR a key and a version and the plugin's version is already known during import time, which is the case for plugins loaded from entry points) or at the very least stop the plugin from being enabled (if a plugin key and a version is specified and the plugin's version is only known after loading, which is the case for plugins loaded from directories). --- src/octoprint/__init__.py | 166 +++++++++++++++++- src/octoprint/cli/__init__.py | 5 +- src/octoprint/cli/plugins.py | 4 +- src/octoprint/cli/server.py | 52 +++--- src/octoprint/plugin/__init__.py | 5 +- src/octoprint/plugin/core.py | 60 +++++-- src/octoprint/plugins/corewizard/__init__.py | 22 ++- .../corewizard/static/css/corewizard.css | 4 + .../corewizard/static/js/corewizard.js | 83 +++++++++ .../corewizard_pluginblacklist_wizard.jinja2 | 26 +++ .../plugins/pluginmanager/__init__.py | 75 ++------ .../pluginmanager/static/js/pluginmanager.js | 35 +++- .../templates/pluginmanager_settings.jinja2 | 2 +- src/octoprint/server/__init__.py | 22 +-- src/octoprint/server/api/settings.py | 14 ++ src/octoprint/settings.py | 5 + .../static/js/app/viewmodels/settings.js | 4 + .../templates/dialogs/settings/server.jinja2 | 4 + .../server/serverPluginBlacklist.jinja2 | 11 ++ .../serverPluginBlacklistDescription.jinja2 | 5 + .../serverPluginBlacklistEnabled.jinja2 | 8 + .../server/serverPluginBlacklistTtl.jinja2 | 9 + .../server/serverPluginBlacklistUrl.jinja2 | 6 + src/octoprint/util/version.py | 88 ++++++++++ 24 files changed, 588 insertions(+), 127 deletions(-) create mode 100644 src/octoprint/plugins/corewizard/static/css/corewizard.css create mode 100644 src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 create mode 100644 src/octoprint/templates/snippets/settings/server/serverPluginBlacklist.jinja2 create mode 100644 src/octoprint/templates/snippets/settings/server/serverPluginBlacklistDescription.jinja2 create mode 100644 src/octoprint/templates/snippets/settings/server/serverPluginBlacklistEnabled.jinja2 create mode 100644 src/octoprint/templates/snippets/settings/server/serverPluginBlacklistTtl.jinja2 create mode 100644 src/octoprint/templates/snippets/settings/server/serverPluginBlacklistUrl.jinja2 create mode 100644 src/octoprint/util/version.py diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 785a5e5cf..e2d32cfc7 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -57,8 +57,9 @@ class FatalStartupError(BaseException): def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, logging_config=None, debug=False, verbosity=0, uncaught_logger=None, - uncaught_handler=None, safe_mode=False, after_preinit_logging=None, + uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None, after_settings=None, after_logging=None, after_safe_mode=None, + after_event_manager=None, after_connectivity_checker=None, after_plugin_manager=None): kwargs = dict() @@ -94,13 +95,28 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, if callable(after_safe_mode): after_safe_mode(**kwargs) - plugin_manager = init_pluginsystem(settings, safe_mode=safe_mode) + event_manager = init_event_manager(settings) + + kwargs["event_manager"] = event_manager + if callable(after_event_manager): + after_event_manager(**kwargs) + + connectivity_checker = init_connectivity_checker(settings, event_manager) + + kwargs["connectivity_checker"] = connectivity_checker + if callable(after_connectivity_checker): + after_connectivity_checker(**kwargs) + + plugin_manager = init_pluginsystem(settings, + safe_mode=safe_mode, + ignore_blacklist=ignore_blacklist, + connectivity_checker=connectivity_checker) kwargs["plugin_manager"] = plugin_manager if callable(after_plugin_manager): after_plugin_manager(**kwargs) - return settings, logger, safe_mode, plugin_manager + return settings, logger, safe_mode, event_manager, connectivity_checker, plugin_manager def init_settings(basedir, configfile): @@ -281,17 +297,21 @@ def set_logging_config(config, debug, verbosity, uncaught_logger, uncaught_handl return logger -def init_pluginsystem(settings, safe_mode=False): +def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connectivity_checker=None): """Initializes the plugin manager based on the settings.""" import os - logger = log.getLogger(__name__) + logger = log.getLogger(__name__ + ".startup") plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), settings.getBaseFolder("plugins")] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) + + plugin_blacklist = [] + if not ignore_blacklist and settings.getBoolean(["server", "pluginBlacklist", "enabled"]): + plugin_blacklist = get_plugin_blacklist(settings, connectivity_checker=connectivity_checker) plugin_validators = [] if safe_mode: @@ -311,13 +331,14 @@ def init_pluginsystem(settings, safe_mode=False): plugin_folders=plugin_folders, plugin_entry_points=plugin_entry_points, plugin_disabled_list=plugin_disabled_list, + plugin_blacklist=plugin_blacklist, plugin_validators=plugin_validators) settings_overlays = dict() disabled_from_overlays = dict() def handle_plugin_loaded(name, plugin): - if hasattr(plugin.instance, "__plugin_settings_overlay__"): + if plugin.instance and hasattr(plugin.instance, "__plugin_settings_overlay__"): plugin.needs_restart = True # plugin has a settings overlay, inject it @@ -356,7 +377,7 @@ def init_pluginsystem(settings, safe_mode=False): if not addon in already_processed and not addon in disabled_list: disabled_list.append(addon) - logger.info("Disabling plugin {} as defined by plugin {} through settings overlay".format(addon, name)) + logger.info("Disabling plugin {} as defined by plugin {}".format(addon, name)) already_processed.append(name) def handle_plugin_enabled(name, plugin): @@ -370,6 +391,137 @@ def init_pluginsystem(settings, safe_mode=False): pm.reload_plugins(startup=True, initialize_implementations=False) return pm + +def get_plugin_blacklist(settings, connectivity_checker=None): + import requests + import os + import time + import yaml + + from octoprint.util import bom_aware_open + from octoprint.util.version import is_octoprint_compatible + + logger = log.getLogger(__name__ + ".startup") + + if connectivity_checker is not None and not connectivity_checker.online: + logger.info("We don't appear to be online, not fetching plugin blacklist") + return [] + + def format_blacklist(entries): + format_entry = lambda x: "{} ({})".format(x[0], x[1]) if isinstance(x, (list, tuple)) and len(x) == 2 \ + else "{} (any)".format(x) + return ", ".join(map(format_entry, entries)) + + def process_blacklist(entries): + result = [] + + if not isinstance(entries, list): + return result + + for entry in entries: + if not "plugin" in entry: + continue + + if "octoversions" in entry and not is_octoprint_compatible(*entry["octoversions"]): + continue + + if "version" in entry: + logger.debug("Blacklisted plugin: {}, version: {}".format(entry["plugin"], entry["version"])) + result.append((entry["plugin"], entry["version"])) + elif "versions" in entry: + logger.debug("Blacklisted plugin: {}, versions: {}".format(entry["plugin"], ", ".join(entry["versions"]))) + for version in entry["versions"]: + result.append((entry["plugin"], version)) + else: + logger.debug("Blacklisted plugin: {}".format(entry["plugin"])) + result.append(entry["key"]) + + return result + + def fetch_blacklist_from_cache(path, ttl): + if not os.path.isfile(path): + return None + + if os.stat(path).st_mtime + ttl < time.time(): + return None + + with bom_aware_open(path, encoding="utf-8", mode="r") as f: + result = yaml.safe_load(f) + + if isinstance(result, list): + return result + + def fetch_blacklist_from_url(url, timeout=3, cache=None): + result = [] + try: + r = requests.get(url, timeout=timeout) + result = process_blacklist(r.json()) + + if cache is not None: + try: + with bom_aware_open(cache, encoding="utf-8", mode="w") as f: + yaml.safe_dump(result, f) + except: + logger.info("Fetched plugin blacklist but couldn't write it to its cache file.") + except: + logger.info("Unable to fetch plugin blacklist from {}, proceeding without it.".format(url)) + return result + + try: + # first attempt to fetch from cache + cache_path = os.path.join(settings.getBaseFolder("data"), "plugin_blacklist.yaml") + ttl = settings.getInt(["server", "pluginBlacklist", "ttl"]) + blacklist = fetch_blacklist_from_cache(cache_path, ttl) + + if blacklist is None: + # no result from the cache, let's fetch it fresh + url = settings.get(["server", "pluginBlacklist", "url"]) + timeout = settings.getFloat(["server", "pluginBlacklist", "timeout"]) + blacklist = fetch_blacklist_from_url(url, timeout=timeout, cache=cache_path) + + if blacklist is None: + # still now result, so no blacklist + blacklist = [] + + if blacklist: + logger.info("Blacklist processing done, " + "adding {} blacklisted plugin versions: {}".format(len(blacklist), + format_blacklist(blacklist))) + else: + logger.info("Blacklist processing done") + + return blacklist + except: + logger.exception("Something went wrong while processing the plugin blacklist. Proceeding without it.") + + +def init_event_manager(settings): + from octoprint.events import eventManager + return eventManager() + + +def init_connectivity_checker(settings, event_manager): + from octoprint.events import Events + from octoprint.util import ConnectivityChecker + + # start regular check if we are connected to the internet + connectivityEnabled = settings.getBoolean(["server", "onlineCheck", "enabled"]) + connectivityInterval = settings.getInt(["server", "onlineCheck", "interval"]) + connectivityHost = settings.get(["server", "onlineCheck", "host"]) + connectivityPort = settings.getInt(["server", "onlineCheck", "port"]) + + def on_connectivity_change(old_value, new_value): + event_manager.fire(Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value)) + + connectivityChecker = ConnectivityChecker(connectivityInterval, + connectivityHost, + port=connectivityPort, + enabled=connectivityEnabled, + on_change=on_connectivity_change) + + return connectivityChecker + + #~~ server main method def main(): diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index 9562b173c..34ad3f30e 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -106,9 +106,9 @@ def standard_options(hidden=False): factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, help="Specify the config file to use."), factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, - help="Increase logging verbosity"), + help="Increase logging verbosity."), factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, - help="Enable safe mode; disables all third party plugins") + help="Enable safe mode; disables all third party plugins.") ] return bulk_options(options) @@ -123,6 +123,7 @@ legacy_options = bulk_options([ hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option), hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option), hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option), + hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option) ]) """Legacy options available directly on the "octoprint" command in earlier versions. Kept available for reasons of backwards compatibility, but hidden from the diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index e650129b1..facfc80cb 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -43,6 +43,7 @@ class OctoPrintPluginCommands(click.MultiCommand): if self._initialized: return + click.echo("Initializing settings & plugin subsystem...") if ctx.obj is None: ctx.obj = OctoPrintContext() @@ -51,7 +52,8 @@ class OctoPrintPluginCommands(click.MultiCommand): from octoprint import init_settings, init_pluginsystem, FatalStartupError try: self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) - self.plugin_manager = init_pluginsystem(self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)) + self.plugin_manager = init_pluginsystem(self.settings, + safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error initializing the settings or the plugin system.", err=True) diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 5789af64e..3adea9f5b 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -11,7 +11,8 @@ import sys from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option -def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, octoprint_daemon=None): +def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode, + ignore_blacklist, octoprint_daemon=None): """Initializes the environment and starts up the server.""" from octoprint import init_platform, __display_version__, FatalStartupError @@ -19,7 +20,7 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi def log_startup(recorder=None, safe_mode=None, **kwargs): from octoprint.logging import get_divider_line - logger = logging.getLogger("octoprint.server") + logger = logging.getLogger("octoprint.startup") logger.info(get_divider_line("*")) logger.info("Starting OctoPrint {}".format(__display_version__)) @@ -71,15 +72,17 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi OctoPrintLogHandler.registerRolloverCallback(rollover_callback) try: - settings, _, safe_mode, plugin_manager = init_platform(basedir, - configfile, - logging_file=logging_config, - debug=debug, - verbosity=verbosity, - uncaught_logger=__name__, - safe_mode=safe_mode, - after_safe_mode=log_startup, - after_plugin_manager=log_register_rollover) + settings, _, safe_mode, event_manager, \ + connectivity_checker, plugin_manager = init_platform(basedir, + configfile, + logging_file=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=__name__, + safe_mode=safe_mode, + ignore_blacklist=ignore_blacklist, + after_safe_mode=log_startup, + after_plugin_manager=log_register_rollover) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error starting up OctoPrint.", err=True) @@ -87,6 +90,8 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi from octoprint.server import Server octoprint_server = Server(settings=settings, plugin_manager=plugin_manager, + event_manager=event_manager, + connectivity_checker=connectivity_checker, host=host, port=port, debug=debug, @@ -107,7 +112,9 @@ server_options = bulk_options([ click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option, help="Allow OctoPrint to run as user root."), click.option("--debug", is_flag=True, callback=set_ctx_obj_option, - help="Enable debug mode.") + help="Enable debug mode."), + click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option, + help="Disable processing of the plugin blacklist.") ]) """Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" @@ -126,7 +133,7 @@ def server_commands(): @server_commands.command(name="safemode") -@standard_options(hidden=True) +@standard_options() @click.pass_context def enable_safemode(ctx, **kwargs): """Sets the safe mode flag for the next start.""" @@ -147,8 +154,8 @@ def enable_safemode(ctx, **kwargs): @server_commands.command(name="serve") +@standard_options() @server_options -@standard_options(hidden=True) @click.pass_context def serve_command(ctx, **kwargs): """Starts the OctoPrint server.""" @@ -166,18 +173,20 @@ def serve_command(ctx, **kwargs): configfile = get_value("configfile") verbosity = get_value("verbosity") safe_mode = get_value("safe_mode") + ignore_blacklist = get_value("ignore_blacklist") run_server(basedir, configfile, host, port, debug, - allow_root, logging, verbosity, safe_mode) + allow_root, logging, verbosity, safe_mode, + ignore_blacklist) if sys.platform != "win32" and sys.platform != "darwin": # we do not support daemon mode under windows or macosx @server_commands.command(name="daemon") + @standard_options() @server_options @daemon_options - @standard_options(hidden=True) @click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]), metavar="start|stop|restart|status") @click.pass_context @@ -185,7 +194,7 @@ if sys.platform != "win32" and sys.platform != "darwin": """ Starts, stops or restarts in daemon mode. - Please note that daemon mode is only supported under Linux right now. + Please note that daemon mode is not supported under Windows and MacOSX right now. """ def get_value(key): @@ -202,6 +211,7 @@ if sys.platform != "win32" and sys.platform != "darwin": configfile = get_value("configfile") verbosity = get_value("verbosity") safe_mode = get_value("safe_mode") + ignore_blacklist = get_value("ignore_blacklist") if pid is None: click.echo("No path to a pidfile set", @@ -210,7 +220,8 @@ if sys.platform != "win32" and sys.platform != "darwin": from octoprint.daemon import Daemon class OctoPrintDaemon(Daemon): - def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, safe_mode): + def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity, + safe_mode, ignore_blacklist): Daemon.__init__(self, pidfile) self._basedir = basedir @@ -222,14 +233,15 @@ if sys.platform != "win32" and sys.platform != "darwin": self._logging_config = logging_config self._verbosity = verbosity self._safe_mode = safe_mode + self._ignore_blacklist = ignore_blacklist def run(self): run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity, self._safe_mode, - octoprint_daemon=self) + self._ignore_blacklist, octoprint_daemon=self) octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, debug, allow_root, logging, verbosity, - safe_mode) + safe_mode, ignore_blacklist) if command == "start": octoprint_daemon.start() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 2f77e2c49..114d2fe61 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -45,7 +45,8 @@ def _validate_plugin(phase, plugin_info): return True def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None, - plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None): + plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, + plugin_validators=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -65,6 +66,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en this defaults to the entry point ``octoprint.plugin``. plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this defaults to all plugins for which ``enabled`` is set to ``False`` in the settings. + plugin_blacklist (list): A list of plugin identifiers/identifier-version tuples that are currently blacklisted. plugin_restart_needing_hooks (list): A list of hook namespaces which cause a plugin to need a restart in order be enabled/disabled. Does not have to contain full hook identifiers, will be matched with startswith similar to logging handlers @@ -120,6 +122,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en plugin_entry_points, logging_prefix="octoprint.plugins.", plugin_disabled_list=plugin_disabled_list, + plugin_blacklist=plugin_blacklist, plugin_restart_needing_hooks=plugin_restart_needing_hooks, plugin_obsolete_hooks=plugin_obsolete_hooks, plugin_validators=plugin_validators) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 76d092e78..d8a58e9e9 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -36,6 +36,8 @@ import fnmatch import pkg_resources import pkginfo +from past.builtins import basestring + try: from os import scandir except ImportError: @@ -57,7 +59,7 @@ class PluginInfo(object): Arguments: key (str): Identifier of the plugin location (str): Installation folder of the plugin - instance (module): Plugin module instance + instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted! name (str): Human readable name of the plugin version (str): Version of the plugin description (str): Description of the plugin @@ -140,6 +142,7 @@ class PluginInfo(object): self.instance = instance self.origin = None self.enabled = True + self.blacklisted = False self.bundled = False self.loaded = False self.managable = True @@ -201,7 +204,7 @@ class PluginInfo(object): def long_str(self, show_bundled=False, bundled_strs=(" [B]", ""), show_location=False, location_str=" - {location}", - show_enabled=False, enabled_strs=("* ", " ")): + show_enabled=False, enabled_strs=("* ", " ", "X ")): """ Long string representation of the plugin's information. Will return a string of the format ````. @@ -209,8 +212,8 @@ class PluginInfo(object): The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows: ``enabled_str`` - a 2-tuple, the first entry being the string to insert when the plugin is enabled, the second - entry the string to insert when it is not. + a 3-tuple, the first entry being the string to insert when the plugin is enabled, the second + entry the string to insert when it is not, the third entry the string when it is blacklisted. ``bundled_str`` a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second entry the string to insert when it is not. @@ -230,7 +233,7 @@ class PluginInfo(object): str: The long string representation of the plugin as described above """ if show_enabled: - ret = enabled_strs[0] if self.enabled else enabled_strs[1] + ret = enabled_strs[2] if self.blacklisted else (enabled_strs[0] if self.enabled else enabled_strs[1]) else: ret = "" @@ -445,7 +448,7 @@ class PluginInfo(object): return self._get_instance_attribute(self.__class__.attr_disable, default=lambda: True) def _get_instance_attribute(self, attr, default=None, defaults=None): - if not hasattr(self.instance, attr): + if self.instance is None or not hasattr(self.instance, attr): if defaults is not None: for value in defaults: if value is not None: @@ -463,8 +466,8 @@ class PluginManager(object): """ def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, - plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, - plugin_validators=None): + plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, + plugin_obsolete_hooks=None, plugin_validators=None): self.logger = logging.getLogger(__name__) if logging_prefix is None: @@ -477,11 +480,14 @@ class PluginManager(object): plugin_entry_points = [] if plugin_disabled_list is None: plugin_disabled_list = [] + if plugin_blacklist is None: + plugin_blacklist = [] self.plugin_folders = plugin_folders self.plugin_types = plugin_types self.plugin_entry_points = plugin_entry_points self.plugin_disabled_list = plugin_disabled_list + self.plugin_blacklist = plugin_blacklist self.plugin_restart_needing_hooks = plugin_restart_needing_hooks self.plugin_obsolete_hooks = plugin_obsolete_hooks self.plugin_validators = plugin_validators @@ -543,7 +549,7 @@ class PluginManager(object): if existing is None: existing = dict(self.plugins) - result = dict() + result = OrderedDict() if self.plugin_folders: result.update(self._find_plugins_from_folders(self.plugin_folders, existing, ignored_uninstalled=ignore_uninstalled)) if self.plugin_entry_points: @@ -552,7 +558,7 @@ class PluginManager(object): return result def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True): - result = dict() + result = OrderedDict() for folder in folders: flagged_readonly = False @@ -596,7 +602,7 @@ class PluginManager(object): return result def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True): - result = dict() + result = OrderedDict() # let's make sure we have a current working set ... working_set = pkg_resources.WorkingSet() @@ -674,6 +680,12 @@ class PluginManager(object): self.logger.warn("Could not locate plugin {key}".format(key=key)) return None + if self._is_plugin_blacklisted(key) or (version is not None and self._is_plugin_version_blacklisted(key, version)): + plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author, url=url, license=license) + plugin.blacklisted = True + self.logger.warn("Plugin {} is blacklisted. Not importing it, only registering a dummy entry.".format(plugin)) + return plugin + plugin = self._import_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license) if plugin is None: return None @@ -696,6 +708,19 @@ class PluginManager(object): def _is_plugin_disabled(self, key): return key in self.plugin_disabled_list or key.endswith('disabled') + def _is_plugin_blacklisted(self, key): + return key in self.plugin_blacklist + + def _is_plugin_version_blacklisted(self, key, version): + def matches_plugin(entry): + if isinstance(entry, (tuple, list)) and len(entry) == 2: + entry_key, entry_version = entry + return entry_key == key and entry_version == version + return False + + return any(map(lambda entry: matches_plugin(entry), + self.plugin_blacklist)) + def reload_plugins(self, startup=False, initialize_implementations=True, force_reload=None): self.logger.info("Loading plugins from {folders} and installed plugin packages...".format( folders=", ".join(map(lambda x: x[0] if isinstance(x, tuple) else str(x), self.plugin_folders)) @@ -710,7 +735,8 @@ class PluginManager(object): # 1st pass: loading the plugins for name, plugin in plugins.items(): try: - self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations) + if not plugin.blacklisted: + self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations) except PluginNeedsRestart: pass except PluginLifecycleException as e: @@ -724,6 +750,9 @@ class PluginManager(object): for name, plugin in plugins.items(): try: if plugin.loaded and not self._is_plugin_disabled(name): + if plugin.blacklisted: + self.logger.warn("Plugin {} is blacklisted. Not enabling it.".format(plugin)) + continue self.enable_plugin(name, plugin=plugin, initialize_implementation=initialize_implementations, startup=startup) except PluginNeedsRestart: pass @@ -780,6 +809,11 @@ class PluginManager(object): plugin.loaded = True + # we might only now have a version, so check again if we are blacklisted + if not plugin.blacklisted and plugin.version and self._is_plugin_version_blacklisted(plugin.key, + plugin.version): + plugin.blacklisted = True + self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) except PluginLifecycleException as e: raise e @@ -1146,7 +1180,7 @@ class PluginManager(object): def log_all_plugins(self, show_bundled=True, bundled_str=(" (bundled)", ""), show_location=True, - location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!"), + location_str=" = {location}", show_enabled=True, enabled_str=(" ", "!", "#"), only_to_handler=None): all_plugins = self.enabled_plugins.values() + self.disabled_plugins.values() diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index bfeb93e77..7beb50a85 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -62,7 +62,8 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, def get_assets(self): if self.is_wizard_required(): return dict( - js=["js/corewizard.js"] + js=["js/corewizard.js"], + css=["css/corewizard.css"] ) else: return dict() @@ -91,7 +92,7 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return result def get_wizard_version(self): - return 1 + return 2 #~~ ACL subwizard @@ -190,6 +191,23 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, def _get_onlinecheck_additional_wizard_template_data(self): return dict(mandatory=self._is_onlinecheck_wizard_required()) + #~~ Plugin blacklist subwizard + + def _is_pluginblacklist_wizard_firstrunonly(self): + return False + + def _is_pluginblacklist_wizard_required(self): + return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None + + def _get_pluginblacklist_wizard_details(self): + return dict(required=self._is_pluginblacklist_wizard_required()) + + def _get_pluginblacklist_wizard_name(self): + return gettext("Plugin blacklist") + + def _get_pluginblacklist_additional_wizard_template_data(self): + return dict(mandatory=self._is_pluginblacklist_wizard_required()) + #~~ Printer profile subwizard def _is_printerprofile_wizard_firstrunonly(self): diff --git a/src/octoprint/plugins/corewizard/static/css/corewizard.css b/src/octoprint/plugins/corewizard/static/css/corewizard.css new file mode 100644 index 000000000..2f15349dd --- /dev/null +++ b/src/octoprint/plugins/corewizard/static/css/corewizard.css @@ -0,0 +1,4 @@ +#wizard_plugin_corewizard_pluginblacklist p { + line-height: 1.5; + margin-bottom: 1.5em; +} diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index 2a09a07b3..b96d92e29 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -207,6 +207,85 @@ $(function() { } + function CoreWizardPluginBlacklistViewModel(parameters) { + var self = this; + + self.settingsViewModel = parameters[0]; + + self.setup = ko.observable(false); + + self.decision = ko.observable(); + self.required = false; + self.active = false; + + self.enablePluginBlacklist = function() { + self.settingsViewModel.server_pluginBlacklist_enabled(true); + self.decision(true); + self._sendData(); + }; + + self.disablePluginBlacklist = function() { + self.settingsViewModel.server_pluginBlacklist_enabled(false); + self.decision(false); + self._sendData(); + }; + + self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + + if (!current || !_.startsWith(current, "wizard_plugin_corewizard_pluginblacklist_") || self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onBeforeWizardFinish = function() { + if (!self.required) return true; + + if (self.setup()) { + return true; + } + + self._showDecisionNeededDialog(); + return false; + }; + + self.onWizardPreventSettingsRefreshDialog = function() { + return self.active; + }; + + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.pluginblacklist && response.corewizard.details.pluginblacklist.required; + }; + + self._showDecisionNeededDialog = function() { + showMessageDialog({ + title: gettext("Please set up the plugin blacklist processing"), + message: gettext("You haven't yet decided on whether to enable or disable the plugin blacklist processing. You need to either enable or disable it before continuing.") + }); + }; + + self._sendData = function() { + var data = { + server: { + pluginBlacklist: { + enabled: self.settingsViewModel.server_pluginBlacklist_enabled() + } + } + }; + + self.active = true; + self.settingsViewModel.saveData(data) + .done(function() { + self.setup(true); + self.active = false; + }); + }; + + } + function CoreWizardPrinterProfileViewModel(parameters) { var self = this; @@ -258,6 +337,10 @@ $(function() { CoreWizardOnlineCheckViewModel, ["settingsViewModel"], "#wizard_plugin_corewizard_onlinecheck" + ], [ + CoreWizardPluginBlacklistViewModel, + ["settingsViewModel"], + "#wizard_plugin_corewizard_pluginblacklist" ], [ CoreWizardPrinterProfileViewModel, ["printerProfilesViewModel"], diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 new file mode 100644 index 000000000..f046ac2fb --- /dev/null +++ b/src/octoprint/plugins/corewizard/templates/corewizard_pluginblacklist_wizard.jinja2 @@ -0,0 +1,26 @@ +

{{ _('Configure plugin blacklist processing') }}

+ +

{% trans %} + To protect against known severe issues with certain versions of third party plugins, OctoPrint supports the use + of a centralized plugin version blacklist to automatically disable such plugin versions before they can interfere with + normal operation, allowing you to uninstall or update them to a newer version. +{% endtrans %}

+ +

{% trans %} + Please decide whether to allow fetch and use of this centralized blacklist starting with the next server start. + You may also change your decision at any time through Settings > Server right from within OctoPrint. +{% endtrans %}

+ + + + diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index a6806ac7f..1892a0e88 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -14,6 +14,7 @@ from octoprint.settings import valid_boolean_trues from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag from octoprint.server import admin_permission, VERSION from octoprint.util.pip import LocalPipCaller, UnknownPip +from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, is_octoprint_compatible from flask import jsonify, make_response from flask.ext.babel import gettext @@ -31,6 +32,8 @@ import dateutil.parser import time import threading +_DATA_FORMAT_VERSION = "v2" + class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, @@ -239,7 +242,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, plugins=self._repository_plugins ), os=self._get_os(), - octoprint=self._get_octoprint_version_string(), + octoprint=get_octoprint_version_string(), pip=dict( available=self._pip_caller.available, version=self._pip_caller.version_string, @@ -262,6 +265,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, hash.update(repr(self._notices)) hash.update(repr(safe_mode)) hash.update(repr(self._connectivity_checker.online)) + hash.update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() def condition(): @@ -526,7 +530,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if not needs_restart: try: - self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) + if plugin.enabled: + self._plugin_manager.disable_plugin(plugin.key, plugin=plugin) except octoprint.plugin.core.PluginLifecycleException as e: self._logger.exception(u"Problem disabling plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=False, unloaded=False, reason=e.reason) @@ -534,7 +539,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return jsonify(result) try: - self._plugin_manager.unload_plugin(plugin.key) + if plugin.loaded: + self._plugin_manager.unload_plugin(plugin.key) except octoprint.plugin.core.PluginLifecycleException as e: self._logger.exception(u"Problem unloading plugin {name}".format(name=plugin.key)) result = dict(result=False, uninstalled=True, disabled=True, unloaded=False, reason=e.reason) @@ -754,7 +760,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return False current_os = self._get_os() - octoprint_version = self._get_octoprint_version(base=True) + octoprint_version = get_octoprint_version(base=True) def map_repository_entry(entry): result = copy.deepcopy(entry) @@ -769,7 +775,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if "compatibility" in entry: if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) and len(entry["compatibility"]["octoprint"]): - result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"]) + result["is_compatible"]["octoprint"] = is_octoprint_compatible(*entry["compatibility"]["octoprint"], + octoprint_version=octoprint_version) if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]): result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"]) @@ -847,26 +854,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._notices = notices return True - def _is_octoprint_compatible(self, octoprint_version, compatibility_entries): - """ - Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``. - """ - - for octo_compat in compatibility_entries: - try: - if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")): - octo_compat = ">={}".format(octo_compat) - - s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat)) - if octoprint_version in s: - break - except: - self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat)) - else: - return False - - return True - @staticmethod def _is_os_compatible(current_os, compatibility_entries): """ @@ -899,38 +886,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, else: return "unmapped" - def _get_octoprint_version_string(self): - return VERSION - - def _get_octoprint_version(self, base=False): - octoprint_version_string = self._get_octoprint_version_string() - - if "-" in octoprint_version_string: - octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")] - - octoprint_version = pkg_resources.parse_version(octoprint_version_string) - - # A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's - # versions should never contains such a prefix, we'll make sure to have stuff behave the same - # regardless of setuptools version anyhow. - if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v": - octoprint_version = octoprint_version[1:] - - if base: - if isinstance(octoprint_version, tuple): - # old setuptools - base_version = [] - for part in octoprint_version: - if part.startswith("*"): - break - base_version.append(part) - base_version.append("*final") - octoprint_version = tuple(base_version) - else: - # new setuptools - octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) - return octoprint_version - @property def _reconnect_hooks(self): reconnect_hooks = self.__class__.RECONNECT_HOOKS @@ -972,6 +927,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, bundled=plugin.bundled, managable=plugin.managable, enabled=plugin.enabled, + blacklisted=plugin.blacklisted, safe_mode_victim=getattr(plugin, "safe_mode_victim", False), safe_mode_enabled=getattr(plugin, "safe_mode_enabled", False), pending_enable=(not plugin.enabled and not getattr(plugin, "safe_mode_enabled", False) and plugin.key in self._pending_enable), @@ -990,13 +946,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if key not in self._notices: return - octoprint_version = self._get_octoprint_version(base=True) + octoprint_version = get_octoprint_version(base=True) plugin_notifications = self._notices.get(key, []) def filter_relevant(notification): return "text" in notification and "date" in notification and \ ("versions" not in notification or plugin.version in notification["versions"]) and \ - ("octoversions" not in notification or self._is_octoprint_compatible(octoprint_version, notification["octoversions"])) + ("octoversions" not in notification or is_octoprint_compatible(*notification["octoversions"], + octoprint_version=octoprint_version)) def map_notification(notification): return self._to_external_notification(key, notification) diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 4d42feaca..8675addaf 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -222,7 +222,9 @@ $(function() { self.enableToggle = function(data) { var command = self._getToggleCommand(data); - return self.enableManagement() && (command == "disable" || !data.safe_mode_victim || data.safe_mode_enabled) && data.key != 'pluginmanager'; + var not_safemode_victim = !data.safe_mode_victim || data.safe_mode_enabled; + var not_blacklisted = !data.blacklisted; + return self.enableManagement() && (command == "disable" || (not_safemode_victim && not_blacklisted)) && data.key != 'pluginmanager'; }; self.enableUninstall = function(data) { @@ -699,7 +701,7 @@ $(function() { return self.isCompatible(data) ? (self.installed(data) ? gettext("Reinstall") : gettext("Install")) : (data.disabled ? gettext("Disabled") : gettext("Incompatible")); }; - self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) { + self._displayNotification = function(response, action, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) { var notification; var beforeClose = function(notification) { @@ -707,7 +709,17 @@ $(function() { }; if (response.result) { - if (response.needs_restart) { + if (action == "install" && response.plugin && response.plugin.blacklisted) { + notification = new PNotify({ + title: titleSuccess, + text: textSuccess, + type: "warning", + callbacks: { + before_close: beforeClose + }, + hide: false + }) + } else if (response.needs_restart) { var options = { title: titleSuccess, text: textRestart, @@ -859,7 +871,9 @@ $(function() { self.toggleButtonTitle = function(data) { var command = self._getToggleCommand(data); if (command == "enable") { - if (data.safe_mode_victim && !data.safe_mode_enabled) { + if (data.blacklisted) { + return gettext("Blacklisted"); + } else if (data.safe_mode_victim && !data.safe_mode_enabled) { return gettext("Disabled due to active safe mode"); } else { return gettext("Enable Plugin"); @@ -1121,6 +1135,17 @@ $(function() { textRestart = textSuccess; textReload = textSuccess; textReconnect = textSuccess; + } else if (data.plugin && data.plugin.blacklisted) { + if (data.was_reinstalled) { + titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name}); + textSuccess = gettext("The plugin was reinstalled successfully, however it is blacklisted and therefore won't be loaded."); + } else { + titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name}); + textSuccess = gettext("The plugin was installed successfully, however it is blacklisted and therefore won't be loaded."); + } + textRestart = textSuccess; + textReload = textSuccess; + textReconnect = textSuccess; } else if (data.was_reinstalled) { titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" reinstalled"), {name: name}); textSuccess = gettext("The plugin was reinstalled successfully"); @@ -1233,7 +1258,7 @@ $(function() { return; } - self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError); + self._displayNotification(data, action, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError); self.requestData(); } }; diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 8829e656a..4dc8b2ae7 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -47,7 +47,7 @@ -
()
+
()
 
diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 7363adfeb..e792846a3 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -146,9 +146,12 @@ def load_user(id): class Server(object): - def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None): + def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, event_manager=None, + host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False, octoprint_daemon=None): self._settings = settings self._plugin_manager = plugin_manager + self._connectivity_checker = connectivity_checker + self._event_manager = event_manager self._host = host self._port = port self._debug = debug @@ -233,7 +236,7 @@ class Server(object): pluginManager.reload_plugins(startup=True, initialize_implementations=False) printerProfileManager = PrinterProfileManager() - eventManager = events.eventManager() + eventManager = self._event_manager analysisQueue = octoprint.filemanager.analysis.AnalysisQueue() slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager) @@ -245,20 +248,7 @@ class Server(object): pluginLifecycleManager = LifecycleManager(pluginManager) preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml")) - # start regular check if we are connected to the internet - connectivityEnabled = self._settings.getBoolean(["server", "onlineCheck", "enabled"]) - connectivityInterval = self._settings.getInt(["server", "onlineCheck", "interval"]) - connectivityHost = self._settings.get(["server", "onlineCheck", "host"]) - connectivityPort = self._settings.getInt(["server", "onlineCheck", "port"]) - - def on_connectivity_change(old_value, new_value): - eventManager.fire(events.Events.CONNECTIVITY_CHANGED, payload=dict(old=old_value, new=new_value)) - - connectivityChecker = octoprint.util.ConnectivityChecker(connectivityInterval, - connectivityHost, - port=connectivityPort, - enabled=connectivityEnabled, - on_change=on_connectivity_change) + connectivityChecker = self._connectivity_checker def on_settings_update(*args, **kwargs): # make sure our connectivity checker runs with the latest settings diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 5112eca30..4223416e5 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -208,6 +208,11 @@ def getSettings(): "interval": int(s.getInt(["server", "onlineCheck", "interval"]) / 60), "host": s.get(["server", "onlineCheck", "host"]), "port": s.getInt(["server", "onlineCheck", "port"]) + }, + "pluginBlacklist": { + "enabled": s.getBoolean(["server", "pluginBlacklist", "enabled"]), + "url": s.get(["server", "pluginBlacklist", "url"]), + "ttl": int(s.getInt(["server", "pluginBlacklist", "ttl"]) / 60) } } } @@ -435,6 +440,15 @@ def _saveSettings(data): pass if "host" in data["server"]["onlineCheck"]: s.set(["server", "onlineCheck", "host"], data["server"]["onlineCheck"]["host"]) if "port" in data["server"]["onlineCheck"]: s.setInt(["server", "onlineCheck", "port"], data["server"]["onlineCheck"]["port"]) + if "pluginBlacklist" in data["server"]: + if "enabled" in data["server"]["pluginBlacklist"]: s.setBoolean(["server", "pluginBlacklist", "enabled"], data["server"]["pluginBlacklist"]["enabled"]) + if "url" in data["server"]["pluginBlacklist"]: s.set(["server", "pluginBlacklist", "url"], data["server"]["pluginBlacklist"]["url"]) + if "ttl" in data["server"]["pluginBlacklist"]: + try: + ttl = int(data["server"]["pluginBlacklist"]["ttl"]) + s.setInt(["server", "pluginBlacklist", "ttl"], ttl * 60) + except ValueError: + pass if "plugins" in data: for plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin): diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d28d352bc..7926af1b3 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -154,6 +154,11 @@ default_settings = { "host": "8.8.8.8", "port": 53 }, + "pluginBlacklist": { + "enabled": None, + "url": "http://plugins.octoprint.org/blacklist.json", + "ttl": 15 * 60 # 15 min + }, "diskspace": { "warning": 500 * 1024 * 1024, # 500 MB "critical": 200 * 1024 * 1024, # 200 MB diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index d5607e71a..c338aeda9 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -218,6 +218,10 @@ $(function() { self.server_onlineCheck_host = ko.observable(); self.server_onlineCheck_port = ko.observable(); + self.server_pluginBlacklist_enabled = ko.observable(); + self.server_pluginBlacklist_url = ko.observable(); + self.server_pluginBlacklist_ttl = ko.observable(); + self.settings = undefined; self.lastReceivedSettings = undefined; diff --git a/src/octoprint/templates/dialogs/settings/server.jinja2 b/src/octoprint/templates/dialogs/settings/server.jinja2 index 8e3fd59e3..b7f6c497e 100644 --- a/src/octoprint/templates/dialogs/settings/server.jinja2 +++ b/src/octoprint/templates/dialogs/settings/server.jinja2 @@ -10,4 +10,8 @@ {% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %} {% include "snippets/settings/server/serverOnlineCheck.jinja2" %} +

{{ _('Plugin blacklist processing') }}

+ + {% include "snippets/settings/server/serverPluginBlacklistDescription.jinja2" %} + {% include "snippets/settings/server/serverPluginBlacklist.jinja2" %} diff --git a/src/octoprint/templates/snippets/settings/server/serverPluginBlacklist.jinja2 b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklist.jinja2 new file mode 100644 index 000000000..02624d738 --- /dev/null +++ b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklist.jinja2 @@ -0,0 +1,11 @@ +{% include "snippets/settings/server/serverPluginBlacklistEnabled.jinja2" %} + +
+
+ +
+ {% include "snippets/settings/server/serverPluginBlacklistUrl.jinja2" %} + {% include "snippets/settings/server/serverPluginBlacklistTtl.jinja2" %} +
+
+
diff --git a/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistDescription.jinja2 b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistDescription.jinja2 new file mode 100644 index 000000000..d4b12013f --- /dev/null +++ b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistDescription.jinja2 @@ -0,0 +1,5 @@ +

{% trans %} + To protect against known severe issues with certain versions of third party plugins, OctoPrint supports + the use of a centralized plugin version blacklist to automatically disable such plugins before they can interfere + with normal operation. +{% endtrans %}

diff --git a/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistEnabled.jinja2 b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistEnabled.jinja2 new file mode 100644 index 000000000..91576aee9 --- /dev/null +++ b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistEnabled.jinja2 @@ -0,0 +1,8 @@ +
+
+ +
+
diff --git a/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistTtl.jinja2 b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistTtl.jinja2 new file mode 100644 index 000000000..a586bac82 --- /dev/null +++ b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistTtl.jinja2 @@ -0,0 +1,9 @@ +
+ +
+
+ + min +
+
+
diff --git a/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistUrl.jinja2 b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistUrl.jinja2 new file mode 100644 index 000000000..781b18466 --- /dev/null +++ b/src/octoprint/templates/snippets/settings/server/serverPluginBlacklistUrl.jinja2 @@ -0,0 +1,6 @@ +
+ +
+ +
+
diff --git a/src/octoprint/util/version.py b/src/octoprint/util/version.py new file mode 100644 index 000000000..0b153a3ab --- /dev/null +++ b/src/octoprint/util/version.py @@ -0,0 +1,88 @@ +# coding=utf-8 +""" +This module provides a bunch of utility methods and helpers for version handling. +""" +from __future__ import absolute_import, division, print_function + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' + +import pkg_resources +import logging + +from octoprint._version import get_versions + + +_VERSION = get_versions()["version"] + + +def get_octoprint_version_string(): + return _VERSION + + +def get_octoprint_version(base=False): + octoprint_version_string = get_octoprint_version_string() + + if "-" in octoprint_version_string: + octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")] + + octoprint_version = pkg_resources.parse_version(octoprint_version_string) + + # A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's + # versions should never contain such a prefix, we'll make sure to have stuff behave the same + # regardless of setuptools version anyhow. + if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v": + octoprint_version = octoprint_version[1:] + + if base: + if isinstance(octoprint_version, tuple): + # old setuptools + base_version = [] + for part in octoprint_version: + if part.startswith("*"): + break + base_version.append(part) + base_version.append("*final") + octoprint_version = tuple(base_version) + else: + # new setuptools + octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) + return octoprint_version + + +def is_octoprint_compatible(*compatibility_entries, **kwargs): + """ + Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``. + + Arguments: + compatibility_entries (str): compatibility string(s) to test against, result will be `True` if any match + is found + octoprint_version (tuple or SetuptoolsVersion): optional OctoPrint version to match against, if not current + base version will be determined via :func:`get_octoprint_version`. + + Returns: + (bool) ``True`` if any of the provided compatibility entries matches or there are no entries, else ``False`` + """ + + logger = logging.getLogger(__name__) + + if not compatibility_entries: + return True + + octoprint_version = kwargs.get("octoprint_version") + if octoprint_version is None: + octoprint_version = get_octoprint_version(base=True) + + for octo_compat in compatibility_entries: + try: + if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")): + octo_compat = ">={}".format(octo_compat) + + s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat)) + if octoprint_version in s: + break + except: + logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat)) + else: + return False + + return True From 14b8fd7fa52171d1942fe5ecb167af971f37d8b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 25 Oct 2017 17:30:56 +0200 Subject: [PATCH 2/9] Only send "deactivated" status if password matches --- src/octoprint/server/api/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index deb7225ff..640822279 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -204,10 +204,10 @@ def login(): user = octoprint.server.userManager.findUser(username) if user is not None: - if not user.is_active(): - return make_response(("Your account is deactivated", 403, [])) - if octoprint.server.userManager.checkPassword(username, password): + if not user.is_active(): + return make_response(("Your account is deactivated", 403, [])) + if octoprint.server.userManager.enabled: user = octoprint.server.userManager.login_user(user) session["usersession.id"] = user.session From 77e48335da16b0f8b991e65689198c2fc3889bee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 26 Oct 2017 13:10:54 +0200 Subject: [PATCH 3/9] Virtual printer: support config of reset lines Also updated config docs accordingly. --- docs/configuration/config_yaml.rst | 80 ++++++++++++++++--- .../plugins/virtual_printer/virtual.py | 4 +- src/octoprint/settings.py | 7 +- 3 files changed, 76 insertions(+), 15 deletions(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index e934fb82f..81c147cd5 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -285,9 +285,13 @@ The following settings are only relevant to you if you want to do OctoPrint deve # to false. okWithLinenumber: false - # Number of extruders to simulate on the virtual printer. + # Number of extruders to simulate on the virtual printer. Map from tool id (0, 1, ...) to temperature + # in °C numExtruders: 1 + # Allows pinning certain hotends to a fixed temperature + pinnedExtruders: null + # Whether to include the current tool temperature in the M105 output as separate T segment or not. # # True: > M105 @@ -304,13 +308,6 @@ The following settings are only relevant to you if you want to do OctoPrint deve # > File opened includeFilenameInOpened: true - # The maximum movement speeds of the simulated printer's axes, in mm/s - movementSpeed: - x: 6000 - y: 6000 - z: 200 - e: 300 - # Whether the simulated printer should also simulate a heated bed or not hasBed: true @@ -331,6 +328,18 @@ The following settings are only relevant to you if you want to do OctoPrint deve # to make sure nothing gets lost on the line repetierStyleResends: false + # If enabled, ok will be sent before a commands output, otherwise after or inline (M105) + # + # True: > M20 + # < ok + # < Begin file list + # < End file list + # False: > M20 + # < Begin file list + # < End file list + # < ok + okBeforeCommandOutput: false + # If enabled, reports the first extruder in M105 responses as T instead of T0 # # True: > M105 @@ -358,7 +367,8 @@ The following settings are only relevant to you if you want to do OctoPrint deve # side will block rxBuffer: 64 - # Size of simulated command buffer + # Size of simulated command buffer, number of commands. If full, buffered commands will block + # until a slot frees up commandBuffer: 4 # Whether to support the M112 command with simulated kill @@ -370,6 +380,58 @@ The following settings are only relevant to you if you want to do OctoPrint deve # Whether to simulate broken M29 behaviour (missing ok after response) brokenM29: true + # Whether F is supported as individual command + supportF: false + + # Firmware name to report (useful for testing firmware detection) + firmwareName: Virtual Marlin 1.0 + + # Simulate a shared nozzle + sharedNozzle: false + + # Send "busy" messages if busy processing something + sendBusy: false + + # Simulate a reset on connect + simulateReset: true + + # Lines to send on simulated reset + resetLines: + - start + - Marlin: Virtual Marlin! + - "\x80" + - "SD card ok" + + # Initial set of prepared oks to use instead of regular ok (e.g. to simulate + # mis-sent oks). Can also be filled at runtime via the debug command prepare_ok + preparedOks: [] + + # Format string for ok response. + # + # Placeholders: + # - lastN: last acknowledged line number + # - buffer: empty slots in internal command buffer + # + # Example format string for "extended" ok format: + # ok N{lastN} P{buffer} + okFormatString: ok + + # Format string for M115 output. + # + # Placeholders: + # - firmare_name: The firmware name as defined in firmwareName + m115FormatString: "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0" + + # Whether to include capability report in M115 output + m115ReportCapabilites: false + + # Capabilities to report if capability report is enabled + capabilities: + AUTOREPORT_TEMP: true + + # Simulated ambient temperature in °C + ambientTemperature: 21.3 + .. _sec-configuration-config_yaml-estimation: Estimation diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 2434393e9..e102d0206 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -55,8 +55,8 @@ class VirtualPrinter(object): self.buffered = queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"])) if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]): - for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']: - self._send(item) + for item in settings().get(["devel", "virtualPrinter", "resetLines"]): + self._send(item + "\n") self._prepared_oks = [] prepared = settings().get(["devel", "virtualPrinter", "preparedOks"]) diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 7926af1b3..b91449947 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -365,12 +365,10 @@ default_settings = { "smoothieTemperatureReporting": False, "extendedSdFileList": False, "throttle": 0.01, - "waitOnLongMoves": False, - "rxBuffer": 64, - "txBuffer": 40, - "commandBuffer": 4, "sendWait": True, "waitInterval": 1.0, + "rxBuffer": 64, + "commandBuffer": 4, "supportM112": True, "echoOnM117": True, "brokenM29": True, @@ -379,6 +377,7 @@ default_settings = { "sharedNozzle": False, "sendBusy": False, "simulateReset": True, + "resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'], "preparedOks": [], "okFormatString": "ok", "m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0", From a1548e1c1d4d2c9b5dbe80c5005a99883ebd2e0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 26 Oct 2017 13:12:09 +0200 Subject: [PATCH 4/9] Fix issue in M115 parser If FIRMWARE_NAME is not there, but NAME is neither, we'd run into an exception due to the Malyan detection. Not anymore. Fixes #2181 --- src/octoprint/util/comm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index f1ee6be04..9799127a3 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -1386,7 +1386,7 @@ class MachineCom(object): # reliable firmware name (NAME + VER) out of the Malyan M115 response. name = data.get("NAME") ver = data.get("VER") - if "malyan" in name.lower() and ver: + if name and "malyan" in name.lower() and ver: firmware_name = name.strip() + " " + ver.strip() if not self._firmware_info_received and firmware_name: From 490ef61e198c39ec6fb0f5566a98e3afd0ee9520 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 26 Oct 2017 13:13:21 +0200 Subject: [PATCH 5/9] If serial.log is disabled, log how to enable it That will hopefully help a bit against the endless stream of "serial .log was empty" statements on the bug tracker. Or not. Here's hope. --- src/octoprint/__init__.py | 2 +- src/octoprint/printer/standard.py | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index e2d32cfc7..765fa308f 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -216,7 +216,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con }, "loggers": { "SERIAL": { - "level": "CRITICAL", + "level": "INFO", "handlers": ["serialFile"], "propagate": False }, diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 7379904ba..cd94590c2 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -208,6 +208,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): from octoprint.logging.handlers import SerialLogHandler SerialLogHandler.on_open_connection() + if not logging.getLogger("SERIAL").isEnabledFor(logging.DEBUG): + # if serial.log is not enabled, log a line to explain that to reduce "serial.log is empty" in tickets... + logging.getLogger("SERIAL").info("serial.log is currently not enabled, you can enable it via Settings > Serial Connection > Log communication to serial.log") self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager) From 2d925a266559ebd6d2f57dc3ae64e9fb14a826f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 26 Oct 2017 14:53:28 +0200 Subject: [PATCH 6/9] Synced with setup.py --- THIRDPARTYLICENSES.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index 30cc98a82..a8a4f733e 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -6,7 +6,7 @@ * [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD * [Bootstrap](http://getbootstrap.com/): Apache License 2.0 * [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0 - * [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT + * [Bootstrap Slider Knockout Binding](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT * [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0 * [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0 * [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain @@ -36,6 +36,8 @@ * [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3 * [chainmap](https://bitbucket.org/jeunice/chainmap): Python * [Click](http://click.pocoo.org/): BSD + * [dateutil](https://dateutil.readthedocs.io/): BSD + * [emoji](https://github.com/carpedm20/emoji/): BSD * [feedparser](https://github.com/kurtmckee/feedparser): BSD * [Flask](http://flask.pocoo.org/): BSD * [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD @@ -44,6 +46,7 @@ * [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD * [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT * [future](https://python-future.org/): MIT + * [futures](https://github.com/agronholm/pythonfutures): Python * [netaddr](https://github.com/drkjam/netaddr/): BSD * [netifaces](https://bitbucket.org/al45tair/netifaces): MIT * [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python @@ -60,6 +63,7 @@ * [Tornado](http://www.tornadoweb.org/): Apache License 2.0 * [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0 * [websocket-client](https://github.com/liris/websocket-client): LGPLv3 + * [wrapt](http://wrapt.readthedocs.org/): BSD ## Development (testing, documentation generation, etc) @@ -69,4 +73,5 @@ * [pypandoc](https://github.com/bebraw/pypandoc): MIT * [Sphinx](http://sphinx-doc.org/): BSD * [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD + * [sphinxcontrib-mermad](https://github.com/mgaitan/sphinxcontrib-mermaid): BSD * [sphinx_rtd_theme](https://github.com/snide/sphinx_rtd_theme/): BSD From 8bf3f4ff50079e8b778047b0e366475b07b41461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 26 Oct 2017 16:03:54 +0200 Subject: [PATCH 7/9] Rate limit snapshots on for z-timelapses This is to prevent against an endless stream of snapshots when accidentally printing a vase mode file despite the warning. As mentioned in #2067 --- THIRDPARTYLICENSES.md | 1 + setup.py | 3 +- src/octoprint/server/api/timelapse.py | 22 ++++++++---- .../static/js/app/viewmodels/timelapse.js | 36 ++++++++++++------- src/octoprint/templates/tabs/timelapse.jinja2 | 17 ++++++--- src/octoprint/timelapse.py | 30 +++++++++++++--- src/octoprint/util/__init__.py | 9 +++++ 7 files changed, 91 insertions(+), 27 deletions(-) diff --git a/THIRDPARTYLICENSES.md b/THIRDPARTYLICENSES.md index a8a4f733e..6f0dd0d3e 100644 --- a/THIRDPARTYLICENSES.md +++ b/THIRDPARTYLICENSES.md @@ -47,6 +47,7 @@ * [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT * [future](https://python-future.org/): MIT * [futures](https://github.com/agronholm/pythonfutures): Python + * [monotonic](https://github.com/atdt/monotonic): Apache License 2.0 * [netaddr](https://github.com/drkjam/netaddr/): BSD * [netifaces](https://bitbucket.org/al45tair/netifaces): MIT * [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python diff --git a/setup.py b/setup.py index 6cf46a1f0..9e1c924f8 100644 --- a/setup.py +++ b/setup.py @@ -51,7 +51,8 @@ INSTALL_REQUIRES = [ "python-dateutil>=2.6,<2.7", "wrapt>=1.10.10,<1.11", "futures>=3.1.1,<3.2", - "emoji>=0.4.5,<0.5" + "emoji>=0.4.5,<0.5", + "monotonic>=1.3,<1.4" ] if sys.platform == "darwin": diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py index 340e4d459..ae160c8ae 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -22,6 +22,7 @@ from octoprint.server.api import api from octoprint.server import NO_CONTENT +_DATA_FORMAT_VERSION = "v2" #~~ timelapse handling @@ -36,7 +37,8 @@ def _config_for_timelapse(timelapse): return dict(type="zchange", postRoll=timelapse.post_roll, fps=timelapse.fps, - retractionZHop=timelapse.retraction_zhop) + retractionZHop=timelapse.retraction_zhop, + minDelay=timelapse.min_delay) elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse): return dict(type="timed", postRoll=timelapse.post_roll, @@ -67,6 +69,7 @@ def _etag(unrendered, lm=None): hash = hashlib.sha1() hash.update(str(lm)) hash.update(repr(config)) + hash.update(repr(_DATA_FORMAT_VERSION)) return hash.hexdigest() @@ -219,10 +222,7 @@ def setTimelapseConfig(): except ValueError: return make_response("Invalid value for capturePostRoll: %r" % data["capturePostRoll"], 400) else: - if capturePostRoll >= 0: - config["options"]["capturePostRoll"] = capturePostRoll - else: - return make_response("Invalid value for capturePostRoll: %d" % capturePostRoll, 400) + config["options"]["capturePostRoll"] = capturePostRoll if "retractionZHop" in data: try: @@ -233,8 +233,18 @@ def setTimelapseConfig(): if retractionZHop >= 0: config["options"]["retractionZHop"] = retractionZHop else: - return make_response("Invalid value for retraction Z-Hop: %d" % retractionZHop, 400) + return make_response("Invalid value for retraction Z-Hop: %f" % retractionZHop, 400) + if "minDelay" in data: + try: + minDelay = float(data["minDelay"]) + except ValueError: + return make_response("Invalid value for minimum delay: %r" % data["minDelay"], 400) + else: + if minDelay >= 0: + config["options"]["minDelay"] = minDelay + else: + return make_response("Invalid value for minimum delay: %f" % minDelay, 400) if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues: octoprint.timelapse.configure_timelapse(config, True) diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js index e0b6417cd..2d60f33fd 100644 --- a/src/octoprint/static/js/app/viewmodels/timelapse.js +++ b/src/octoprint/static/js/app/viewmodels/timelapse.js @@ -10,6 +10,7 @@ $(function() { self.defaultPostRoll = 0; self.defaultInterval = 10; self.defaultRetractionZHop = 0; + self.defaultMinDelay = 5.0; self.defaultCapturePostRoll = true; self.timelapseType = ko.observable(undefined); @@ -17,6 +18,7 @@ $(function() { self.timelapsePostRoll = ko.observable(self.defaultPostRoll); self.timelapseFps = ko.observable(self.defaultFps); self.timelapseRetractionZHop = ko.observable(self.defaultRetractionZHop); + self.timelapseMinDelay = ko.observable(self.defaultMinDelay); self.timelapseCapturePostRoll = ko.observable(self.defaultCapturePostRoll); self.persist = ko.observable(false); @@ -42,10 +44,10 @@ $(function() { }); self.timelapseTypeSelected = ko.pureComputed(function() { - return ("off" != self.timelapseType()); + return ("off" !== self.timelapseType()); }); self.intervalInputEnabled = ko.pureComputed(function() { - return ("timed" == self.timelapseType()); + return ("timed" === self.timelapseType()); }); self.saveButtonEnabled = ko.pureComputed(function() { return self.isDirty() && !self.isPrinting() && self.loginState.isUser(); @@ -66,6 +68,9 @@ $(function() { self.timelapseRetractionZHop.subscribe(function(newValue) { self.isDirty(true); }); + self.timelapseMinDelay.subscribe(function() { + self.isDirty(true); + }); self.timelapseCapturePostRoll.subscribe(function() { self.isDirty(true); }); @@ -155,31 +160,37 @@ $(function() { // timelapse config self.timelapseType(config.type); - if (config.type == "timed" && config.interval != undefined && config.interval > 0) { + if (config.type === "timed" && config.interval !== undefined && config.interval > 0) { self.timelapseTimedInterval(config.interval); } else { self.timelapseTimedInterval(self.defaultInterval); } - if (config.type == "timed" && config.capturePostRoll != undefined){ + if (config.type === "timed" && config.capturePostRoll !== undefined){ self.timelapseCapturePostRoll(config.capturePostRoll); } else { self.timelapseCapturePostRoll(self.defaultCapturePostRoll); } - if (config.type == "zchange" && config.retractionZHop != undefined && config.retractionZHop > 0) { + if (config.type === "zchange" && config.retractionZHop !== undefined && config.retractionZHop > 0) { self.timelapseRetractionZHop(config.retractionZHop); } else { self.timelapseRetractionZHop(self.defaultRetractionZHop); } - if (config.postRoll != undefined && config.postRoll >= 0) { + if (config.type === "zchange" && config.minDelay !== undefined && config.minDelay >= 0) { + self.timelapseMinDelay(config.minDelay); + } else { + self.timelapseMinDelay(self.defaultMinDelay); + } + + if (config.postRoll !== undefined && config.postRoll >= 0) { self.timelapsePostRoll(config.postRoll); } else { self.timelapsePostRoll(self.defaultPostRoll); } - if (config.fps != undefined && config.fps > 0) { + if (config.fps !== undefined && config.fps > 0) { self.timelapseFps(config.fps); } else { self.timelapseFps(self.defaultFps); @@ -363,13 +374,14 @@ $(function() { "save": self.persist() }; - if (self.timelapseType() == "timed") { + if (self.timelapseType() === "timed") { payload["interval"] = self.timelapseTimedInterval(); payload["capturePostRoll"] = self.timelapseCapturePostRoll(); } - if (self.timelapseType() == "zchange") { + if (self.timelapseType() === "zchange") { payload["retractionZHop"] = self.timelapseRetractionZHop(); + payload["minDelay"] = self.timelapseMinDelay(); } OctoPrint.timelapse.saveConfig(payload) @@ -384,7 +396,7 @@ $(function() { _.extend(options, { callbacks: { before_close: function(notice) { - if (self.timelapsePopup == notice) { + if (self.timelapsePopup === notice) { self.timelapsePopup = undefined; } } @@ -465,7 +477,7 @@ $(function() { self.onEventMovieFailed = function(payload) { var title, html; - if (payload.reason == "no_frames") { + if (payload.reason === "no_frames") { title = gettext("Cannot render timelapse"); html = "

" + _.sprintf(gettext("Rendering of timelapse %(movie_prefix)s is not possible since no frames were captured. Is the snapshot URL configured correctly?"), payload) + "

"; } else if (payload.reason = "returncode") { @@ -492,7 +504,7 @@ $(function() { type: "success", callbacks: { before_close: function(notice) { - if (self.timelapsePopup == notice) { + if (self.timelapsePopup === notice) { self.timelapsePopup = undefined; } } diff --git a/src/octoprint/templates/tabs/timelapse.jinja2 b/src/octoprint/templates/tabs/timelapse.jinja2 index 1ea865d73..df81a93e0 100644 --- a/src/octoprint/templates/tabs/timelapse.jinja2 +++ b/src/octoprint/templates/tabs/timelapse.jinja2 @@ -16,20 +16,20 @@
- + {{ _('sec') }}
- + {{ _('fps') }}
- + {{ _('sec') }}
@@ -42,12 +42,21 @@
- + {{ _('mm') }}
{{ _('Enter the retraction z-hop used in the firmware or the gcode file to trigger snapshots for the timelapse only if a real layer change happens. For this to work properly your retraction z-hop has to be different from your layerheight!') }}
+
+ +
+ + {{ _('sec') }} +
+ {{ _('OctoPrint will not allow a snapshot to be taken based on a z-change unless the last one was more than this delay ago. This is to prevent issues if you accidentally print a vase mode type file while this timelapse mode is active.') }} +
+