diff --git a/AUTHORS.md b/AUTHORS.md index bea57d2ed..a56725a75 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -80,6 +80,7 @@ date of first contribution): * [Andreas Werner](https://github.com/gallore) * [Shawn Bruce](https://github.com/kantlivelong) * [Claudiu Ceia] (https://github.com/ClaudiuCeia) + * [Goswin von Brederlow](https://github.com/mrvn) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and 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/bundledplugins/pluginmanager.rst b/docs/bundledplugins/pluginmanager.rst index e8c3675eb..d2a923e85 100644 --- a/docs/bundledplugins/pluginmanager.rst +++ b/docs/bundledplugins/pluginmanager.rst @@ -54,6 +54,12 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: # Time to live for the repository cache repository_ttl: 1440 + # The URL of the plugin notices feed to use + notices: http://plugins.octoprint.org/notices.json + + # Time to live for the notices feed cache + notices_ttl: 360 + # Additional arguments to use with pip. Defaults to unset, # you normally shouldn't need to modify this pip_args: --some --additional --pip --arguments @@ -76,6 +82,36 @@ under Settings > Plugin Manager, or by directly editing ``config.yaml``: - hidden - plugins +.. _sec-bundledplugins-pluginmanager-hooks: + +Hooks +----- + +.. _sec-bundledplugins-pluginmanager-hooks-reconnect_hooks: + +octoprint.plugin.pluginmanager.reconnect_hooks +++++++++++++++++++++++++++++++++++++++++++++++ + +.. py:function:: reconnect_hooks_hook(*args, **kwargs) + + Returns additional hooks defined by the plugin for which the plugin manager + should display the "You should reconnect to your printer" message on plugin + install/uninstall/enabling/disabling. + + Handlers should return a Python list containing the affected hook names. + + **Example** + + .. code-block:: python + + def reconnect_hooks_hook(*args, **kwargs): + return ["octoprint.plugin.exampleplugin.some_custom_hook", + "octoprint.plugin.exampleplugin.some_other_custom_hook"] + + __plugin_hooks__ = { + "octoprint.plugin.pluginmanager.reconnect_hooks": reconnect_hooks_hook + } + .. _sec-bundledplugins-pluginmanager-sourcecode: Source Code diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index 17efc535c..763a0de5e 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -198,6 +198,13 @@ Version checks * ``branch``: Branch of the Bitbucket repository to check, defaults to ``master`` if not set. * ``current``: Current commit hash. Will be updated automatically. + * ``api_user``: (mandatory only for private repositories) Bitbucket user name (not email address). + Requires ``api_password`` to be set. Hint: This is used for the check only. For the actual + download you might register your public SSH key as access key for the according repo and + configure this as pip URL in ``config.yaml``: ``git+ssh://git@bitbucket.org/my_user/my_repo.git@{target_version}`` + * ``api_password``: (mandatory only for private repositories) App password. Requires + ``api_user`` to be set. **Important**: Never use your actual Bitbucket login password. Generate + a new app password. App passwords are user specific on Bitbucket. * ``git_commit``: Checks a local git repository for new commits on its configured remote. Additional config parameters: diff --git a/docs/conf.py b/docs/conf.py index 74799d526..3827b54fa 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -33,7 +33,7 @@ needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain', - 'sphinx.ext.napoleon'] + 'sphinx.ext.napoleon', 'sphinxcontrib.mermaid'] todo_include_todos = True # Add any paths that contain templates here, relative to this directory. 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 b471193f5..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 --------------------- @@ -477,6 +485,15 @@ PositionUpdate * ``t``: last tool selected *through OctoPrint* * ``f``: last feedrate for move commands ``G0``, ``G1`` or ``G28`` sent *through OctoPrint* +ToolChange + A tool change command was sent to the printer. The payload contains the former current tool index and the + new current tool index. + + Payload: + + * ``old``: old tool index + * ``new``: new tool index + Timelapses ---------- diff --git a/docs/features/gcode_scripts.rst b/docs/features/gcode_scripts.rst index ee3136da8..9c12a35c7 100644 --- a/docs/features/gcode_scripts.rst +++ b/docs/features/gcode_scripts.rst @@ -68,7 +68,16 @@ All GCODE scripts have access to the following template variables through the te * ``printer_profile``: The currently selected Printer Profile, including information such as the extruder count, the build volume size, the filament diameter etc. - * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!) + * ``last_position``: Last position reported by the printer via `M114` (might be unset if no `M114` was sent so far!). + Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and + current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no + position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + * ``last_temperature``: Last actual and target temperature reported for all available tools and if available the + heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``, + ...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped + to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be + present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also + note that ``actual`` and ``target`` might be ``None``. * ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type`` and ``script.name`` respectively. @@ -76,17 +85,24 @@ There are a few additional template variables available for the following specif * ``afterPrintPaused`` and ``beforePrintResumed`` - * ``pause_position``: Position reported by the printer via ``M114`` immediately before the print was paused. Consists - of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and current tool - ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no position could be - retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + * ``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. * ``afterPrintCancelled`` * ``cancel_position``: Position reported by the printer via ``M114`` immediately before the print was cancelled. - Consists of ``x``, ``y``, ``z`` and ``e`` coordinates as received by the printer and tracked values for ``f`` and - current tool ``t`` taken from commands sent through OctoPrint. All of these coordinates might be ``None`` if no - position could be retrieved from the printer or the values could not be tracked (in case of ``f`` and ``t``)! + 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. + .. warning:: 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 cfdf3800f..e1009b415 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -389,14 +389,15 @@ This describes actually four hooks: * ``octoprint.comm.protocol.gcode.sending`` * ``octoprint.comm.protocol.gcode.sent`` -.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs) +.. py:function:: protocol_gcodephase_hook(comm_instance, phase, cmd, cmd_type, gcode, subcode=None, *args, **kwargs) Pre- and postprocess commands as they progress through the various phases of being sent to the printer. The phases are the following: * ``queuing``: This phase is triggered just before the command is added to the send queue of the communication layer. This corresponds to the moment a command is being read from a file that is currently being printed. Handlers - may suppress or change commands or their command type here. + may suppress or change commands or their command type here. This is the only phase that supports multi command + expansion by having the handler return a list, see below for details. * ``queued``: This phase is triggered just after the command was added to the send queue of the communication layer. No manipulation is possible here anymore (returned values will be ignored). * ``sending``: This phase is triggered just before the command is actually being sent to the printer. Right afterwards @@ -425,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 @@ -450,6 +451,27 @@ 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. + * **"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 + + 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. **Example** @@ -469,6 +491,8 @@ This describes actually four hooks: :param str cmd_type: Type of command, e.g. ``temperature_poll`` for temperature polling or ``sd_status_poll`` for SD printing status polling. :param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed + :param str subcode: Parsed subcode of the GCODE command, e.g. ``1`` for ``M80.1``. Will be None if no subcode was provided + or no command could be parsed. :return: None, 1-tuple, 2-tuple or string, see the description above for details. .. _sec-plugins-hook-comm-protocol-gcode-received: @@ -922,3 +946,38 @@ octoprint.ui.web.templatetypes :param dict template_sorting: read-only dictionary of currently configured template sorting specifications :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 + 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/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index f389ce5ce..584b745ba 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -299,6 +299,130 @@ on your view model, taking a list of all bound view models: }); }) +.. _sec-plugins-viewmodels-livecycle: + +Lifecycle diagrams +------------------ + +.. _sec-plugins-viewmodels-startup: + +Web interface startup +~~~~~~~~~~~~~~~~~~~~~ + +.. mermaid:: + + sequenceDiagram + participant Main + participant onServerConnect + participant fetchSettings + participant bindViewModels + participant DataUpdater + participant LoginStateViewModel + + Note right of DataUpdater: connectCallback = undefined + + activate Main + + Main->>+DataUpdater: connect + Note right of DataUpdater: initialized = false + DataUpdater-->>Main: ok + deactivate Main + DataUpdater->>DataUpdater: asynchronous connect to server... + activate DataUpdater + Note right of DataUpdater: store any callbacks instead of triggering (e.g. onServerConnect, fromHistoryData, fromCurrentData, ...) + DataUpdater-X+Main: done + deactivate DataUpdater + deactivate DataUpdater + + Main->>+DataUpdater: connectCallback = onServerConnect + Note right of DataUpdater: connectCallback = onServerConnect + DataUpdater-->>-Main: ok + Main->>+onServerConnect: call + onServerConnect->>+LoginStateViewModel: passiveLogin + LoginStateViewModel-->>onServerConnect: ok + onServerConnect-->>Main: ok + deactivate onServerConnect + deactivate Main + + LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login + Note over Main,LoginStateViewModel: Session available! + LoginStateViewModel-X+onServerConnect: done + deactivate LoginStateViewModel + deactivate LoginStateViewModel + + onServerConnect->>+DataUpdater: initialized + Note right of DataUpdater: initialized = true + DataUpdater->DataUpdater: trigger stored callbacks + DataUpdater-->>-onServerConnect: ok + onServerConnect-X+Main: done + deactivate onServerConnect + + Main->>+fetchSettings: call + Note right of fetchSettings: trigger onStartup + + fetchSettings-->>Main: ok + deactivate Main + + fetchSettings->>+fetchSettings: asynchronous settings fetch + fetchSettings->>+bindViewModels: call + + loop for each view model + bindViewModels->bindViewModels: trigger onBeforeBinding + bindViewModels->bindViewModels: trigger onBoundTo + bindViewModels->bindViewModels: trigger onAfterBinding + end + + bindViewModels->bindViewModels: trigger onAllBound + opt User is logged in + bindViewModels->>+LoginStateViewModel: onAllBound + LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn + LoginStateViewModel-->>-bindViewModels: ok + end + bindViewModels->bindViewModels: trigger onStartupComplete + bindViewModels-->>-fetchSettings: ok + + deactivate fetchSettings + deactivate fetchSettings + + +.. _sec-plugins-viewmodels-reconnect: + +Web interface reconnect +~~~~~~~~~~~~~~~~~~~~~~~ + +.. mermaid:: + + sequenceDiagram + participant onServerConnect + participant DataUpdater + participant LoginStateViewModel + + activate DataUpdater + DataUpdater->>DataUpdater: call connectCallback + DataUpdater->>+onServerConnect: call + onServerConnect-->>DataUpdater: ok + deactivate DataUpdater + + onServerConnect->>+LoginStateViewModel: passiveLogin + LoginStateViewModel-->>onServerConnect: ok + deactivate onServerConnect + LoginStateViewModel->>+LoginStateViewModel: asynchronous passive login + Note over onServerConnect,LoginStateViewModel: Session available! + opt User is logged in + LoginStateViewModel->LoginStateViewModel: trigger onUserLoggedIn + end + + activate onServerConnect + LoginStateViewModel-XonServerConnect: done + deactivate LoginStateViewModel + deactivate LoginStateViewModel + + onServerConnect->>+DataUpdater: initialized + DataUpdater->DataUpdater: trigger stored callbacks + DataUpdater-->>onServerConnect: ok + deactivate DataUpdater + deactivate onServerConnect + .. seealso:: `OctoPrint's core viewmodels `_ diff --git a/docs/sphinxext/onlineinclude.py b/docs/sphinxext/onlineinclude.py index 633eeef35..b6d9a1810 100644 --- a/docs/sphinxext/onlineinclude.py +++ b/docs/sphinxext/onlineinclude.py @@ -7,41 +7,99 @@ __copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the import codecs -import urllib2 +import requests +from contextlib import closing -from sphinx.directives import LiteralInclude, dedent_lines +from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \ + nodes, set_source_info, parselinenos, logger, container_wrapper + +if False: + # For type annotation + from typing import Any, List # NOQA cache = dict() +class OnlineIncludeReader(LiteralIncludeReader): + + def read_file(self, filename, location=None): + # type: (unicode, Any) -> List[unicode] + + global cache + try: + if filename in cache: + lines = cache[filename] + else: + with closing(requests.get(filename, stream=True)) as r: + r.encoding = self.encoding + lines = r.text.splitlines(True) + cache[filename] = lines + + if 'tab-width' in self.options: + lines = [line.expandtabs(self.options['tab-width']) for line in lines] + + return lines + except (IOError, OSError): + raise IOError(_('Include file %r not found or reading it failed') % filename) + except UnicodeError: + raise UnicodeError(_('Encoding %r used for reading included file %r seems to ' + 'be wrong, try giving an :encoding: option') % + (self.encoding, filename)) + + class OnlineIncludeDirective(LiteralInclude): - def read_with_encoding(self, filename, document, codec_info, encoding): - global cache + def run(self): + # type: () -> List[nodes.Node] + document = self.state.document + if not document.settings.file_insertion_enabled: + return [document.reporter.warning('File insertion disabled', + line=self.lineno)] + env = document.settings.env + + # convert options['diff'] to absolute path + if 'diff' in self.options: + _, path = env.relfn2path(self.options['diff']) + self.options['diff'] = path - f = None try: - if not self.arguments[0] in cache: - f = codecs.StreamReaderWriter(urllib2.urlopen(self.arguments[0]), codec_info[2], - codec_info[3], 'strict') - lines = f.readlines() - cache[self.arguments[0]] = lines - else: - lines = cache[self.arguments[0]] + location = self.state_machine.get_source_and_line(self.lineno) + url = self.arguments[0] + + reader = OnlineIncludeReader(url, self.options, env.config) + text, lines = reader.read(location=location) + + retnode = nodes.literal_block(text, text, source=url) + set_source_info(self, retnode) + if self.options.get('diff'): # if diff is set, set udiff + retnode['language'] = 'udiff' + elif 'language' in self.options: + retnode['language'] = self.options['language'] + retnode['linenos'] = ('linenos' in self.options or + 'lineno-start' in self.options or + 'lineno-match' in self.options) + retnode['classes'] += self.options.get('class', []) + extra_args = retnode['highlight_args'] = {} + if 'emphasize-lines' in self.options: + hl_lines = parselinenos(self.options['emphasize-lines'], lines) + if any(i >= lines for i in hl_lines): + logger.warning('line number spec is out of range(1-%d): %r' % + (lines, self.options['emphasize-lines']), + location=location) + extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines] + extra_args['linenostart'] = reader.lineno_start + + if 'caption' in self.options: + caption = self.options['caption'] or self.arguments[0] + retnode = container_wrapper(self, retnode, caption) + + # retnode will be note_implicit_target that is linked from caption and numref. + # when options['name'] is provided, it should be primary ID. + self.add_name(retnode) + + return [retnode] + except Exception as exc: + return [document.reporter.warning(str(exc), line=self.lineno)] - lines = dedent_lines(lines, self.options.get('dedent')) - return lines - except (IOError, OSError, urllib2.URLError): - return [document.reporter.warning( - 'Include file %r not found or reading it failed' % self.arguments[0], - line=self.lineno)] - except UnicodeError: - return [document.reporter.warning( - 'Encoding %r used for reading included file %r seems to ' - 'be wrong, try giving an :encoding: option' % - (encoding, self.arguments[0]))] - finally: - if f is not None: - f.close() def visit_onlineinclude(translator, node): translator.visit_literal_block(node) @@ -53,4 +111,4 @@ def setup(app): app.add_directive("onlineinclude", OnlineIncludeDirective) handler = (visit_onlineinclude, depart_onlineinclude) - app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) \ No newline at end of file + app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler) diff --git a/setup.py b/setup.py index c6eabbd09..8ab62c207 100644 --- a/setup.py +++ b/setup.py @@ -48,7 +48,9 @@ INSTALL_REQUIRES = [ "future>=0.15,<0.16", "scandir>=1.3,<1.4", "websocket-client>=0.40,<0.41", - "python-dateutil>=2.6,<2.7" + "python-dateutil>=2.6,<2.7", + "wrapt>=1.10.10,<1.11", + "futures>=3.1.1,<3.2" ] if sys.platform == "darwin": @@ -64,9 +66,10 @@ EXTRA_REQUIRES = dict( "ddt", # Documentation dependencies - "sphinx>=1.3,<1.4", + "sphinx>=1.6,<1.7", "sphinxcontrib-httpdomain", - "sphinx_rtd_theme", + "sphinxcontrib-mermaid", + "sphinx_bootstrap_theme", # PyPi upload related "pypandoc" 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/dev.py b/src/octoprint/cli/dev.py index 7273b8ba0..0d8dd57a1 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms import click +from past.builtins import basestring + class OctoPrintDevelCommands(click.MultiCommand): """ Custom `click.MultiCommand `_ 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 c8630e59a..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" @@ -53,10 +54,10 @@ class Events(object): METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished" METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated" - FILE_ADDED = "FileAdded", - FILE_REMOVED = "FileRemoved", - FOLDER_ADDED = "FolderAdded", - FOLDER_REMOVED = "FolderRemoved", + FILE_ADDED = "FileAdded" + FILE_REMOVED = "FileRemoved" + FOLDER_ADDED = "FolderAdded" + FOLDER_REMOVED = "FolderRemoved" # SD Upload TRANSFER_STARTED = "TransferStarted" @@ -84,6 +85,7 @@ class Events(object): EJECT = "Eject" E_STOP = "EStop" POSITION_UPDATE = "PositionUpdate" + TOOL_CHANGE = "ToolChange" REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived" # Timelapse diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 35c9075e4..a5b1bf6af 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -20,6 +20,8 @@ from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper from collections import namedtuple +from past.builtins import basestring + ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type") ContentTypeDetector = namedtuple("ContentTypeDetector", "extensions, detector") @@ -251,6 +253,26 @@ class FileManager(object): def default_slicer(self): return self._slicing_manager.default_slicer + def analyse(self, destination, path, printer_profile_id=None): + if not self.file_exists(destination, path): + return + + if printer_profile_id is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + else: + printer_profile = self._printer_profile_manager.get(printer_profile_id) + if printer_profile is None: + printer_profile = self._printer_profile_manager.get_current_or_default() + + queue_entry = self._analysis_queue_entry(destination, path) + self._analysis_queue.dequeue(queue_entry) + + queue_entry = self._analysis_queue_entry(destination, path, printer_profile=printer_profile) + if queue_entry: + return self._analysis_queue.enqueue(queue_entry, high_priority=True) + + return False + def slice(self, slicer_name, source_location, source_path, dest_location, dest_path, position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None): absolute_source_path = self.path_on_disk(source_location, source_path) diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index a774cc378..33a7a2e8f 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -19,8 +19,6 @@ import time from octoprint.events import Events, eventManager from octoprint.settings import settings -import octoprint.util.gcodeInterpreter as gcodeInterpreter - class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")): """ @@ -305,39 +303,95 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue): * The extruded volume in cm³ """ - def _do_analysis(self, high_priority=False): - try: - throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) - throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) - if throttle > 0: - def throttle_callback(filePos, readBytes): - if filePos % throttle_lines == 0: - # only apply throttle every 100 lines - time.sleep(throttle) - else: - throttle_callback = None + def __init__(self, finished_callback): + AbstractAnalysisQueue.__init__(self, finished_callback) - self._gcode = gcodeInterpreter.gcode() - self._gcode.load(self._current.absolute_path, self._current.printer_profile, throttle=throttle_callback) + self._aborted = False + self._reenqueue = False + + def _do_analysis(self, high_priority=False): + import sarge + import sys + import yaml + + try: + throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \ + else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"]) + throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"]) + max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"]) + g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"]) + speedx = self._current.printer_profile["axes"]["x"]["speed"] + speedy = self._current.printer_profile["axes"]["y"]["speed"] + offsets = self._current.printer_profile["extruder"]["offsets"] + + interpreter = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "util", "gcodeInterpreter.py")) + command = [sys.executable, interpreter, "--speed-x={}".format(speedx), "--speed-y={}".format(speedy), + "--max-t={}".format(max_extruders), "--throttle={}".format(throttle), + "--throttle-lines={}".format(throttle_lines)] + for offset in offsets[1:]: + command += ["--offset", str(offset[0]), str(offset[1])] + if g90_extruder: + command += ["--g90-extruder"] + command.append(self._current.absolute_path) + + self._logger.info("Invoking analysis command: {}".format(" ".join(command))) + + self._aborted = False + p = sarge.run(command, async=True, stdout=sarge.Capture()) + + while len(p.commands) == 0: + # somewhat ugly... we can't use wait_events because + # the events might not be all set if an exception + # by sarge is triggered within the async process + # thread + time.sleep(0.01) + + # by now we should have a command, let's wait for its + # process to have been prepared + p.commands[0].process_ready.wait() + + if not p.commands[0].process: + # the process might have been set to None in case of any exception + raise RuntimeError(u"Error while trying to run command {}".format(" ".join(command))) + + try: + # let's wait for stuff to finish + while p.returncode is None: + if self._aborted: + # oh, we shall abort, let's do so! + p.commands[0].terminate() + raise AnalysisAborted(reenqueue=self._reenqueue) + + # else continue + p.commands[0].poll() + finally: + p.close() + + output = p.stdout.text + self._logger.debug("Got output: {!r}".format(output)) + + if not "RESULTS:" in output: + raise RuntimeError("No analysis result found") + + _, output = output.split("RESULTS:") + analysis = yaml.safe_load(output) result = dict() - result["printingArea"] = self._gcode.printing_area - result["dimensions"] = self._gcode.dimensions - if self._gcode.totalMoveTimeMinute: - result["estimatedPrintTime"] = self._gcode.totalMoveTimeMinute * 60 - if self._gcode.extrusionAmount: + result["printingArea"] = analysis["printing_area"] + result["dimensions"] = analysis["dimensions"] + if analysis["total_time"]: + result["estimatedPrintTime"] = analysis["total_time"] * 60 + if analysis["extrusion_length"]: result["filament"] = dict() - for i in range(len(self._gcode.extrusionAmount)): + for i in range(len(analysis["extrusion_length"])): result["filament"]["tool%d" % i] = { - "length": self._gcode.extrusionAmount[i], - "volume": self._gcode.extrusionVolume[i] + "length": analysis["extrusion_length"][i], + "volume": analysis["extrusion_volume"][i] } return result - except gcodeInterpreter.AnalysisAborted as ex: - raise AnalysisAborted(reenqueue=ex.reenqueue) finally: self._gcode = None def _do_abort(self, reenqueue=True): - if self._gcode: - self._gcode.abort(reenqueue=reenqueue) + self._aborted = True + self._reenqueue = reenqueue diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index c69b3e14c..0f49ec88a 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -20,6 +20,8 @@ from octoprint.util import atomic_write from contextlib import contextmanager from copy import deepcopy +from past.builtins import basestring + import octoprint.filemanager from octoprint.util import is_hidden_path 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 57adfb2ed..2f77e2c49 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -104,7 +104,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en UiPlugin] if plugin_restart_needing_hooks is None: - plugin_restart_needing_hooks = ["octoprint.server.http"] + plugin_restart_needing_hooks = ["octoprint.server.http.*", + "octoprint.printer.factory"] if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] @@ -176,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 @@ -212,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. """ @@ -224,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) @@ -263,13 +269,17 @@ class PluginSettings(object): :returns: The retrieved settings value. :rtype: object - .. method:: get_int(path) + .. method:: get_int(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``int``. + Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. - .. method:: get_float(path) + .. method:: get_float(path, min=None, max=None) - Like :func:`get` but tries to convert the retrieved value to ``float``. + Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if + the value is greater than it. .. method:: get_boolean(path) @@ -285,13 +295,19 @@ class PluginSettings(object): :param boolean force: If set to True, the modified configuration will even be written back to disk if the value didn't change. - .. method:: set_int(path, value, force=False) + .. method:: set_int(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. - .. method:: set_float(path, value, force=False) + .. method:: set_float(path, value, force=False, min=None, max=None) Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. + If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal + to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than + that, ``max`` if greater than that) will be set instead. .. method:: set_boolean(path, value, force=False) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 4f98a29ab..76d092e78 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -31,6 +31,7 @@ import os import imp from collections import defaultdict, namedtuple, OrderedDict import logging +import fnmatch import pkg_resources import pkginfo @@ -946,45 +947,107 @@ class PluginManager(object): return plugin.needs_restart or self.has_restart_needing_implementation(plugin) or self.has_restart_needing_hooks(plugin) def has_restart_needing_implementation(self, plugin): - if not plugin.implementation: - return False - - return isinstance(plugin.implementation, RestartNeedingPlugin) + return self.has_any_of_mixins(plugin, RestartNeedingPlugin) def has_restart_needing_hooks(self, plugin): - if not plugin.hooks: - return False - - hooks = plugin.hooks.keys() - for hook in hooks: - if self.is_restart_needing_hook(hook): - return True - return False + return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) def has_obsolete_hooks(self, plugin): - if not plugin.hooks: - return False - - hooks = plugin.hooks.keys() - for hook in hooks: - if self.is_obsolete_hook(hook): - return True - return False + return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) def is_restart_needing_hook(self, hook): - if self.plugin_restart_needing_hooks is None: - return False - - for h in self.plugin_restart_needing_hooks: - if hook.startswith(h): - return True - - return False + return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) def is_obsolete_hook(self, hook): - if self.plugin_obsolete_hooks is None: + return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) + + @staticmethod + def has_any_of_hooks(plugin, *hooks): + """ + Tests if the ``plugin`` contains any of the provided ``hooks``. + + Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. + + Args: + plugin: plugin to test hooks for + *hooks: hooks to test against + + Returns: + (bool): True if any of the plugin's hooks match the provided hooks, + False otherwise. + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = filter(lambda hook: hook is not None, hooks) + if not hooks: return False - return hook in self.plugin_obsolete_hooks + if not plugin or not plugin.hooks: + return False + + plugin_hooks = plugin.hooks.keys() + + return any(map(lambda hook: PluginManager.hook_matches_hooks(hook, *hooks), + plugin_hooks)) + + @staticmethod + def hook_matches_hooks(hook, *hooks): + """ + Tests if ``hook`` matches any of the provided ``hooks`` to test for. + + ``hook`` is expected to be an exact hook name. + + ``hooks`` is expected to be a list containing one or more hook names or + patterns. That can be either an exact hook name or an + :func:`fnmatch.fnmatch` pattern. + + Args: + hook: the hook to test + hooks: the hook name patterns to test against + + Returns: + (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. + + """ + + if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): + hooks = hooks[0] + + hooks = filter(lambda hook: hook is not None, hooks) + if not hooks: + return False + if not hook: + return False + + return any(map(lambda h: fnmatch.fnmatch(hook, h), + hooks)) + + @staticmethod + def has_any_of_mixins(plugin, *mixins): + """ + Tests if the ``plugin`` has an implementation implementing any + of the provided ``mixins``. + + Args: + plugin: plugin for which to check the implementation + *mixins: mixins to test against + + Returns: + (bool): True if the plugin's implementation implements any of the + provided mixins, False otherwise. + """ + + if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): + mixins = mixins[0] + + mixins = filter(lambda mixin: mixin is not None, mixins) + if not mixins: + return False + if not plugin or not plugin.implementation: + return False + + return isinstance(plugin.implementation, tuple(mixins)) def initialize_implementations(self, additional_injects=None, additional_inject_factories=None, additional_pre_inits=None, additional_post_inits=None): for name, plugin in self.enabled_plugins.items(): diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index 098688f67..196a23761 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -23,6 +23,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms from .core import (Plugin, RestartNeedingPlugin, SortablePlugin) +from past.builtins import basestring class OctoPrintPlugin(Plugin): """ @@ -742,7 +743,7 @@ class UiPlugin(OctoPrintPlugin, SortablePlugin): OctoPrint's version, current ``UI_API_KEY``, tracked file paths and ``LastModified`` value). Returns: - basestring: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). + str: An alternatively calculated ETag value. Ignored if ``None`` is returned (default). """ return None diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 74bc192ae..c064d860f 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 2fe4dbb7d..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 ? "icon-circle" : "icon-circle-blank"; + var icon = data.enabled ? "fa fa-toggle-on" : "fa fa-toggle-off"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -258,22 +258,22 @@ $(function() { buttons: [{ text: gettext("Later"), click: function(notice) { - self.hiddenChannels.push(key); notice.remove(); + self.hiddenChannels.push(key); } }, { text: gettext("Mark read"), click: function(notice) { - self.markRead(key, value.last); notice.remove(); + self.markRead(key, value.last); } }, { text: gettext("Read..."), addClass: "btn-primary", click: function(notice) { + notice.remove(); self.showAnnouncementDialog(key); self.markRead(key, value.last); - notice.remove(); } }] }, @@ -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/announcements/templates/announcements.jinja2 b/src/octoprint/plugins/announcements/templates/announcements.jinja2 index 24fbe551f..0560c8ebc 100644 --- a/src/octoprint/plugins/announcements/templates/announcements.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements.jinja2 @@ -28,7 +28,7 @@
@@ -40,7 +40,7 @@ diff --git a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 index 8f91e47eb..933cc5521 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_navbar.jinja2 @@ -1,3 +1,3 @@ - + diff --git a/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 b/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 index 0d76029c1..b3d42996d 100644 --- a/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 +++ b/src/octoprint/plugins/announcements/templates/announcements_settings.jinja2 @@ -32,4 +32,4 @@ - + diff --git a/src/octoprint/plugins/corewizard/__init__.py b/src/octoprint/plugins/corewizard/__init__.py index d9c61f67d..d4ea955b3 100644 --- a/src/octoprint/plugins/corewizard/__init__.py +++ b/src/octoprint/plugins/corewizard/__init__.py @@ -49,15 +49,24 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, #~~ AssetPlugin API def get_assets(self): - return dict( - js=["js/corewizard.js"] - ) + if self.is_wizard_required(): + return dict( + js=["js/corewizard.js"] + ) + else: + return dict() #~~ 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() @@ -68,13 +77,19 @@ 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() def _get_acl_wizard_details(self): - return dict() + return dict(required=self._is_acl_wizard_required()) def _get_acl_wizard_name(self): return gettext("Access Control") @@ -111,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"]) @@ -119,13 +137,16 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path) def _get_webcam_wizard_details(self): - return dict() + return dict(required=self._is_webcam_wizard_required()) def _get_webcam_wizard_name(self): return gettext("Webcam & Timelapse") #~~ 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"]) @@ -134,18 +155,38 @@ class CoreWizardPlugin(octoprint.plugin.AssetPlugin, return not (system_shutdown_command and system_restart_command and server_restart_command) def _get_servercommands_wizard_details(self): - return dict() + return dict(required=self._is_servercommands_wizard_required()) 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 def _get_printerprofile_wizard_details(self): - return dict() + return dict(required=self._is_printerprofile_wizard_required()) def _get_printerprofile_wizard_name(self): return gettext("Default Printer Profile") diff --git a/src/octoprint/plugins/corewizard/static/js/corewizard.js b/src/octoprint/plugins/corewizard/static/js/corewizard.js index 1c37e2666..2a09a07b3 100644 --- a/src/octoprint/plugins/corewizard/static/js/corewizard.js +++ b/src/octoprint/plugins/corewizard/static/js/corewizard.js @@ -11,6 +11,8 @@ $(function() { self.setup = ko.observable(false); self.decision = ko.observable(); + self.required = false; + self.passwordMismatch = ko.pureComputed(function() { return self.password() != self.confirmedPassword(); }); @@ -72,6 +74,8 @@ $(function() { }; self.onBeforeWizardTabChange = function(next, current) { + if (!self.required) return true; + if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) { return true; } @@ -82,7 +86,13 @@ $(function() { return false; }; + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.acl && response.corewizard.details.acl.required; + }; + self.onWizardFinish = function() { + if (!self.required) return; + if (!self.decision()) { return "reload"; } @@ -94,7 +104,14 @@ $(function() { self.settingsViewModel = parameters[0]; + self.required = false; + + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.webcam && response.corewizard.details.webcam.required; + }; + self.onWizardFinish = function() { + if (!self.required) return; if (self.settingsViewModel.webcam_streamUrl() || (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) { return "reload"; @@ -108,23 +125,116 @@ $(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; self.printerProfiles = parameters[0]; + self.required = false; + self.editor = self.printerProfiles.createProfileEditor(); self.editorLoaded = ko.observable(false); - self.onStartup = function() { + self.onWizardDetails = function(response) { + self.required = response && response.corewizard && response.corewizard.details && response.corewizard.details.printerprofile && response.corewizard.details.printerprofile.required; + if (!self.required) return; + OctoPrint.printerprofiles.get("_default") .done(function(data) { self.editor.fromProfileData(data); self.editorLoaded(true); + }) + .fail(function() { + self.editor.fromProfileData(); + self.editorLoaded(true); }); }; self.onWizardFinish = function() { + if (!self.required) return; + OctoPrint.printerprofiles.update("_default", self.editor.toProfileData()) .done(function() { self.printerProfiles.requestData(); @@ -144,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 %}

+ + + + diff --git a/src/octoprint/plugins/cura/profile.py b/src/octoprint/plugins/cura/profile.py index 2f8792d09..c8dd13772 100644 --- a/src/octoprint/plugins/cura/profile.py +++ b/src/octoprint/plugins/cura/profile.py @@ -7,7 +7,9 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re + from builtins import range +from past.builtins import basestring class SupportLocationTypes(object): NONE = "none" diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 index 7057bff27..71ff14659 100644 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 +++ b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profileImporter.jinja2 @@ -59,6 +59,6 @@ diff --git a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 index 454c97065..f5d85ea3e 100644 --- a/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 +++ b/src/octoprint/plugins/cura/templates/snippets/settings/cura/profiles.jinja2 @@ -12,10 +12,10 @@ - + -  |  +  |  diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 47365b2e8..64199e9a6 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -5,6 +5,7 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" +from past.builtins import basestring import octoprint.plugin import octoprint.plugin.core @@ -35,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") @@ -44,7 +46,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, macos=["darwin"], freebsd=lambda x: x.startswith("freebsd")) - pip_inapplicable_arguments = dict(uninstall=["--user"]) + PIP_INAPPLICABLE_ARGUMENTS = dict(uninstall=["--user"]) + + RECONNECT_HOOKS = ["octoprint.comm.protocol.*",] def __init__(self): self._pending_enable = set() @@ -97,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 @@ -194,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): @@ -236,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 @@ -247,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(): @@ -415,6 +423,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, needs_restart=True, needs_refresh=True, + needs_reconnect=True, was_reinstalled=False, plugin="unknown") self._send_result_notification("install", result) @@ -426,6 +435,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, or reinstall is not None needs_refresh = new_plugin.implementation \ and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(new_plugin, self._reconnect_hooks) and self._printer.is_operational() is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin.key, "uninstalled") self._plugin_manager.mark_plugin(new_plugin.key, @@ -440,6 +450,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, source_type=source_type, needs_restart=needs_restart, needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, was_reinstalled=new_plugin.key in all_plugins_before or reinstall is not None, plugin=self._to_external_plugin(new_plugin)) self._send_result_notification("install", result) @@ -496,6 +507,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed") self._plugin_manager.mark_plugin(plugin.key, @@ -521,7 +533,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, self._plugin_manager.reload_plugins() - result = dict(result=True, needs_restart=needs_restart, needs_refresh=needs_refresh, plugin=self._to_external_plugin(plugin)) + result = dict(result=True, + needs_restart=needs_restart, + needs_refresh=needs_refresh, + needs_reconnect=needs_reconnect, + plugin=self._to_external_plugin(plugin)) self._send_result_notification("uninstall", result) return jsonify(result) @@ -531,11 +547,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin) + needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational() pending = ((command == "disable" and plugin.key in self._pending_enable) or (command == "enable" and plugin.key in self._pending_disable)) safe_mode_victim = getattr(plugin, "safe_mode_victim", False) needs_restart_api = (needs_restart or safe_mode_victim) and not pending needs_refresh_api = needs_refresh and not pending + needs_reconnect_api = needs_reconnect and not pending try: if command == "disable": @@ -549,11 +567,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, result = dict(result=True, needs_restart=True, needs_refresh=True, + needs_reconnect=True, plugin=self._to_external_plugin(plugin)) else: result = dict(result=True, needs_restart=needs_restart_api, needs_refresh=needs_refresh_api, + needs_reconnect=needs_reconnect_api, plugin=self._to_external_plugin(plugin)) self._send_result_notification(command, result) @@ -605,7 +625,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, if additional_args is not None: - inapplicable_arguments = self.__class__.pip_inapplicable_arguments.get(args[0], list()) + inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list()) for inapplicable_argument in inapplicable_arguments: additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args) @@ -664,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): @@ -681,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) @@ -743,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) @@ -881,6 +921,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, octoprint_version = pkg_resources.parse_version(octoprint_version.base_version) return octoprint_version + @property + def _reconnect_hooks(self): + reconnect_hooks = self.__class__.RECONNECT_HOOKS + + reconnect_hook_provider_hooks = self._plugin_manager.get_hooks("octoprint.plugin.pluginmanager.reconnect_hooks") + for name, hook in reconnect_hook_provider_hooks.items(): + try: + result = hook() + if isinstance(result, (list, tuple)): + reconnect_hooks.extend(filter(lambda x: isinstance(x, basestring), result)) + except: + self._logger.exception("Error while retrieving additional hooks for which a " + "reconnect is required from plugin {name}".format(**locals())) + + return reconnect_hooks + def _get_plugins(self): plugins = self._plugin_manager.plugins diff --git a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css index 65ae4796c..91383181e 100644 --- a/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css +++ b/src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css @@ -1 +1 @@ -table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output span{display:block}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file +table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009} \ No newline at end of file diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 0ee352e0e..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) { @@ -663,7 +665,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, titleError, textError) { + self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError) { var notification; var beforeClose = function(notification) { @@ -685,17 +687,21 @@ $(function() { hide: false }; + var restartClicked = false; if (self.restartCommandSpec) { options.confirm = { confirm: true, buttons: [{ text: gettext("Restart now"), - click: function () { + click: function (notice) { + if (restartClicked) return; + restartClicked = true; showConfirmationDialog({ message: gettext("This will restart your OctoPrint server."), onproceed: function() { OctoPrint.system.executeCommand("core", "restart") .done(function() { + notice.remove(); new PNotify({ title: gettext("Restart in progress"), text: gettext("The server is now being restarted in the background") @@ -707,6 +713,9 @@ $(function() { text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.") }) }); + }, + onclose: function() { + restartClicked = false; } }); } @@ -716,6 +725,7 @@ $(function() { notification = PNotify.singleButtonNotify(options); } else if (response.needs_refresh) { + var refreshClicked = false; notification = PNotify.singleButtonNotify({ title: titleSuccess, text: textReload, @@ -724,6 +734,8 @@ $(function() { buttons: [{ text: gettext("Reload now"), click: function () { + if (refreshClicked) return; + refreshClicked = true; location.reload(true); } }] @@ -737,6 +749,15 @@ $(function() { }, hide: false }) + } else if (response.needs_reconnect) { + notification = new PNotify({ + title: titleSuccess, + text: textReconnect, + callbacks: { + before_close: beforeClose + }, + hide: false + }) } else { notification = new PNotify({ title: titleSuccess, @@ -795,7 +816,7 @@ $(function() { }; self.toggleButtonCss = function(data) { - var icon = self._getToggleCommand(data) == "enable" ? "icon-circle-blank" : "icon-circle"; + var icon = self._getToggleCommand(data) == "enable" ? "fa fa-toggle-off" : "fa fa-toggle-on"; var disabled = (self.enableToggle(data)) ? "" : " disabled"; return icon + disabled; @@ -1001,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) { @@ -1050,7 +1075,7 @@ $(function() { }); self._scrollWorkingOutputToEnd(); } else if (messageType == "result") { - var titleSuccess, textSuccess, textRestart, textReload, titleError, textError; + var titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError; var action = data.action; var name = "Unknown"; @@ -1070,16 +1095,19 @@ $(function() { textSuccess = gettext("A plugin was installed successfully, however it was impossible to detect which one. Please Restart OctoPrint to make sure everything will be registered properly"); 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"); textRestart = gettext("The plugin was reinstalled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was reinstalled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was reinstalled successfully, however a reconnect to the printer is needed for that to take effect."); } else { titleSuccess = _.sprintf(gettext("Plugin \"%(name)s\" installed"), {name: name}); textSuccess = gettext("The plugin was installed successfully"); textRestart = gettext("The plugin was installed successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was installed successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was installed successfully, however a reconnect to the printer is needed for that to take effect."); } titleError = gettext("Something went wrong"); @@ -1131,6 +1159,7 @@ $(function() { textSuccess = gettext("The plugin was uninstalled successfully"); textRestart = gettext("The plugin was uninstalled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was uninstalled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was uninstalled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1148,6 +1177,7 @@ $(function() { textSuccess = gettext("The plugin was enabled successfully."); textRestart = gettext("The plugin was enabled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was enabled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was enabled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1165,6 +1195,7 @@ $(function() { textSuccess = gettext("The plugin was disabled successfully."); textRestart = gettext("The plugin was disabled successfully, however a restart of OctoPrint is needed for that to take effect."); textReload = gettext("The plugin was disabled successfully, however a reload of the page is needed for that to take effect."); + textReconnect = gettext("The plugin was disabled successfully, however a reconnect to the printer is needed for that to take effect."); titleError = gettext("Something went wrong"); if (data.hasOwnProperty("reason")) { @@ -1177,7 +1208,7 @@ $(function() { return; } - self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, titleError, textError); + self._displayNotification(data, titleSuccess, textSuccess, textRestart, textReload, textReconnect, titleError, textError); self.requestData(); } }; diff --git a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less index cd49e51db..2b591e9cb 100644 --- a/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less +++ b/src/octoprint/plugins/pluginmanager/static/less/pluginmanager.less @@ -85,10 +85,6 @@ table { } #settings_plugin_pluginmanager_workingdialog_output { - span { - display: block; - } - .message { font-weight: bold; } diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index 8e8e614f9..10f921dbc 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -20,12 +20,19 @@ {% 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() }}
- +

{{ _('Installed Plugins') }}

@@ -40,18 +47,18 @@ -
()
+
()
 
- {{ _('Homepage') }} - - + {{ _('Homepage') }} + +  
-  |  +  |  @@ -73,8 +80,8 @@ @@ -209,7 +217,7 @@
-
{{ _('Advanced options') }}
+
{{ _('Advanced options') }}
diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 507c5593c..256db8320 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -15,6 +15,9 @@ import time import logging import logging.handlers import hashlib +import traceback + +from concurrent import futures from . import version_checks, updaters, exceptions, util, cli @@ -34,7 +37,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.StartupPlugin, - octoprint.plugin.WizardPlugin): + octoprint.plugin.WizardPlugin, + octoprint.plugin.EventHandlerPlugin): COMMIT_TRACKING_TYPES = ("github_commit", "bitbucket_commit") @@ -44,7 +48,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._configured_checks = None self._refresh_configured_checks = False - self._get_versions_mutex = threading.Lock() + self._get_versions_mutex = threading.RLock() + self._get_versions_data = None + self._get_versions_data_ready = threading.Event() self._version_cache = dict() self._version_cache_ttl = 0 @@ -218,9 +224,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, "repo": "OctoPrint", "update_script": "{{python}} \"{update_script}\" --branch={{branch}} --force={{force}} \"{{folder}}\" {{target}}".format(update_script=update_script), "restart": "octoprint", - "stable_branch": dict(branch="master", name="Stable"), - "prerelease_branches": [dict(branch="rc/maintenance", name="Maintenance RCs"), - dict(branch="rc/devel", name="Devel RCs")] + "stable_branch": dict(branch="master", commitish=["master"], name="Stable"), + "prerelease_branches": [dict(branch="rc/maintenance", + commitish=["rc/maintenance"], # maintenance RCs + name="Maintenance RCs"), + dict(branch="rc/devel", + commitish=["rc/maintenance", "rc/devel"], # devel & maintenance RCs + name="Devel RCs")] }, }, "pip_command": None, @@ -463,15 +473,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, def view(): try: information, update_available, update_possible = self.get_current_versions(check_targets=check_targets, force=force) - - # we don't want to transfer python_checker or python_updater values through json - replace with True - for key, data in information.items(): - if "check" in data: - if "python_checker" in data["check"]: - data["check"]["python_checker"] = True - if "python_updater" in data["check"]: - data["check"]["python_updater"] = True - return flask.jsonify(dict(status="updatePossible" if update_available and update_possible else "updateAvailable" if update_available else "current", information=information, timestamp=self._version_cache_timestamp)) @@ -498,9 +499,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, hash.update(repr(data["information"])) hash.update(str(data["available"])) hash.update(str(data["possible"])) + hash.update(str(data.get("online", None))) hash.update(",".join(targets)) hash.update(str(self._version_cache_timestamp)) + hash.update(str(self._connectivity_checker.online)) return hash.hexdigest() def condition(): @@ -562,6 +565,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, checkout_folder = self._get_octoprint_checkout_folder(checks=checks) return check and "update_script" in check and not checkout_folder + ##~~ EventHandlerPlugin API + + 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 + + thread = threading.Thread(target=self.get_current_versions) + thread.daemon = True + thread.start() + #~~ Updater def get_current_versions(self, check_targets=None, force=False): @@ -581,53 +595,91 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, information = dict() # we don't want to do the same work twice, so let's use a lock - with self._get_versions_mutex: - for target, check in checks.items(): - if not target in check_targets: - continue + if self._get_versions_mutex.acquire(False): + self._get_versions_data_ready.clear() + try: + futures_to_result = dict() + online = self._connectivity_checker.check_immediately() + self._logger.debug("Looks like we are {}".format("online" if online else "offline")) - if not check: - continue + with futures.ThreadPoolExecutor(max_workers=5) as executor: + for target, check in checks.items(): + if not target in check_targets: + continue - try: - populated_check = self._populated_check(target, check) - target_information, target_update_available, target_update_possible = self._get_current_version(target, populated_check, force=force) - if target_information is None: - target_information = dict() - except exceptions.UnknownCheckType: - self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", ""))) - continue + if not check: + continue - target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information) + try: + populated_check = self._populated_check(target, check) + future = executor.submit(self._get_current_version, target, populated_check, force=force) + futures_to_result[future] = (target, populated_check) + except exceptions.UnknownCheckType: + self._logger.warn("Unknown update check type for target {}: {}".format(target, + check.get("type", + ""))) + continue + except: + self._logger.exception("Could not check {} for updates".format(target)) + continue - update_available = update_available or target_update_available - update_possible = update_possible or (target_update_possible and target_update_available) + for future in futures.as_completed(futures_to_result): - local_name = target_information["local"]["name"] - local_value = target_information["local"]["value"] + target, populated_check = futures_to_result[future] + if future.exception() is not None: + self._logger.error("Could not check {} for updates, error: {!r}".format(target, + future.exception())) + continue - release_notes = None - if target_information and target_information["remote"] and target_information["remote"]["value"]: - if "release_notes" in populated_check and populated_check["release_notes"]: - release_notes = populated_check["release_notes"] - elif "release_notes" in target_information["remote"]: - release_notes = target_information["remote"]["release_notes"] + target_information, target_update_available, target_update_possible, target_online, target_error = future.result() - if release_notes: - release_notes = release_notes.format(octoprint_version=VERSION, - target_name=target_information["remote"]["name"], - target_version=target_information["remote"]["value"]) + target_information = dict_merge(dict(local=dict(name="?", value="?"), + remote=dict(name="?", value="?", + release_notes=None), + needs_online=True), target_information) - information[target] = dict(updateAvailable=target_update_available, - updatePossible=target_update_possible, - information=target_information, - displayName=populated_check["displayName"], - displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value), - check=populated_check, - releaseNotes=release_notes) + update_available = update_available or target_update_available + update_possible = update_possible or (target_update_possible and target_update_available) + + local_name = target_information["local"]["name"] + local_value = target_information["local"]["value"] + + release_notes = None + if target_information and target_information["remote"] and target_information["remote"][ + "value"]: + if "release_notes" in populated_check and populated_check["release_notes"]: + release_notes = populated_check["release_notes"] + elif "release_notes" in target_information["remote"]: + release_notes = target_information["remote"]["release_notes"] + + if release_notes: + release_notes = release_notes.format(octoprint_version=VERSION, + target_name=target_information["remote"]["name"], + target_version=target_information["remote"]["value"]) + + information[target] = dict(updateAvailable=target_update_available, + updatePossible=target_update_possible, + information=target_information, + displayName=populated_check["displayName"], + displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, + local_name=local_name, + local_value=local_value), + releaseNotes=release_notes, + online=target_online, + error=target_error) + + if self._version_cache_dirty: + self._save_version_cache() + + self._get_versions_data = information, update_available, update_possible + self._get_versions_data_ready.set() + finally: + self._get_versions_mutex.release() + + else: # something's already in progress, let's wait for it to complete and use its result + self._get_versions_data_ready.wait() + information, update_available, update_possible = self._get_versions_data - if self._version_cache_dirty: - self._save_version_cache() return information, update_available, update_possible def _get_check_hash(self, check): @@ -646,36 +698,50 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, hash.update(dict_to_sorted_repr(check)) return hash.hexdigest() - def _get_current_version(self, target, check, force=False): + def _get_current_version(self, target, check, force=False, online=None): """ Determines the current version information for one target based on its check configuration. """ current_hash = self._get_check_hash(check) + if online is None: + online = self._connectivity_checker.online if target in self._version_cache and not force: data = self._version_cache[target] - if data["hash"] == current_hash and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"]: + if data["hash"] == current_hash \ + and data["timestamp"] + self._version_cache_ttl >= time.time() > data["timestamp"] \ + and data.get("online", None) == online: # we also check that timestamp < now to not get confused too much by clock changes - return data["information"], data["available"], data["possible"] + return data["information"], data["available"], data["possible"], data["online"], data.get("error", None) information = dict() update_available = False + error = None try: version_checker = self._get_version_checker(target, check) - information, is_current = version_checker.get_latest(target, check) + information, is_current = version_checker.get_latest(target, check, online=online) if information is not None and not is_current: update_available = True + except exceptions.CannotCheckOffline: + update_possible = False + information["needs_online"] = True except exceptions.UnknownCheckType: self._logger.warn("Unknown check type %s for %s" % (check["type"], target)) update_possible = False + error = "unknown_check" + except exceptions.NetworkError: + self._logger.warn("Could not check %s for updates due to a network error" % target) + update_possible = False + error = "network" except: self._logger.exception("Could not check %s for updates" % target) update_possible = False + error = "unknown" else: try: updater = self._get_updater(target, check) - update_possible = updater.can_perform_update(target, check) + update_possible = updater.can_perform_update(target, check, online=online) except: update_possible = False @@ -683,9 +749,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, hash=current_hash, information=information, available=update_available, - possible=update_possible) + possible=update_possible, + online=online, + error=error) self._version_cache_dirty = True - return information, update_available, update_possible + return information, update_available, update_possible, online, error def perform_updates(self, check_targets=None, force=False): """ @@ -797,7 +865,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._send_client_message("success", dict(results=target_results)) def _perform_update(self, target, check, force): - information, update_available, update_possible = self._get_current_version(target, check) + online = self._connectivity_checker.online + + information, update_available, update_possible, _, _ = self._get_current_version(target, check, online=online) if not update_available and not force: return False, None @@ -820,7 +890,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, if updater is None: raise exceptions.UnknownUpdateType() - update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log) + update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log, online=online) target_result = ("success", update_result) self._logger.info("Update of %s to %s successful!" % (target, target_version)) @@ -829,6 +899,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type")) return False, None + except exceptions.CannotUpdateOffline: + self._logger.warn("Update of %s can not be performed, it's not marked as 'offline' capable but we are apparently offline right now" % target) + self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="No internet connection")) + except Exception as e: self._logger.exception("Update of %s can not be performed" % target) if not "ignorable" in populated_check or not populated_check["ignorable"]: @@ -868,7 +942,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, self._logger.info("Restarting...") try: - util.execute(restart_command) + util.execute(restart_command, evaluate_returncode=False, async=True) except exceptions.ScriptError as e: self._logger.exception("Error while restarting via command {}".format(restart_command)) self._logger.warn("Restart stdout:\n{}".format(e.stdout)) @@ -917,8 +991,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, result["force_base"] = False if check.get("update_script", None): - # if we are using the update_script, we need to set our update_branch and force - # to install the exact version we requested + # if we are using the update_script, we need to set our update_branch if check.get("prerelease", None): # we are tracking prereleases => we want to be on the correct prerelease channel/branch @@ -928,14 +1001,13 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, # in case it's not already set result["update_branch"] = check.get("update_branch", channel) - # we also force our target version in the update - result["force_exact_version"] = True - else: # we are not tracking prereleases, but aren't on the stable branch either => switch back # to stable branch on update result["update_branch"] = check.get("update_branch", stable_branch) + # we also force an exact version + result["force_exact_version"] = True if BRANCH != result.get("prerelease_channel"): # we force python unequality check here because that will also allow us to diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 36e445996..42e7629b9 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -9,12 +9,14 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): import click import sys import requests.exceptions - import octoprint_client as client + from octoprint.cli.client import create_client, client_options @click.command("check") @click.option("--force", is_flag=True, help="Ignore the cache for the update check") + @click.option("--only-new", is_flag=True, help="Only show entries with updates available") + @client_options @click.argument("targets", nargs=-1) - def check_command(force, targets): + def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets): """ Check for updates. @@ -37,7 +39,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): if targets: params["check"] = ",".join(targets) - client.init_client(cli_group.settings) + client = create_client(settings=cli_group.settings, + apikey=apikey, + host=host, + port=port, + httpuser=httpuser, + httppass=httppass, + https=https, + prefix=prefix) + r = client.get("plugin/softwareupdate/check", params=params) try: r.raise_for_status() @@ -58,10 +68,15 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): status_text = "Update available" else: status_text = "Update available (manual)" - line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"], - info["information"]["local"]["name"], - info["information"]["remote"]["name"], - status_text) + + elif only_new: + continue + + line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"], + key, + info["information"]["local"]["name"], + info["information"]["remote"]["name"], + status_text) if key == "octoprint": octoprint_line = line else: @@ -83,8 +98,9 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): @click.command("update") @click.option("--force", is_flag=True, help="Update even if already up to date") + @client_options @click.argument("targets", nargs=-1) - def update_command(force, targets): + def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets): """ Apply updates. @@ -108,7 +124,13 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): if targets: data["check"] = targets - client.init_client(cli_group.settings) + client = create_client(apikey=apikey, + host=host, + port=port, + httpuser=httpuser, + httppass=httppass, + https=https, + prefix=prefix) flags = dict( waiting_for_restart=False, diff --git a/src/octoprint/plugins/softwareupdate/exceptions.py b/src/octoprint/plugins/softwareupdate/exceptions.py index 452eabeaf..75f66d3b4 100644 --- a/src/octoprint/plugins/softwareupdate/exceptions.py +++ b/src/octoprint/plugins/softwareupdate/exceptions.py @@ -18,6 +18,20 @@ class UnknownUpdateType(Exception): class UnknownCheckType(Exception): pass +class NetworkError(Exception): + def __init__(self, message=None, cause=None): + Exception.__init__(self) + self.message = message + self.cause = cause + + def __str__(self): + if self.message is not None: + return self.message + elif self.cause is not None: + return "NetworkError caused by {}".format(self.cause) + else: + return "NetworkError" + class UpdateError(Exception): def __init__(self, message, data): self.message = message @@ -35,3 +49,8 @@ class RestartFailed(Exception): class ConfigurationInvalid(Exception): pass +class CannotCheckOffline(Exception): + pass + +class CannotUpdateOffline(Exception): + pass diff --git a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css index 7aa306f96..38ccc7f64 100644 --- a/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css +++ b/src/octoprint/plugins/softwareupdate/static/css/softwareupdate.css @@ -1 +1 @@ -td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output span{display:block}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block} \ No newline at end of file +td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block} \ No newline at end of file diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index cfc20cb5d..e0c856f22 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -123,8 +123,9 @@ $(function() { self.config_updateMethod = ko.observable(); self.config_releaseChannel = ko.observable(); - self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog"); - self.confirmationDialog = $("#softwareupdate_confirmation_dialog"); + self.configurationDialog = undefined; + self.confirmationDialog = undefined; + self._updateClicked = false; self.config_availableCheckTypes = ko.observableArray([]); self.config_availableReleaseChannels = ko.observableArray([]); @@ -203,7 +204,7 @@ $(function() { self.savePluginSettings = function(viewModel, event) { var target = $(event.target); - target.prepend(' '); + target.prepend(' '); var data = { plugins: { @@ -223,7 +224,7 @@ $(function() { self.performCheck(); }, complete: function() { - $("i.icon-spinner", target).remove(); + $("i.fa-spinner", target).remove(); }, sending: true }); @@ -314,11 +315,11 @@ $(function() { if (data.status == "updateAvailable" || data.status == "updatePossible") { var text = "
" + gettext("There are updates available for the following components:"); - text += "
    "; + text += "
      "; _.each(self.versions.items(), function(update_info) { if (update_info.updateAvailable) { text += "
    • " - + "" + + "" + "" + update_info.fullNameRemote + "" + (update_info.releaseNotes ? "" + gettext("Release Notes") + "" : "") + "
    • "; @@ -326,7 +327,7 @@ $(function() { }); text += "
    "; - text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; + text += "

    " + gettext("Those components marked with can be updated directly.") + "

    "; if (!self.loginState.isAdmin()) { text += "

    " + gettext("To have updates applied, get in touch with an administrator of this OctoPrint instance.") + "

    "; @@ -357,7 +358,11 @@ $(function() { }, { text: gettext("Update now"), addClass: "btn-primary", - click: self.update + click: function() { + if (self._updateClicked) return; + self._updateClicked = true; + self.update(); + } }] }; options["buttons"] = { @@ -412,6 +417,42 @@ $(function() { }); }; + self.iconTitleForEntry = function(data) { + if (data.updatePossible) { + return ""; + } else if (!data.online && data.information && data.information.needs_online) { + return gettext("No internet connection"); + } else if (data.error) { + return self.errorTextForEntry(data); + } else { + return gettext("Update not possible"); + } + }; + + self.errorTextForEntry = function(data) { + if (!data.error) { + return ""; + } + + switch (data.error) { + case "unknown_check": { + return gettext("Unknown update check, configuration ok?"); + } + case "needs_online": { + return gettext("Cannot check for update, need online connection"); + } + case "network": { + return gettext("Network error while checking for update"); + } + case "unknown": { + return gettext("Unknown error while checking for update, please check the logs"); + } + default: { + return ""; + } + } + }; + self._markNotificationAsSeen = function(data) { if (!Modernizr.localstorage) return false; @@ -472,7 +513,7 @@ $(function() { var options = { title: gettext("Updating..."), text: gettext("Now updating, please wait."), - icon: "icon-cog icon-spin", + icon: "fa fa-cog fa-spin", hide: false, buttons: { closer: false, @@ -501,8 +542,14 @@ $(function() { }; self.update = function(force) { - if (self.updateInProgress) return; - if (!self.loginState.isAdmin()) return; + if (self.updateInProgress) { + self._updateClicked = false; + return; + } + if (!self.loginState.isAdmin()) { + self._updateClicked = false; + return; + } if (self.printerState.isPrinting()) { self._showPopup({ @@ -510,6 +557,7 @@ $(function() { text: gettext("A print job is currently in progress. Updating will be prevented until it is done."), type: "error" }); + self._updateClicked = false; } else { self.forceUpdate = (force == true); self.confirmationDialog.modal("show"); @@ -518,9 +566,13 @@ $(function() { }; self.confirmUpdate = function() { - self.confirmationDialog.modal("hide"); self.performUpdate(self.forceUpdate, _.map(self.availableAndPossible(), function(info) { return info.key })); + self.confirmationDialog.modal("hide"); + }; + + self.confirmationHidden = function() { + self._updateClicked = false; }; self._showWorkingDialog = function(title) { @@ -578,6 +630,10 @@ $(function() { self.onStartup = function() { self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog"); self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output"); + self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog"); + self.confirmationDialog = $("#softwareupdate_confirmation_dialog"); + + self.confirmationDialog.on("hidden", self.confirmationHidden); }; self.onServerDisconnect = function() { @@ -587,6 +643,11 @@ $(function() { return true; }; + self.onEventConnectivityChanged = function(payload) { + if (!payload || !payload.new) return; + self.performCheck(); + }; + self.onDataUpdaterReconnect = function() { if (self.waitingForRestart) { self.waitingForRestart = false; diff --git a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less index aeb84d1e8..a7a3d683b 100644 --- a/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less +++ b/src/octoprint/plugins/softwareupdate/static/less/softwareupdate.less @@ -2,12 +2,14 @@ td.settings_plugin_softwareupdate_column_update { width: 16px; } -#settings_plugin_softwareupdate_workingdialog_output { - font-size: 0.8em; - - span { +td.settings_plugin_softwareupdate_column_information { + .line { display: block; } +} + +#settings_plugin_softwareupdate_workingdialog_output { + font-size: 0.8em; .message { font-weight: bold; diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 1120d04e6..aa6c9e500 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -1,6 +1,6 @@
    {% trans %} Please configure the checkout folder of OctoPrint, otherwise - this plugin won't be able to update it. Click on the button + this plugin won't be able to update it. Click on the button to do this. Also refer to the Documentation. {% endtrans %}
    {% trans %} @@ -17,7 +17,7 @@ {% endtrans %}
    - +

    {{ _('Current versions') }}

    @@ -26,14 +26,15 @@ - + - :
    + :
    - {{ _('Installed:') }}
    - {{ _('Available:') }}
    - {{ _('Release Notes:') }} + {{ _('Installed:') }} + {{ _('Available:') }} + {{ _('Release Notes:') }} +
    @@ -57,14 +58,14 @@
- +
- +
{{ _('Last cache refresh:') }} - - + +
@@ -108,7 +109,7 @@