diff --git a/.versioneer-lookup b/.versioneer-lookup index ed09d1585..d08eaf68e 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -18,12 +18,12 @@ HEAD # maintenance is currently the branch for preparation of maintenance release 1.3.5 # so are any fix/... and improve/... branches -maintenance 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev -fix/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev -improve/.* 1.3.5 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev +maintenance 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev +fix/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev +improve/.* 1.3.6 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.3.5rc1 -staging/maintenance 1.3.5rc1 fe481e12b3c50a2def3b41515200e13a8c6a5c72 pep440-dev +# staging/maintenance is currently the branch for preparation of 1.3.5rc2 +staging/maintenance 1.3.5rc2 1a6dbb3f4a5bef857cdeb13c031b9deca2cf30a2 pep440-dev # every other branch is a development branch and thus gets resolved to 1.4.0-dev for now .* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a36cf58f..06906f238 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,76 @@ # OctoPrint Changelog +## 1.3.5rc1 (2017-07-26) + +### Improvements + + * [#1162](https://github.com/foosel/OctoPrint/pull/1162) - Allow `octoprint.comm.protocol.gcode.queuing` hook to return a list of commands. + * [#1572](https://github.com/foosel/OctoPrint/issues/1572) & [#1881](https://github.com/foosel/OctoPrint/issues/1881) - Refactored web interface startup process to minimise risk of race conditions and speed improvements. Also added sequence diagram to the documentation showing the new processing order. + * [#1640](https://github.com/foosel/OctoPrint/issues/1640) - Mouse over temperature graph to get exact data for that time. + * [#1679](https://github.com/foosel/OctoPrint/issues/1679) - Support temperature autoreporting by the firmware instead of polling if the firmware reports to support it. For this to work with Marlin 1.1.0 to 1.1.3 you'll need to explicitly enable `EXTENDED_CAPABILITIES_REPORT` *and* `AUTO_REPORT_TEMPERATURES` in your firmware configuration, otherwise your firmware won't report that it actually supports this feature. + * [#1737](https://github.com/foosel/OctoPrint/issues/1737) - Auto-detect Anet A8 firmware and treat as Repetier Firmware (which it actually appears to be, just renamed - thanks Anet for making this even harder). + * [#1842](https://github.com/foosel/OctoPrint/issues/1842) - Update bundled FontAwesome to 4.7 (see also [#1915](https://github.com/foosel/OctoPrint/pull/1915)). + * [#1910](https://github.com/foosel/OctoPrint/issues/1910) - Make last/pause/cancel temperature available for GCODE scripts. + * [#1925](https://github.com/foosel/OctoPrint/issues/1925) - Include configured webcam stream URL in "Webcam stream not loaded" message for logged in users/admins. Slightly different wording for guests vs users vs admins. + * [#1941](https://github.com/foosel/OctoPrint/issues/1941) - Enable "block while dwelling" flag when Malyan firmware is detected since that firmware seems to handle `G4` identically to Repetier Firmware instead of Marlin (like it claims to). See also [#1762](https://github.com/foosel/OctoPrint/issues/1762). + * [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Add option to disable position logging on cancel/pause. See "Log position on cancel" and "Log position on pause" under Settings > Serial > Advanced options. + * [#1971](https://github.com/foosel/OctoPrint/issues/1971) - Refactored temperature inputs. They now sport some fancy +/- buttons to increment/decrement the current temperature (which also auto submit after a couple of seconds) and easier editing by keyboard. The temperature offset was also slightly redesigned to make room for that. + * [#1975](https://github.com/foosel/OctoPrint/issues/1975) - Better error reporting when deleting timelapses. + * [#2010](https://github.com/foosel/OctoPrint/pull/2010) - Slight refactoring in the terminal tab: Full width input field, auto focus of input field when just clicking on terminal output. + * [#2011](https://github.com/foosel/OctoPrint/issues/2011) - Centralized online connectivity check (with opt-in of course). None of the bundled plugins will attempt to fetch data from the net when the connectivity check indicates that would fail anyhow. This should improve server startup times and various requests when running isolated. + * [#2025](https://github.com/foosel/OctoPrint/issues/2025) - More verbose logging of asynchronous system commands (e.g. restart/shutdown). + * Allow timelapse configuration through UI even when not connected to the printer (suggested in [#1918](https://github.com/foosel/OctoPrint/issues/1918)) + * Disable "Upload to SD" UI elements while printing (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914)) + * Update bundled SockJS to 1.1.2 incl. source maps + * Set `X-Robots` HTTP header and remove `Server` header from all responses, also set `robots` meta tag in page. + * Don't require to enter programmer mode for printer port autodetection when there's only one possible port candidate anyhow. + * More sensible sorting of baudrates (additionally configured, then 115200, then 250000, then everything else). + * Don't show "Unhandled communication error" on autodetection failure. + * Make timeout after which to unload the webcam stream after navigating away from it configurable (as suggested in [#1937](https://github.com/foosel/OctoPrint/issues/1937)) + * Add `ToolChange` event and tool change GCODE scripts + * Support parsing GCODE subcodes. + * Add `octoprint.users.factory` hook, allowing plugins to extend/swap out the user manager OctoPrint uses. + * Corewizard: Disable view model and client code if it's not actually required. + * Corewizard: Disable injection of JS files into UI when it's not actually required. + * GCODE analysis: Moved into its own subprocess. That should improve performance on multi core systems. + * GCODE viewer: Ignore coordinates outside bed when zooming/centering on model. Those usually are nozzle priming routines. + * JS Client Lib: Add centralized browser detection as `OctoPrint.coreui.browser`. Available properties: `chrome`, `firefox`, `safari`, `ie`, `edge`, `opera` as well as `mobile` and `desktop`, all of which are boolean values. + * Plugin Manager plugin: Detect if a plugin requires a reconnect to the printer to become fully active/inactive. + * Software Update plugin: Force exact version when updating OctoPrint and tracking releases. + * Software Update plugin: "Devel RCs" release channel now also tracks maintenance RCs. That way people don't have to toggle between the two any more to get *all* RCs. + * Software Update plugin: `bitbucket_commit` check type now supports API credentials (see also [#1993](https://github.com/foosel/OctoPrint/pull/1993)). + * Wizard: Allow suppressing the "the settings got updated" dialog through subwizards, in case they need to update settings asynchronously as part of their workflow. + * More resilience against expected folders being files. + * More resilience against a wrong user manager class being configured. + * Some code refactoring & cleanup. + * Some HTML & CSS improvements. + +### Bug fixes + + * [#1916](https://github.com/foosel/OctoPrint/issues/1916) - Fix webcam not loading if first/initial tab is "Control" + * [#1924](https://github.com/foosel/OctoPrint/issues/1924) - Filter out source map links from bundled JS webassets. + * [#1943](https://github.com/foosel/OctoPrint/issues/1943) - Fix issue causing unnecessary creation of default printer profile on startup + * [#1946](https://github.com/foosel/OctoPrint/issues/1946) - Decouple writing of print log from everything else. Fixes delay in cancel processing. + * [#1963](https://github.com/foosel/OctoPrint/issues/1963) & [#1974](https://github.com/foosel/OctoPrint/issues/1974) - Allow empty & custom size in print job events. Also fixes an issue with timelapses when printing from SD on printers that require the GPX plugin to work. + * [#1996](https://github.com/foosel/OctoPrint/issues/1996) - Support all line ending variantes in the GCODE viewer. Solves an issue with GCODE generated for Prusa's multi material extruder since that uses only `\r` for some reason. + * [#2007](https://github.com/foosel/OctoPrint/issues/2007) - Fix issue parsing temperature lines from the printer that contain negative values. + * [#2012](https://github.com/foosel/OctoPrint/issues/2012) - Fix command line interface of Software Update plugin. + * [#2017](https://github.com/foosel/OctoPrint/issues/2017) - Fix issue in GCODE viewer with files that contain a visit to the first layer twice (e.g. brim, then nose dive from higher z for actual model), causing all but the last layer segment to not be rendered. + * Fix various popup buttons allowing multiple clicks (suggested in [#1914](https://github.com/foosel/OctoPrint/issues/1914)) + * Software Update Plugin: Perform server restart asynchronously. Should reduce restart times on updates significantly. + * Don't hex-escape `\t`, `\r` or `\n` in terminal output + * Use client side default printer profile if the default profile could not be found on the server + * Use both "to" and "from" coordinates of a given move for min/max model coordinate calculation in GCODE analysis. Otherwise wrong values could be calculated under certain circumstances. + * Fix potential race condition in resend request handling. + * Fix potential race condition in web socket handling. + * Fix handling of tool offsets in GCODE analysis - diverted too far from firmware implementations, causing wrong calculations. + * Fix `FileAdded`, `FileRemoved`, `FolderAdded`, `FolderRemoved` events not being fired with the correct event name. + * Fix potential division by zero in progress reporting if the timing was just right. + * Fix sorting order for multiple tools in the "State" panel. + * Fix file position vs. line ending handling in GCODE viewer. Could lead to slightly off file position calculation and hence possibly to the wrong move being plotted when synchronizing with print progress. + +([Commits](https://github.com/foosel/OctoPrint/compare/1.3.4...1.3.5rc1)) + ## 1.3.4 (2017-06-01) ### Note for owners of Malyan M200/Monoprice Select Mini diff --git a/SUPPORTERS.md b/SUPPORTERS.md index 2909b8101..6cb81dcbb 100644 --- a/SUPPORTERS.md +++ b/SUPPORTERS.md @@ -7,6 +7,7 @@ thanks to everyone who contributed! ## Patreon Patrons * 3D Moniak + * Aaron Lieberman * Aleph Objects, Inc. * Andrew Moorby * Arnljot Arntsen @@ -14,24 +15,24 @@ thanks to everyone who contributed! * Boris Hussein * Brad Jackson * Brian E. Tyler - * Chris Day * Christian Petropolis + * COLLE+McVOY * CreativeTools * D Brian Kimmel * DeltaMaker 3D Printers - * Doug Johnson * E3D BigBox * Ernesto Martinez * Exovite * F. Kunsmann + * Farren Young II * Frank Sander * Gary Deen * Gary N McKinney * George Robles * günter weber - * Ivan Krasin * James Seigel * Jamie R McGuigan + * Jason Lawrence * Jeff Moe * Josh Daniels * Kaile Riser @@ -55,14 +56,14 @@ thanks to everyone who contributed! * Roger Strolz * Roy Cortes * Samer Najia - * SD3D * SeeMeCNC * Simon Hallam * Stefan Krister * Stephane Schittly * Sven Mueller + * Symbiotic Devices * Thomas Hatley * Timeshell.ca * Trent Shumay -and 1098 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file +and 1117 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)! \ No newline at end of file diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index debb35d16..e934fb82f 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -909,6 +909,20 @@ Use the following settings to configure the server: # Command to shut down the system OctoPrint is running on, defaults to being unset systemShutdownCommand: sudo shutdown -h now + # Configuration of the regular online connectivity check + onlineCheck: + # whether the online check is enabled, defaults to false due to valid privacy concerns + enabled: false + + # interval in which to check for online connectivity (in seconds) + interval: 300 + + # DNS host against which to check (default: 8.8.8.8 aka Google's DNS) + host: 8.8.8.8 + + # DNS port against which to check (default: 53 - the default DNS port) + port: 53 + # Settings of when to display what disk space warning diskspace: diff --git a/docs/events/index.rst b/docs/events/index.rst index bc6f1245f..225331f5a 100644 --- a/docs/events/index.rst +++ b/docs/events/index.rst @@ -110,6 +110,14 @@ ClientClosed * ``remoteAddress``: the remote address (IP) of the client that disconnected +ConnectivityChanged + The server's internet connectivity changed + + Payload: + + * ``old``: Old connectivity value (true for online, false for offline) + * ``new``: New connectivity value (true for online, false for offline) + Printer communication --------------------- diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index 6b14a616b..9c12a35c7 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -87,6 +87,9 @@ There are a few additional template variables available for the following specif * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. See ``last_position`` above for the structure to expect here. + + **Please note:** This will not be available if you disable + "Log position on pause" under Settings > Serial > Advanced options! * ``pause_temperature``: Last known temperature values when the print was paused. See ``last_temperature`` above for the structure to expect here. @@ -94,6 +97,9 @@ There are a few additional template variables available for the following specif * ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. See ``last_position`` above for the structure to expect here. + + **Please note:** This will not be available if you disable + "Log position on cancel" under Settings > Serial > Advanced options! * ``cancel_temperature``: Last known temperature values when the print was cancelled. See ``last_temperature`` above for the structure to expect here. diff --git a/docs/modules/index.rst b/docs/modules/index.rst index 1cdb36a0a..0f67513b7 100644 --- a/docs/modules/index.rst +++ b/docs/modules/index.rst @@ -14,4 +14,5 @@ Internal Modules server.rst settings.rst slicing.rst + users.rst util.rst diff --git a/docs/modules/users.rst b/docs/modules/users.rst new file mode 100644 index 000000000..f147a46a3 --- /dev/null +++ b/docs/modules/users.rst @@ -0,0 +1,9 @@ +.. _sec-modules-users: + +octoprint.users +--------------- + +.. automodule:: octoprint.users + :members: + + diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 9d20c3a2d..ed69d9967 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -426,7 +426,7 @@ This describes actually four hooks: * ``None``: Don't change anything. Note that Python functions will also automatically return ``None`` if an empty ``return`` statement is used or just nothing is returned explicitly from the handler. Hence, the following - examples are all falling into this category: + examples are all falling into this category and equivalent: .. code-block:: python @@ -451,21 +451,24 @@ This describes actually four hooks: should use this option. * A 2-tuple consisting of a rewritten version of the ``cmd`` and the ``cmd_type``, e.g. ``return "M105", "temperature_poll"``. Handlers which wish to rewrite both the command and the command type should use this option. - * A list of any of the above to allow for expanding one command into + * **"queuing" phase only**: A list of any of the above to allow for expanding one command into many. The following example shows how any queued command could be turned into a sequence of a temperature query, line number reset, display of the ``gcode`` on the printer's display and finally the actual command (this example does not make a lot of sense to be quite honest): .. code-block:: python - def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): - if gcode or not cmd.startswith("@foo"): - return + def rewrite_foo(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs): + if gcode or not cmd.startswith("@foo"): + return - return [("M105", "temperature_poll"), - ("M110",), - "M117 echo foo: {}".format(cmd)] + return [("M105", "temperature_poll"), # 2-tuple, command & command type + ("M110",), # 1-tuple, just the command + "M117 echo foo: {}".format(cmd)] # string, just the command + __plugin_hooks__ = { + "octoprint.comm.protocol.gcode.queuing": rewrite_foo + } Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type`` to one already in the queue will give an error. @@ -944,6 +947,41 @@ octoprint.ui.web.templatetypes :return: a list of 3-tuples (template type, rule, sorting spec) :rtype: list +.. _sec-plugins-hook-users-factory: + +octoprint.users.factory +~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: user_manager_factory_hook(components, settings, *args, **kwargs) + + Return a :class:`~octoprint.users.UserManager` instance to use as global user manager object. This will + be called only once during initial server startup. + + The provided ``components`` is a dictionary containing the already initialized system components: + + * ``plugin_manager``: The :class:`~octoprint.plugin.core.PluginManager` + * ``printer_profile_manager``: The :class:`~octoprint.printer.profile.PrinterProfileManager` + * ``event_bus``: The :class:`~octoprint.events.EventManager` + * ``analysis_queue``: The :class:`~octoprint.filemanager.analysis.AnalysisQueue` + * ``slicing_manager``: The :class:`~octoprint.slicing.SlicingManager` + * ``file_manager``: The :class:`~octoprint.filemanager.FileManager` + * ``app_session_manager``: The :class:`~octoprint.server.util.flask.AppSessionManager` + * ``plugin_lifecycle_manager``: The :class:`~octoprint.server.LifecycleManager` + * ``preemptive_cache``: The :class:`~octoprint.server.util.flask.PreemptiveCache` + + If the factory returns anything but ``None``, it will be assigned to the global ``userManager`` instance. + + If no of the registered factories return a user manager instance, the class referenced by the ``config.yaml`` + entry ``accessControl.userManager`` will be initialized if possible, otherwise a stock + :class:`~octoprint.users.FilebasedUserManager` will be instantiated, linked to the default user storage + file ``~/.octoprint/users.yaml``. + + :param dict components: System components to use for user manager instance initialization + :param SettingsManager settings: The global settings manager instance to fetch configuration values from if necessary + :return: The ``userManager`` instance to use globally. + :rtype: UserManager subclass or None + + .. _sec-plugins-hook-timelapse-capture-pre: octoprint.timelapse.capture.pre @@ -974,4 +1012,4 @@ octoprint.timelapse.capture.post :param str filename: The path of the frame that should have been saved. :param boolean success: Indicates whether the capture was successful or not. :return: None - :rtype: None \ No newline at end of file + :rtype: None diff --git a/docs/plugins/injectedproperties.rst b/docs/plugins/injectedproperties.rst index 4fbf2a3bc..0e063773a 100644 --- a/docs/plugins/injectedproperties.rst +++ b/docs/plugins/injectedproperties.rst @@ -45,6 +45,8 @@ An overview of these properties follows. OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`. ``self._user_manager`` OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`. +``self._connectivity_checker`` + OctoPrint's connectivity checker, an instance of :class:`octoprint.util.ConnectivityChecker`. .. seealso:: diff --git a/setup.py b/setup.py index c2e41193c..0a0f6b717 100644 --- a/setup.py +++ b/setup.py @@ -46,7 +46,8 @@ INSTALL_REQUIRES = [ "scandir>=1.3,<1.4", "websocket-client>=0.40,<0.41", "python-dateutil>=2.6,<2.7", - "wrapt>=1.10.10,<1.11" + "wrapt>=1.10.10,<1.11", + "futures>=3.1.1,<3.2" ] if sys.platform == "darwin": diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 97fcce652..b40f710c3 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -9,7 +9,7 @@ import json import octoprint_client -from octoprint.cli import get_ctx_obj_option +from octoprint.cli import get_ctx_obj_option, bulk_options from octoprint import init_settings, FatalStartupError @@ -23,43 +23,66 @@ class JsonStringParamType(click.ParamType): self.fail("%s is not a valid json string" % value, param, ctx) +def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None): + assert(host is not None or settings is not None) + assert(port is not None or settings is not None) + assert(apikey is not None or settings is not None) + + if not host: + host = settings.get(["server", "host"]) + host = host if host != "0.0.0.0" else "127.0.0.1" + if not port: + port = settings.getInt(["server", "port"]) + + if not apikey: + apikey = settings.get(["api", "key"]) + + baseurl = octoprint_client.build_base_url(https=https, + httpuser=httpuser, + httppass=httppass, + host=host, + port=port, + prefix=prefix) + + return octoprint_client.Client(baseurl, apikey) + + +client_options = bulk_options([ + click.option("--apikey", "-a", type=click.STRING), + click.option("--host", "-h", type=click.STRING), + click.option("--port", "-p", type=click.INT), + click.option("--httpuser", type=click.STRING), + click.option("--httppass", type=click.STRING), + click.option("--https", is_flag=True), + click.option("--prefix", type=click.STRING) +]) +"""Common options to configure an API client.""" + + @click.group() def client_commands(): pass @client_commands.group("client", context_settings=dict(ignore_unknown_options=True)) -@click.option("--apikey", "-a", type=click.STRING) -@click.option("--host", "-h", type=click.STRING) -@click.option("--port", "-p", type=click.INT) -@click.option("--httpuser", type=click.STRING) -@click.option("--httppass", type=click.STRING) -@click.option("--https", is_flag=True) -@click.option("--prefix", type=click.STRING) +@client_options @click.pass_context def client(ctx, apikey, host, port, httpuser, httppass, https, prefix): """Basic API client.""" try: + settings = None if not host or not port or not apikey: settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None)) - if not host: - host = settings.get(["server", "host"]) - host = host if host != "0.0.0.0" else "127.0.0.1" - if not port: - port = settings.getInt(["server", "port"]) + ctx.obj.client = create_client(settings=settings, + apikey=apikey, + host=host, + port=port, + httpuser=httpuser, + httppass=httppass, + https=https, + prefix=prefix) - if not apikey: - apikey = settings.get(["api", "key"]) - - baseurl = octoprint_client.build_base_url(https=https, - httpuser=httpuser, - httppass=httppass, - host=host, - port=port, - prefix=prefix) - - ctx.obj.client = octoprint_client.Client(baseurl, apikey) except FatalStartupError as e: click.echo(e.message, err=True) click.echo("There was a fatal error initializing the client.", err=True) diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index 8b13eb1c5..e650129b1 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -60,6 +60,8 @@ class OctoPrintPluginCommands(click.MultiCommand): # fetch registered hooks self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") + logging.basicConfig(level=logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARN) + self._initialized = True def list_commands(self, ctx): @@ -88,14 +90,14 @@ class OctoPrintPluginCommands(click.MultiCommand): continue result[name + self.sep + command.name] = command except: - self._logger.exception("Error while retrieving cli commants for plugin {}".format(name)) + self._logger.exception("Error while retrieving cli commands for plugin {}".format(name)) return result @click.group() @pass_octoprint_ctx def plugin_commands(obj): - logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN) + pass @plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands) def plugins(): diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 3c39c71b3..7f9b818fd 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -27,9 +27,10 @@ def all_events(): class Events(object): - # application startup + # server STARTUP = "Startup" SHUTDOWN = "Shutdown" + CONNECTIVITY_CHANGED = "ConnectivityChanged" # connect/disconnect to printer CONNECTING = "Connecting" diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index 1f78abae7..1021b169a 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -135,3 +135,16 @@ def get_divider_line(c, message=None, length=78, indent=3): return c * indent + " " + message + " " + c * (length - indent - 2 - len(message)) else: return c * indent + " " + message + + +def prefix_multilines(text, prefix=": "): + lines = text.splitlines() + if not lines: + return "" + + if len(lines) == 1: + return lines[0] + + return lines[0] + "\n" + "\n".join(map(lambda line: prefix + line, + lines[1:])) + diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index d6214d626..2f77e2c49 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -177,7 +177,7 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) -def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None): +def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True): """ Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success @@ -213,6 +213,8 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. + initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status + is determined be presence of injected ``_identifier`` property. """ @@ -225,6 +227,9 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context) for plugin in plugins: + if initialized and not hasattr(plugin, "_identifier"): + continue + if hasattr(plugin, method): try: result = getattr(plugin, method)(*args, **kwargs) diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 7f73efb20..ce776d725 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -28,7 +28,8 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.BlueprintPlugin, octoprint.plugin.StartupPlugin, - octoprint.plugin.TemplatePlugin): + octoprint.plugin.TemplatePlugin, + octoprint.plugin.EventHandlerPlugin): def __init__(self): self._cached_channel_configs = None @@ -210,6 +211,14 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, return NO_CONTENT + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + from octoprint.events import Events + if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): + return + self._fetch_all_channels_async() + # Internal Tools def _mark_read_until(self, channel, until): @@ -266,6 +275,11 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, safe_key = self._slugify(key) return self._get_channel_configs(force=force).get(safe_key) + def _fetch_all_channels_async(self, force=False): + thread = threading.Thread(target=self._fetch_all_channels, kwargs=dict(force=force)) + thread.daemon = True + thread.start() + def _fetch_all_channels(self, force=False): """Fetch all channel feeds from cache or network.""" @@ -298,7 +312,10 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, if data is None: # cache not allowed or empty, fetch from network - data = self._get_channel_data_from_network(key, config) + if self._connectivity_checker.online: + data = self._get_channel_data_from_network(key, config) + else: + self._logger.info("Looks like we are offline, can't fetch announcements for channel {} from network".format(key)) return data diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index a5af767d0..dd31096ee 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -40,7 +40,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = data.enabled ? "fa fa-circle" : "fa fa-circle-o"; + var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -317,7 +317,13 @@ $(function() { self.announcementDialog = $("#plugin_announcements_dialog"); self.announcementDialogContent = $("#plugin_announcements_dialog_content"); self.announcementDialogTabs = $("#plugin_announcements_dialog_tabs"); + }; + + self.onEventConnectivityChanged = function(payload) { + if (!payload || !payload.new) return; + self.retrieveData(); } + } // view model class, parameters for constructor, container to bind to diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index 6b7a5cd8b..cdaf49620 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -59,8 +59,14 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, #~~ WizardPlugin API def is_wizard_required(self): - methods = self._get_subwizard_attrs("_is_", "_wizard_required") - return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values())) + required = self._get_subwizard_attrs("_is_", "_wizard_required") + firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly") + firstrun = self._settings.global_get(["server", "firstRun"]) + + any_not_firstrunonly = any(map(lambda m: not m(), firstrunonly.values())) + any_required = any(map(lambda m: m(), required.values())) + + return (firstrun or any_not_firstrunonly) and any_required def get_wizard_details(self): result = dict() @@ -71,8 +77,14 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return result + def get_wizard_version(self): + return 1 + #~~ ACL subwizard + def _is_acl_wizard_firstrunonly(self): + return True + def _is_acl_wizard_required(self): return self._user_manager.enabled and not self._user_manager.hasBeenCustomized() @@ -114,6 +126,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, #~~ Webcam subwizard + def _is_webcam_wizard_firstrunonly(self): + return True + def _is_webcam_wizard_required(self): webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"]) webcam_stream_url = self._settings.global_get(["webcam", "stream"]) @@ -129,6 +144,9 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, #~~ Server commands subwizard + def _is_servercommands_wizard_firstrunonly(self): + return True + def _is_servercommands_wizard_required(self): system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"]) system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"]) @@ -142,8 +160,28 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, def _get_servercommands_wizard_name(self): return gettext("Server Commands") + #~~ Online check subwizard + + def _is_onlinecheck_wizard_firstrunonly(self): + return False + + def _is_onlinecheck_wizard_required(self): + return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None + + def _get_onlinecheck_wizard_details(self): + return dict(required=self._is_onlinecheck_wizard_required()) + + def _get_onlinecheck_wizard_name(self): + return gettext("Online connectivity check") + + def _get_onlinecheck_additional_wizard_template_data(self): + return dict(mandatory=self._is_onlinecheck_wizard_required()) + #~~ Printer profile subwizard + def _is_printerprofile_wizard_firstrunonly(self): + return True + def _is_printerprofile_wizard_required(self): return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1 diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index b59b676b2..2a09a07b3 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -125,6 +125,88 @@ $(function() { self.settingsViewModel = parameters[0]; } + function CoreWizardOnlineCheckViewModel(parameters) { + var self = this; + + self.settingsViewModel = parameters[0]; + + self.setup = ko.observable(false); + + self.decision = ko.observable(); + self.required = false; + self.active = false; + + self.enableOnlineCheck = function() { + self.settingsViewModel.server_onlineCheck_enabled(true); + self.decision(true); + self._sendData(); + }; + + self.disableOnlineCheck = function() { + self.settingsViewModel.server_onlineCheck_enabled(false); + self.decision(false); + self._sendData(); + }; + + self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + + if (!current || !_.startsWith(current, "wizard_plugin_corewizard_onlinecheck_") || 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.onlinecheck && response.corewizard.details.onlinecheck.required; + }; + + self._showDecisionNeededDialog = function() { + showMessageDialog({ + title: gettext("Please set up the online connectivity check"), + message: gettext("You haven't yet decided on whether to enable or disable the online connectivity check. You need to either enable or disable it before continuing.") + }); + }; + + self._sendData = function() { + var data = { + server: { + onlineCheck: { + enabled: self.settingsViewModel.server_onlineCheck_enabled(), + interval: self.settingsViewModel.server_onlineCheck_interval(), + host: self.settingsViewModel.server_onlineCheck_host(), + port: self.settingsViewModel.server_onlineCheck_port() + } + } + }; + + self.active = true; + self.settingsViewModel.saveData(data) + .done(function() { + self.setup(true); + self.active = false; + }); + }; + + } + function CoreWizardPrinterProfileViewModel(parameters) { var self = this; @@ -172,6 +254,10 @@ $(function() { CoreWizardServerCommandsViewModel, ["settingsViewModel"], "#wizard_plugin_corewizard_servercommands" + ], [ + CoreWizardOnlineCheckViewModel, + ["settingsViewModel"], + "#wizard_plugin_corewizard_onlinecheck" ], [ CoreWizardPrinterProfileViewModel, ["printerProfilesViewModel"], diff --git a/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 new file mode 100644 index 000000000..15dc69c09 --- /dev/null +++ b/src/octoprint/plugins/corewizard/templates/corewizard_onlinecheck_wizard.jinja2 @@ -0,0 +1,46 @@ +

{{ _('Configure the connectivity check') }}

+ +{% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %} + +

{% trans %} + If it is disabled OctoPrint will always assume to have a working connection to the internet. + If that should not actually be the case, server startups, update checks and the like might take longer. +{% endtrans %}

+ +

{% trans %} + OctoPrint comes preconfigured to perform the connectivity check every 15 minutes. You may change the value here. +{% endtrans %}

+ +
+ {% include "snippets/settings/server/serverOnlineCheckInterval.jinja2" %} +
+ +

{% trans %} + OctoPrint comes preconfigured to utilize Google's DNS server 8.8.8.8, port 53 for the connectivity check (if + it's enabled). If you have concerns about using that, define the IP and port of a different online server that you + trust and that has a high availability. +{% endtrans %}

+ +
+ {% include "snippets/settings/server/serverOnlineCheckHost.jinja2" %} + {% include "snippets/settings/server/serverOnlineCheckPort.jinja2" %} +
+ +

{% trans %} + Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at + any time to a later date through Settings > Server right from within OctoPrint. +{% endtrans %}

+ +
+ {{ _('Disable Connectivity Check') }} + {{ _('Enable Connectivity Check') }} +
+ + diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 9e5755802..8ec6ce907 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -36,7 +36,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin, - octoprint.plugin.BlueprintPlugin): + octoprint.plugin.BlueprintPlugin, + octoprint.plugin.EventHandlerPlugin): ARCHIVE_EXTENSIONS = (".zip", ".tar.gz", ".tgz", ".tar") @@ -100,13 +101,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._console_logger.propagate = False # decouple repository fetching from server startup - def fetch_data(): - self._repository_available = self._fetch_repository_from_disk() - self._notices_available = self._fetch_notices_from_disk() - - thread = threading.Thread(target=fetch_data) - thread.daemon = True - thread.start() + self._fetch_all_data(async=True) ##~~ SettingsPlugin @@ -197,6 +192,14 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, except Exception as e: self._logger.warn("Could not remove temporary file {path} again: {message}".format(path=archive.name, message=str(e))) + ##~~ EventHandlerPlugin + + def on_event(self, event, payload): + from octoprint.events import Events + if event != Events.CONNECTIVITY_CHANGED or not payload or not payload.get("new", False): + return + self._fetch_all_data(async=True) + ##~~ SimpleApiPlugin def get_api_commands(self): @@ -239,7 +242,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, additional_args=self._settings.get(["pip_args"]), python=sys.executable ), - safe_mode=safe_mode) + safe_mode=safe_mode, + online=self._connectivity_checker.online) def etag(): import hashlib @@ -250,6 +254,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, hash.update(str(self._notices_available)) hash.update(repr(self._notices)) hash.update(repr(safe_mode)) + hash.update(repr(self._connectivity_checker.online)) return hash.hexdigest() def condition(): @@ -679,6 +684,18 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, elif (plugin.enabled or getattr(plugin, "safe_mode_enabled", False)) and plugin.key not in self._pending_disable: self._pending_disable.add(plugin.key) + def _fetch_all_data(self, async=False): + def run(): + self._repository_available = self._fetch_repository_from_disk() + self._notices_available = self._fetch_notices_from_disk() + + if async: + thread = threading.Thread(target=run) + thread.daemon = True + thread.start() + else: + run() + def _fetch_repository_from_disk(self): repo_data = None if os.path.isfile(self._repository_cache_path): @@ -696,6 +713,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, return self._refresh_repository(repo_data=repo_data) def _fetch_repository_from_url(self): + if not self._connectivity_checker.online: + self._logger.info("Looks like we are offline, can't fetch repository from network") + return None + repository_url = self._settings.get(["repository"]) try: r = requests.get(repository_url, timeout=30) @@ -758,13 +779,17 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, import json with open(self._notices_cache_path) as f: notice_data = json.load(f) - self._logger.info("Loaded notices from disk, was still valid") + self._logger.info("Loaded notice data from disk, was still valid") except: self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path)) return self._refresh_notices(notice_data=notice_data) def _fetch_notices_from_url(self): + if not self._connectivity_checker.online: + self._logger.info("Looks like we are offline, can't fetch notices from network") + return None + notices_url = self._settings.get(["notices"]) try: r = requests.get(notices_url, timeout=30) diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 5fb046186..6ac2e718c 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -174,6 +174,7 @@ $(function() { self.pipPython = ko.observable(); self.safeMode = ko.observable(); + self.online = ko.observable(); self.pipUseUserString = ko.pureComputed(function() { return self.pipUseUser() ? "yes" : "no"; @@ -234,7 +235,7 @@ $(function() { }; self.enableRepoInstall = function(data) { - return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.isCompatible(data); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data); }; self.invalidUrl = ko.pureComputed(function() { @@ -244,7 +245,7 @@ $(function() { self.enableUrlInstall = ko.pureComputed(function() { var url = self.installUrl(); - return self.enableManagement() && self.pipAvailable() && !self.safeMode() && url !== undefined && url.trim() != "" && !self.invalidUrl(); + return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && url !== undefined && url.trim() != "" && !self.invalidUrl(); }); self.invalidArchive = ko.pureComputed(function() { @@ -321,6 +322,7 @@ $(function() { self._fromPipResponse(data.pip, options); self.safeMode(data.safe_mode || false); + self.online(data.online !== undefined ? data.online : true); }; self._fromPluginsResponse = function(data, options) { @@ -814,7 +816,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = self._getToggleCommand(data) == "enable" ? "fa fa-circle-o" : "fa fa-circle"; + var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -1020,6 +1022,10 @@ $(function() { self._closeAllNotifications(); }; + self.onEventConnectivityChanged = function(payload) { + self.requestData({eval_notices: true}); + }; + self._closeAllNotifications = function() { if (self.notifications) { _.each(self.notifications, function(notification) { diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 4931e698f..10f921dbc 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -20,6 +20,13 @@ {% endtrans %} {% endmacro %} +{% macro pluginmanager_offline() %} +
{% trans %} + It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible + to install new plugins from the plugin repository or archive URLs. +{% endtrans %}
+{% endmacro %} + {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} {{ pluginmanager_safemode() }} @@ -124,6 +131,7 @@ {{ pluginmanager_printing() }} {{ pluginmanager_nopip() }} {{ pluginmanager_safemode() }} + {{ pluginmanager_offline() }}

{{ _('... from the Plugin Repository', url='http://plugins.octoprint.org') }} +
+ +
+
+ +
diff --git a/src/octoprint/templates/dialogs/settings/server.jinja2 b/src/octoprint/templates/dialogs/settings/server.jinja2 index 74adfb4f7..8e3fd59e3 100644 --- a/src/octoprint/templates/dialogs/settings/server.jinja2 +++ b/src/octoprint/templates/dialogs/settings/server.jinja2 @@ -4,4 +4,10 @@ {% include "snippets/settings/server/serverCommandServerRestart.jinja2" %} {% include "snippets/settings/server/serverCommandSystemRestart.jinja2" %} {% include "snippets/settings/server/serverCommandSystemShutdown.jinja2" %} + +

{{ _('Connectivity check') }}

+ + {% include "snippets/settings/server/serverOnlineCheckDescription.jinja2" %} + {% include "snippets/settings/server/serverOnlineCheck.jinja2" %} + diff --git a/src/octoprint/templates/dialogs/temperature.jinja2 b/src/octoprint/templates/dialogs/temperature.jinja2 index 78911009c..83b05a157 100644 --- a/src/octoprint/templates/dialogs/temperature.jinja2 +++ b/src/octoprint/templates/dialogs/temperature.jinja2 @@ -5,7 +5,7 @@