diff --git a/.versioneer-lookup b/.versioneer-lookup index 094d7998a..bb61500f1 100644 --- a/.versioneer-lookup +++ b/.versioneer-lookup @@ -24,13 +24,13 @@ maintenance 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev fix/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev improve/.* 1.4.1 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev -# staging/maintenance is currently the branch for preparation of 1.4.0rc6 +# staging/maintenance is currently the branch for preparation of 1.4.0rc7 # so is regressionfix/... -staging/maintenance 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev -regressionfix/.* 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev +staging/maintenance 1.4.0rc7 d99af420acb9d5b18a4f60f9cae8abb458e131d4 pep440-dev +regressionfix/.* 1.4.0rc7 d99af420acb9d5b18a4f60f9cae8abb458e131d4 pep440-dev -# staging/devel is currently inactive (but has the 1.4.0rc6 namespace) -staging/devel 1.4.0rc6 73f7c4d8a11a7aea7b0ece474d3bf37ad53c65d4 pep440-dev +# staging/devel is currently inactive (but has the 1.4.0rc7 namespace) +staging/devel 1.4.0rc7 d99af420acb9d5b18a4f60f9cae8abb458e131d4 pep440-dev # every other branch is a development branch and thus gets resolved to 1.5.0-dev for now .* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev diff --git a/AUTHORS.md b/AUTHORS.md index 8398e0cb5..2bc8d675e 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -115,6 +115,8 @@ date of first contribution): * [Ludovico de Nittis](https://github.com/RyuzakiKK) * [Dominik Paľo](https://github.com/DominikPalo) * [Kelly Anderson](https://github.com/cbxbiker61) + * [Jim Neill](https://github.com/jneilliii) + * [Dustin Kerber](https://github.com/kerber) 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/README.md b/README.md index 0e4ac5f3a..c070609ef 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # OctoPrint -![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen) -[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint) +![GitHub release](https://img.shields.io/github/release/OctoPrint/OctoPrint.svg?colorB=brightgreen) +[![Travis build status](https://img.shields.io/travis/OctoPrint/OctoPrint.svg)](https://travis-ci.org/OctoPrint/OctoPrint) [![Discourse topics](https://img.shields.io/discourse/https/community.octoprint.org/users.svg)](https://community.octoprint.org) [![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org) [![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d) @@ -30,7 +30,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!** You are currently looking at the source code repository of OctoPrint. If you already installed it (e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only -want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki) +want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/OctoPrint/OctoPrint/wiki) might be of more interest for you. You might also want to subscribe to join [the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be able to help you with any questions you might have. @@ -38,8 +38,8 @@ able to help you with any questions you might have. ## Contributing Contributions of all kinds are welcome, not only in the form of code but also with regards to the -[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help -in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on +[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/OctoPrint/OctoPrint/wiki), debugging help +in the [bug tracker](https://github.com/OctoPrint/OctoPrint/issues), support of other users on [the community forum at community.octoprint.org](https://community.octoprint.org) and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme). @@ -48,12 +48,12 @@ in any way to make it better instead of just complaining about it -- this is an after all :) For information about how to go about submitting bug reports or pull requests, please see the project's -[Contribution Guidelines](https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md). +[Contribution Guidelines](https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md). ## Installation Installation instructions for installing from source for different operating -systems can be found [on the wiki](https://github.com/foosel/OctoPrint/wiki#assorted-guides). +systems can be found [on the wiki](https://github.com/OctoPrint/OctoPrint/wiki#assorted-guides). If you want to run OctoPrint on a Raspberry Pi, you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi) which is a custom SD card image that includes OctoPrint plus dependencies. @@ -63,7 +63,7 @@ and runtime environment are the following (as *regular user*, please keep your hands *off* of the `sudo` command here!) - this assumes you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your system: -1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git` +1. Checkout OctoPrint: `git clone https://github.com/OctoPrint/OctoPrint.git` 2. Change into the OctoPrint folder: `cd OctoPrint` 3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`. diff --git a/docs/bundledplugins/firmware_check.rst b/docs/bundledplugins/firmware_check.rst new file mode 100644 index 000000000..ceb071039 --- /dev/null +++ b/docs/bundledplugins/firmware_check.rst @@ -0,0 +1,7 @@ +.. _sec-bundledplugins-firmware_check: + +Firmware Check +============== + +The firmware check plugin - while considered bundled with OctoPrint - is a separate project on its own release +cycle and documented on :ref:`its Github repository `_. diff --git a/docs/bundledplugins/printer_safety_check.rst b/docs/bundledplugins/printer_safety_check.rst deleted file mode 100644 index 320de9053..000000000 --- a/docs/bundledplugins/printer_safety_check.rst +++ /dev/null @@ -1,52 +0,0 @@ -.. _sec-bundledplugins-printer_safety_check: - -Printer Safety Check -==================== - -The Printer Safety Check plugin comes bundled with OctoPrint starting with version 1.3.7. - -It tries to identify printers or rather printer firmwares with known safety issues, such as -disabled thermal runaway protection, and displays a warning box to logged in users on -such identification. - -.. _fig-bundledplugins-printer_safety_check-example: -.. figure:: ../images/bundledplugins-printer_safety_check-example.png - :align: center - :alt: Printer Safety Check warning example - - An example of a warning generated by the Printer Safety Check - -Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ `_ -for a list of currently identified printers. - -If you know of further printers/printer firmwares that need to be added here, please -`get in touch on the forum and provide their response to an M115 `_. - -.. note:: - - Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though - that even if your printer might be running totally fine with a known unsafe configuration, that might change - unexpectedly and with `catastrophic `_ - `results `_. - -.. _sec-bundledplugins-printer_safety_check-events: - -Events ------- - -warning - A printer safety warning was triggered. - - Payload: - - * ``check_type``: type of check that was triggered (e.g. ``m115``, ``received`` or ``cap``) - * ``check_name``: name of check that was triggered (e.g. ``aneta8``) - * ``warning_type``: type of warning that was triggered (e.g. ``firmware-unsafe``) - -.. _sec-bundledplugins-printer_safety_check-source: - -Source Code ------------ - -The source of the Printer Safety Check plugin is bundled with OctoPrint and can be -found in its source repository under ``src/octoprint/plugins/printer_safety_check``. diff --git a/docs/bundledplugins/softwareupdate.rst b/docs/bundledplugins/softwareupdate.rst index d72735ec6..1023a8bb1 100644 --- a/docs/bundledplugins/softwareupdate.rst +++ b/docs/bundledplugins/softwareupdate.rst @@ -37,9 +37,9 @@ There you can adjust the following settings: * **OctoPrint Release Channel** (if tracking releases): The release channel of OctoPrint to track for updates. If you only want stable versions, select "Stable" here which is also the default. "Maintenance RCs" will also allow you to update to maintenance release candidates, "Devel RCs" will also allow you to update to development release candidates. If in doubt, leave it at - "Stable". `Read more about Release Channels here `_. + "Stable". `Read more about Release Channels here `_. * **OctoPrint checkout folder** (if tracking git commits): This must be the path to OctoPrint's git checkout folder - (``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide `_). + (``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide `_). Note that since OctoPrint 1.3.6 you will no longer need to set this to be able to update to releases, only if you want to be able to update against some bleeding edge git branch. * **Version cache TTL**: The "time to live" of the cache OctoPrint will use to temporarily persist the version information @@ -133,7 +133,7 @@ Configuring the Plugin user: foosel repo: OctoPrint method: pip - pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip' + pip: 'https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip' # further checks may be defined here @@ -273,7 +273,7 @@ Update methods user: foosel repo: OctoPrint method: pip - pip: 'https://github.com/foosel/OctoPrint/archive/{target_version}.zip' + pip: 'https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip' update_script: '{python} "/path/to/octoprint-update.py" --python="{python}" "{folder}" "{target}"' checkout_folder: /path/to/octoprint/checkout/folder diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 64001bde6..a18bf3d7c 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -1126,7 +1126,7 @@ Use the following settings to configure the server: * ``X-Scheme``: should contain your custom URL scheme to use (if different from ``http``), e.g. ``https`` If you use these headers OctoPrint will work both via the reverse proxy as well as when called directly. Take a look - `into OctoPrint's wiki `_ for some + `into OctoPrint's wiki `_ for some examples on how to configure this. .. _sec-configuration-config_yaml-slicing: diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 71c953de3..de1b7e353 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -19,7 +19,7 @@ below. * Checkout the OctoPrint sources from their Git repository: - * ``git clone -b devel https://github.com/foosel/OctoPrint.git`` + * ``git clone -b devel https://github.com/OctoPrint/OctoPrint.git`` * Enter the checked out source folder: ``cd OctoPrint`` * Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for @@ -86,7 +86,7 @@ installed: .. todo:: Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a - `Pull Request `_ to get the necessary + `Pull Request `_ to get the necessary steps into this guide! Then: @@ -94,7 +94,7 @@ Then: .. code-block:: none cd ~/devel - git clone -b devel https://github.com/foosel/OctoPrint.git + git clone -b devel https://github.com/OctoPrint/OctoPrint.git cd OctoPrint virtualenv venv source ./venv/bin/activate @@ -131,7 +131,7 @@ Open the Git Bash you just installed and in that: pip install virtualenv cd /c/Devel - git clone https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint virtualenv venv source ./venv/Scripts/activate @@ -145,7 +145,7 @@ Mac OS X .. note:: - This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki `_. + This guide is based on the `Setup Guide for Mac OS X on OctoPrint's Community Forum `_. Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks. .. todo:: @@ -178,7 +178,7 @@ You'll need a user account with administrator privileges. .. code-block:: none cd ~/devel - git clone https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint virtualenv venv source venv/bin/activate @@ -197,7 +197,7 @@ IDE Setup .. todo:: Using another IDE than the ones below? Please send a - `Pull Request `_ to get the necessary + `Pull Request `_ to get the necessary steps into this guide! .. _sec-development-environment-ides-pycharm: diff --git a/docs/features/plugins.rst b/docs/features/plugins.rst index 450074713..8e8e26765 100644 --- a/docs/features/plugins.rst +++ b/docs/features/plugins.rst @@ -28,7 +28,7 @@ Finding Plugins The official OctoPrint Plugin Repository can be found at `plugins.octoprint.org `_. -Some plugins may also be found in the list provided in `the OctoPrint wiki `_ +Some plugins may also be found in the list provided in `the OctoPrint wiki `_ and on the `OctoPrint organization Github page `_. .. _sec-features-plugins-installing: diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 7a4090b76..3ac2939d5 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -14,7 +14,7 @@ First of all let use make sure that you have OctoPrint checked out and set up fo development environment:: $ cd ~/devel - $ git clone https://github.com/foosel/OctoPrint + $ git clone https://github.com/OctoPrint/OctoPrint [...] $ cd OctoPrint $ virtualenv venv @@ -143,7 +143,7 @@ as a simple python file following the naming convention ``.py that can be done in one file. Distributing multiple files and getting your users to install them in the right way so that OctoPrint will be able to actually find and load them is certainly not impossible, but we want to do it in the best way possible, meaning we want to make our plugin a fully installable Python module that your users will be able to -install directly via `OctoPrint's built-in Plugin Manager `_ +install directly via `OctoPrint's built-in Plugin Manager `_ or alternatively manually utilizing Python's standard package manager ``pip`` directly. So let's begin. We'll use the `cookiecutter `_ template for OctoPrint plugins @@ -1091,7 +1091,7 @@ you haven't seen yet, :ref:`take a look at the available plugin mixins `_ might be a good example to learn from. For how to -add support for a slicer, OctoPrint's own bundled `CuraEngine plugin `_ +add support for a slicer, the `CuraEngine Legacy plugin `_ might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin `_ might show what's possible with a few lines of code already. Finally, just take a look at the `official Plugin Repository `_ if you are looking for examples. diff --git a/docs/plugins/helpers.rst b/docs/plugins/helpers.rst index f8c5424f3..73b2a7935 100644 --- a/docs/plugins/helpers.rst +++ b/docs/plugins/helpers.rst @@ -7,7 +7,7 @@ Helpers are methods that plugins can expose to other plugins in order to make co system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``. An example for providing some helper functions to the system can be found in the -`Discovery Plugin `_, +`Discovery Plugin `_, which provides its SSDP browsing and Zeroconf browsing and publishing functions as helper methods. .. code-block:: python diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index 4c5361ac2..3f1a44ac0 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -65,7 +65,7 @@ the general type of script for which to look for additions ("gcode") and the scr return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take care to add prefix and suffix as necessary after a small round of preprocessing. -Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ +Plugins can easily add their own hooks too. For example, the `Software Update Plugin `_ declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order to register themselves with the Software Update Plugin by returning their own update check configuration. @@ -215,7 +215,7 @@ octoprint.access.permissions fields are as follows: * ``key``: A key for the permission to be used for referring to it from source code. This will turned uppercase - and prefixed with ``PLUGIN__`` before being made available on ``octoprint.access.permissions.Permissions``, + and prefixed with ``PLUGIN__`` before being made available on ``octoprint.access.permissions.Permissions``, e.g. ``my_permission`` on the plugin with identifier ``example`` turns into ``PLUGIN_EXAMPLE_MY_PERMISSION`` and can be accessed as ``octoprint.access.permissions.Permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the server and ``permissions.PLUGIN_EXAMPLE_MY_PERMISSION`` on the ``AccessViewModel`` on the client. Must only contain a-z, A-Z, 0-9 and _. diff --git a/docs/plugins/viewmodels.rst b/docs/plugins/viewmodels.rst index a5fc5bd46..33d28e9a8 100644 --- a/docs/plugins/viewmodels.rst +++ b/docs/plugins/viewmodels.rst @@ -438,7 +438,7 @@ Web interface reconnect .. seealso:: - `OctoPrint's core viewmodels `_ + `OctoPrint's core viewmodels `_ OctoPrint's own view models use the same mechanisms for interacting with each other and the web application as plugins. Their source code is therefore a good point of reference on how to achieve certain things. `KnockoutJS documentation `_ diff --git a/setup.py b/setup.py index 6724f3ff4..91245addd 100644 --- a/setup.py +++ b/setup.py @@ -24,6 +24,9 @@ SETUP_REQUIRES = [ # Requirements for our application INSTALL_REQUIRES = [ + # additional OctoPrint plugins that are maintained on a different release cycle + "OctoPrint-FirmwareCheck>=2020.03.27", + # the following dependencies are non trivial to update since later versions introduce backwards incompatible # changes that might affect plugins, or due to other observed problems diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index e718a7aa3..1f3439374 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -38,7 +38,7 @@ def _validate_plugin(phase, plugin_info): def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, - plugin_validators=None, compatibility_ignored_list=None): + plugin_considered_bundled=None, plugin_validators=None, compatibility_ignored_list=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -63,6 +63,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en to logging handlers plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will not be enabled since they might depend on functionality that is no longer available. + plugin_considered_bundled (list): A list of plugin identifiers that are considered bundled plugins even if + installed separately. plugin_validators (list): A list of additional plugin validators through which to process each plugin. compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as incompatible. This is for development purposes only and should not be used in production. @@ -95,6 +97,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en if plugin_obsolete_hooks is None: plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"] + if plugin_considered_bundled is None: + plugin_considered_bundled = ["firmware_check"] + if plugin_validators is None: plugin_validators = [_validate_plugin] else: @@ -108,6 +113,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en plugin_blacklist=plugin_blacklist, plugin_restart_needing_hooks=plugin_restart_needing_hooks, plugin_obsolete_hooks=plugin_obsolete_hooks, + plugin_considered_bundled=plugin_considered_bundled, plugin_validators=plugin_validators, compatibility_ignored_list=compatibility_ignored_list) else: diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index f7956fe5e..4c900687a 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -119,21 +119,21 @@ class PluginInfo(object): """ Module attribute from which to retrieve the plugin's license. """ attr_pythoncompat = '__plugin_pythoncompat__' - """ - Module attribute from which to retrieve the plugin's python compatibility string. - + """ + Module attribute from which to retrieve the plugin's python compatibility string. + If unset a default of ``>=2.7,<3`` will be assumed, meaning that the plugin will be considered compatible to Python 2 but not Python 3. - + To mark a plugin as Python 3 compatible, a string of ``>=2.7,<4`` is recommended. - + Bundled plugins will automatically be assumed to be compatible. """ attr_hidden = '__plugin_hidden__' """ Module attribute from which to determine if the plugin's hidden or not. - + Only evaluated for bundled plugins, in order to hide them from the Plugin Manager and similar places. """ @@ -649,7 +649,8 @@ class PluginManager(object): def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, - plugin_obsolete_hooks=None, plugin_validators=None, compatibility_ignored_list=None): + plugin_obsolete_hooks=None, plugin_considered_bundled=None, plugin_validators=None, + compatibility_ignored_list=None): self.logger = logging.getLogger(__name__) if logging_prefix is None: @@ -666,6 +667,8 @@ class PluginManager(object): plugin_blacklist = [] if compatibility_ignored_list is None: compatibility_ignored_list = [] + if plugin_considered_bundled is None: + plugin_considered_bundled = [] self.plugin_folders = plugin_folders self.plugin_bases = plugin_bases @@ -677,6 +680,7 @@ class PluginManager(object): self.plugin_validators = plugin_validators self.logging_prefix = logging_prefix self.compatibility_ignored_list = compatibility_ignored_list + self.plugin_considered_bundled = plugin_considered_bundled self.enabled_plugins = dict() self.disabled_plugins = dict() @@ -878,7 +882,8 @@ class PluginManager(object): # plugin is already defined or marked as uninstalled, ignore it continue - kwargs = dict(module_name=module_name, version=version) + bundled = key in self.plugin_considered_bundled + kwargs = dict(module_name=module_name, version=version, bundled=bundled) package_name = entry_point.dist.project_name try: entry_point_metadata = EntryPointMetadata(entry_point) diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 5997acb02..44719840c 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -149,7 +149,7 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin, def get_template_configs(self): return [ dict(type="settings", name=gettext("Announcements"), template="announcements_settings.jinja2", custom_bindings=True), - dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_ANNOUNCEMENT)") + dict(type="navbar", template="announcements_navbar.jinja2", styles=["display: none"], data_bind="visible: loginState.hasPermission(access.permissions.PLUGIN_ANNOUNCEMENTS_READ)") ] # Blueprint Plugin diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 2d5e7dafd..e618df3dc 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -61,7 +61,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin, octoprint.plugin.AssetPlugin, octoprint.plugin.BlueprintPlugin, - octoprint.plugin.StartupPlugin): + octoprint.plugin.StartupPlugin, + octoprint.plugin.WizardPlugin): _pip_caller = None @@ -99,7 +100,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, ##~~ TemplatePlugin def get_template_configs(self): - return [dict(type="settings", name=gettext("Backup & Restore"))] + return [dict(type="settings", name=gettext("Backup & Restore")), + dict(type="wizard", name=gettext("Restore Backup?"))] ##~~ BlueprintPlugin @@ -210,9 +212,10 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, return NO_CONTENT @octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"]) - @no_firstrun_access - @Permissions.PLUGIN_BACKUP_ACCESS.require(403) def perform_restore(self): + if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get(["server", "firstRun"]): + return flask.abort(403) + if not is_os_compatible(["!windows"]): return flask.make_response("Invalid request, the restores are not supported on the underlying operating system", 400) @@ -325,6 +328,14 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, def is_blueprint_protected(self): return False + ##~~ WizardPlugin + + def is_wizard_required(self): + return self._settings.global_get(["server", "firstRun"]) + + def get_wizard_details(self): + return dict(required=self.is_wizard_required()) + ##~~ tornado hook def route_hook(self, *args, **kwargs): @@ -796,12 +807,25 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, try: if callable(on_log_progress): on_log_progress("Unpacking backup to {}...".format(temp)) + abstemp = os.path.abspath(temp) + dirs = {} for member in zip.infolist(): abspath = os.path.abspath(os.path.join(temp, member.filename)) if abspath.startswith(abstemp): + date_time = time.mktime(member.date_time + (0, 0, -1)) + zip.extract(member, temp) + if os.path.isdir(abspath): + dirs[abspath] = date_time + else: + os.utime(abspath, (date_time, date_time)) + + # set time on folders + for abspath, date_time in dirs.items(): + os.utime(abspath, (date_time, date_time)) + # sanity check configfile = os.path.join(temp, "basedir", "config.yaml") if not os.path.exists(configfile): @@ -929,6 +953,9 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, os.remove(path) # restart server + if not restart_command: + restart_command = configdata.get("server", dict()).get("commands", dict()).get("serverRestartCommand") + if restart_command: import sarge @@ -949,6 +976,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin, else: if callable(on_restore_done): on_restore_done(path) + if callable(on_log_error): + on_log_error("No restart command configured. Please restart OctoPrint manually.") return True diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 2414b3a53..8bfe05e00 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -29,9 +29,10 @@ $(function() { self.backupInProgress = ko.observable(false); self.restoreSupported = ko.observable(true); - self.backupUploadButton = $("#settings-backup-upload"); self.backupUploadData = undefined; - self.backupUploadButton.fileupload({ + self.backupUploadName = ko.observable(); + + var backupFileuploadOptions = { dataType: "json", maxNumberOfFiles: 1, autoUpload: false, @@ -49,8 +50,11 @@ $(function() { self.backupUploadName(undefined); self.backupUploadData = undefined; } - }); - self.backupUploadName = ko.observable(); + }; + + $("#settings-backup-upload").fileupload(backupFileuploadOptions); + $("#wizard-backup-upload").fileupload(backupFileuploadOptions); + self.restoreInProgress = ko.observable(false); self.restoreTitle = ko.observable(); self.restoreDialog = undefined; @@ -284,6 +288,6 @@ $(function() { OCTOPRINT_VIEWMODELS.push({ construct: BackupViewModel, dependencies: ["loginStateViewModel", "settingsViewModel"], - elements: ["#settings_plugin_backup"] + elements: ["#settings_plugin_backup", "#wizard_plugin_backup"] }); }); diff --git a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 index 6fcc72ca4..e19733aa5 100644 --- a/src/octoprint/plugins/backup/templates/backup_settings.jinja2 +++ b/src/octoprint/plugins/backup/templates/backup_settings.jinja2 @@ -96,26 +96,8 @@

{{ _('Restore settings & files from an uploaded backup archive.') }}

-
-
- -
-
- - {{ _('Browse...') }} - - - -
-
-
- -
-
- -
-
-
+ {% set plugin_backup_upload_form_id='settings-backup-upload' %} + {% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %}
diff --git a/src/octoprint/plugins/backup/templates/backup_wizard.jinja2 b/src/octoprint/plugins/backup/templates/backup_wizard.jinja2 new file mode 100644 index 000000000..8ba4f479c --- /dev/null +++ b/src/octoprint/plugins/backup/templates/backup_wizard.jinja2 @@ -0,0 +1,8 @@ +

{{ _('Restore from a backup?') }}

+ +{% trans %}

+ If you would like to restore OctoPrint configuration from a backup now is the time. +

{% endtrans %} + +{% set plugin_backup_upload_form_id='wizard-backup-upload' %} +{% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %} diff --git a/src/octoprint/plugins/backup/templates/snippets/plugin/backup/backup_plugin_upload_form.jinja2 b/src/octoprint/plugins/backup/templates/snippets/plugin/backup/backup_plugin_upload_form.jinja2 new file mode 100644 index 000000000..268a567f5 --- /dev/null +++ b/src/octoprint/plugins/backup/templates/snippets/plugin/backup/backup_plugin_upload_form.jinja2 @@ -0,0 +1,20 @@ +
+
+ +
+
+ + {{ _('Browse...') }} + + + +
+
+
+ +
+
+ +
+
+
diff --git a/src/octoprint/plugins/corewizard/subwizards.py b/src/octoprint/plugins/corewizard/subwizards.py index 0fee431c7..7d206ea00 100644 --- a/src/octoprint/plugins/corewizard/subwizards.py +++ b/src/octoprint/plugins/corewizard/subwizards.py @@ -107,7 +107,7 @@ class OnlineCheckSubwizard(object): return dict(required=self._is_onlinecheck_wizard_required()) def _get_onlinecheck_wizard_name(self): - return gettext("Online connectivity check") + return gettext("Online Connectivity Check") def _get_onlinecheck_additional_wizard_template_data(self): return dict(mandatory=self._is_onlinecheck_wizard_required()) @@ -125,7 +125,7 @@ class PluginBlacklistSubwizard(object): return dict(required=self._is_pluginblacklist_wizard_required()) def _get_pluginblacklist_wizard_name(self): - return gettext("Plugin blacklist") + return gettext("Plugin Blacklist") def _get_pluginblacklist_additional_wizard_template_data(self): return dict(mandatory=self._is_pluginblacklist_wizard_required()) diff --git a/src/octoprint/plugins/pi_support/static/js/pi_support.js b/src/octoprint/plugins/pi_support/static/js/pi_support.js index e6b0aaef1..4f3a8a13d 100644 --- a/src/octoprint/plugins/pi_support/static/js/pi_support.js +++ b/src/octoprint/plugins/pi_support/static/js/pi_support.js @@ -29,13 +29,11 @@ $(function() { self.fromThrottleState(response.throttle_state); // OctoPi version - $("#octopi_support_footer").remove(); + $("#pi_support_footer").remove(); if (!response.octopi_version) return; - var octoPrintVersion = $(".footer span.version"); - var octoPiVersion = $(" " + gettext("running on") + " " + gettext("OctoPi") - + " " + response.octopi_version + ""); - $(octoPiVersion).insertAfter(octoPrintVersion); + var octoPiVersion = $(""); + $("#footer_version").append(octoPiVersion); }) }; diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 3605d08db..898fdf7c4 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -1180,6 +1180,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin, version=plugin.version, url=plugin.url, license=plugin.license, + python=plugin.pythoncompat, bundled=plugin.bundled, managable=plugin.managable, enabled=plugin.enabled, diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index e24babc17..3f76067f6 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -91,6 +91,7 @@ {{ _('Homepage') }} + Python  
diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py deleted file mode 100644 index ffb6a2fd2..000000000 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ /dev/null @@ -1,203 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" - -import octoprint.plugin - -from octoprint.events import Events -from octoprint.access import USER_GROUP -from octoprint.access.permissions import Permissions -from octoprint.util import to_unicode - -from .checks.firmware_unsafe import FirmwareUnsafeChecks - -import flask -from flask_babel import gettext - -import textwrap - -TERMINAL_SAFETY_WARNING = """ -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -{message} - -Learn more at https://faq.octoprint.org/warning-{warning_type} -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - -""" - -SAFETY_CHECKS = { - "firmware-unsafe": FirmwareUnsafeChecks.as_dict() -} - -class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, - octoprint.plugin.EventHandlerPlugin, - octoprint.plugin.SimpleApiPlugin, - octoprint.plugin.TemplatePlugin): - - # noinspection PyMissingConstructor - def __init__(self): - self._warnings = dict() - self._scan_received = True - - ##~~ TemplatePlugin API - - def get_template_configs(self): - return [ - dict(type="sidebar", - name=gettext("Printer Safety Warning"), - data_bind="visible: printerState.isOperational() && loginState.isAdmin() && warnings().length > 0", - icon="exclamation-triangle", - styles_wrapper=["display: none"]) - ] - - ##~~ AssetPlugin API - - def get_assets(self): - return dict(js=("js/printer_safety_check.js",), - clientjs=("clientjs/printer_safety_check.js",), - css=("css/printer_safety_check.css",), - less=("less/printer_safety_check.less",)) - - ##~~ EventHandlerPlugin API - - def on_event(self, event, payload): - if event == Events.DISCONNECTED: - self._reset_warnings() - self._reset_state() - self._reset_checks() - - ##~~ SimpleApiPlugin API - - def on_api_get(self, request): - if not Permissions.PLUGIN_PRINTER_SAFETY_CHECK_DISPLAY.can(): - return flask.make_response("Insufficient rights", 403) - return flask.jsonify(self._warnings) - - ##~~ GCODE received hook handler - - def on_gcode_received(self, comm_instance, line, *args, **kwargs): - if self._scan_received: - self._run_checks("received", to_unicode(line, errors="replace")) - return line - - ##~~ Firmware info hook handler - - def on_firmware_info_received(self, comm_instance, firmware_name, firmware_data): - self._run_checks("m115", - to_unicode(firmware_name, errors="replace"), - dict((to_unicode(key, errors="replace"), to_unicode(value, errors="replace")) - for key, value in firmware_data.items())) - self._scan_received = False - - ##~~ Firmware capability hook handler - - def on_firmware_cap_received(self, comm_instance, cap, enabled, all_caps): - self._run_checks("cap", - to_unicode(cap, errors="replace"), - enabled) - - ##~~ Additional permissions hook handler - - def get_additional_permissions(self): - return [ - dict(key="DISPLAY", - name="Display printer safety warnings", - description=gettext("Allows to see printer safety warnings"), - roles=["display"], - default_groups=[USER_GROUP]) - ] - - ##~~ Helpers - - def _run_checks(self, check_type, *args, **kwargs): - changes = False - - for warning_type, check_data in SAFETY_CHECKS.items(): - checks = check_data.get("checks") - message = check_data.get("message") - if not checks or not message: - continue - - for check in checks: - if not check.active: - # skip non active checks - continue - - method = getattr(check, check_type, None) - if not callable(method): - # skip uncallable checks - continue - - # execute method - try: - method(*args, **kwargs) - except Exception: - self._logger.exception("There was an error running method {} on check {!r}".format(check_type, check)) - continue - - # check if now triggered - if check.triggered: - self._register_warning(warning_type, message) - - # noinspection PyUnresolvedReferences - self._event_bus.fire(Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING, dict(check_name=check.name, - warning_type=warning_type)) - changes = True - break - - if changes: - self._ping_clients() - - def _register_warning(self, warning_type, message): - self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)), - warning_type=warning_type)) - self._warnings[warning_type] = message - - def _reset_warnings(self): - self._warnings.clear() - self._ping_clients() - - def _reset_state(self): - self._scan_received = True - - def _reset_checks(self): - for warning_type, check_data in SAFETY_CHECKS.items(): - checks = check_data.get("checks") - if not checks: - continue - - for check in checks: - check.reset() - - def _log_to_terminal(self, message): - if self._printer: - lines = message.split("\n") - self._printer.log_lines(*lines) - - def _ping_clients(self): - self._plugin_manager.send_plugin_message(self._identifier, dict(type="update")) - - -def register_custom_events(*args, **kwargs): - return ["warning",] - - -__plugin_name__ = "Printer Safety Check" -__plugin_author__ = "Gina Häußge" -__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html" -__plugin_description__ = "Checks for unsafe printers/printer firmwares" -__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to " - "check if the printer it is connected to has a known safety " - "issue and inform you about that fact.") -__plugin_license__ = "AGPLv3" -__plugin_implementation__ = PrinterSafetyCheckPlugin() -__plugin_hooks__ = { - "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received, - "octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received, - "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received, - "octoprint.events.register_custom_events": register_custom_events, - "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions -} - diff --git a/src/octoprint/plugins/printer_safety_check/checks/__init__.py b/src/octoprint/plugins/printer_safety_check/checks/__init__.py deleted file mode 100644 index fbc4a22e4..000000000 --- a/src/octoprint/plugins/printer_safety_check/checks/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" - - -class Check(object): - name = None - - def __init__(self): - self._active = True - self._triggered = False - - def received(self, line): - """Called when receiving a new line from the printer""" - pass - - def m115(self, name, data): - """Called when receiving the response to an M115 from the printer""" - pass - - def cap(self, cap, enabled): - """Called when receiving a capability report line""" - pass - - @property - def active(self): - """Whether this check is still active""" - return self._active - - @property - def triggered(self): - """Whether the check has been triggered""" - return self._triggered - - def reset(self): - self._active = True - self._triggered = False - - -class AuthorCheck(Check): - authors = () - - AUTHOR = "| Author: ".lower() - - def received(self, line): - if not line: - return - - lower_line = line.lower() - if self.AUTHOR in lower_line: - self._triggered = any(map(lambda x: x in lower_line, self.authors)) - self._active = False - diff --git a/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py b/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py deleted file mode 100644 index 03719772e..000000000 --- a/src/octoprint/plugins/printer_safety_check/checks/firmware_unsafe.py +++ /dev/null @@ -1,180 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import absolute_import, division, print_function, unicode_literals - -__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' -__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License" - -from flask_babel import gettext -from octoprint.util.version import get_comparable_version -from . import Check, AuthorCheck - -class FirmwareUnsafeChecks(object): - @classmethod - def as_dict(cls): - return dict(checks=(AnetA8Check(), AnycubicCheck(), CrealityCR10sCheck(), CrealityEnder3Check(), - MalyanM200Check(), Micro3DIMECheck(), Micro3DStockCheck(), RepetierBefore092Check(), - ThermalProtectionCapCheck()), - message=gettext("Your printer's firmware is known to lack mandatory safety features (e.g. " - "thermal runaway protection). This is a fire risk.")) - -class AnetA8Check(Check): - """ - Anet A8 stock firmware - - Identified through firmware name "ANET_A8_". - """ - name = "anet_a8" - - def m115(self, name, data): - self._triggered = name and name.lower().startswith("anet_a8_") - self._active = False - -class AnycubicCheck(Check): - """ - Anycubic MEGA stock firmware - - Identified through "Author: (Jolly, xxxxxxxx.CO.)" or "| Author: (**Jolly, xxxxxxxx.CO.**)" in startup messages - combined with "echo:Vx.y.z" in startup messages, with x.y.z < 1.1.2. - """ - name = "anycubic" - - AUTHOR = "| Author: ".lower() - VERSION = "echo:V" - - CRITICAL_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower() - CRITICAL_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower() - - FIXED_VERSION = get_comparable_version("1.1.2") - - def __init__(self): - Check.__init__(self) - self._author_matches = None - self._version_matches = None - - def received(self, line): - if not line: - return - - lower_line = line.lower() - if self.AUTHOR in lower_line: - self._author_matches = self.CRITICAL_AUTHOR1 in lower_line or self.CRITICAL_AUTHOR2 in lower_line - elif line.startswith(self.VERSION): - self._version_matches = self._broken_version(line) - else: - return - - self._evaluate() - - def _broken_version(self, line): - version_str = line[len(self.VERSION):] - version = get_comparable_version(version_str, base=True) - if version is not None and version < self.FIXED_VERSION: - return True - else: - return False - - def _evaluate(self): - if self._author_matches is None or self._version_matches is None: - return - self._triggered = self._author_matches and self._version_matches - self._active = False - - def reset(self): - Check.reset(self) - self._author_matches = None - self._version_matches = None - -class CrealityCR10sCheck(AuthorCheck): - """ - Creality CR10s - - Identified through " | Author: (CR-10Slanguage)" in startup messages. - """ - name = "creality_cr10s" - authors = (" | Author: (CR-10Slanguage)".lower(),) - -class CrealityEnder3Check(AuthorCheck): - """ - Creality Ender3 - - Identified through " | Author: (Ender3)" in startup messages. - """ - name = "creality_ender3" - authors = (" | Author: (Ender3)".lower(),) - -class MalyanM200Check(Check): - """ - Malyan M200 stock firmware prior to version 4.0 - - Identified through firmware name "Malyan*", model "M200" and version < 4.0. - """ - name = "malyan_m200" - - FIXED_VERSION = get_comparable_version("4.0") - - def m115(self, name, data): - self._triggered = name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" and get_comparable_version(data.get("VER", "0")) < self.FIXED_VERSION - self._active = False - -class Micro3DIMECheck(Check): - """ - Micro3D with IME firmware - - Identified through firmware name "iME*". - """ - name = "micro3d_ime" - - def m115(self, name, data): - self._triggered = name and name.lower().startswith("ime") - self._active = False - -class Micro3DStockCheck(Check): - """ - Micro3D with IME firmware - - Identified through firmware name "Micro3D*". - """ - name = "micro3d" - - def m115(self, name, data): - self._triggered = name and name.lower().startswith("micro3d") - self._active = False - -class RepetierBefore092Check(Check): - """ - Repetier firmware prior to version 0.92 - - Identified through firmware name "Repetier_x.y.z" with x.y.z < 0.92 - """ - name = "repetier_before_092" - - FIXED_VERSION = get_comparable_version("0.92") - - def m115(self, name, data): - if name and name.lower().startswith("repetier"): - version = self._extract_repetier_version(name) - self._triggered = version is not None and version < self.FIXED_VERSION - self._active = False - - def _extract_repetier_version(self, name): - """ - Extracts the Repetier version number from the firmware name. - - Example: "Repetier_0.91" => 0.91 - """ - version = None - if "_" in name: - _, version = name.split("_", 1) - version = get_comparable_version(version, base=True) - return version - -class ThermalProtectionCapCheck(Check): - """ - Firmware reporting disabled THERMAL_PROTECTION capability - """ - name = "capability" - - def cap(self, cap, enabled): - if cap == "THERMAL_PROTECTION": - self._triggered = not enabled - self._active = False diff --git a/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js deleted file mode 100644 index 5a52fc4f9..000000000 --- a/src/octoprint/plugins/printer_safety_check/static/clientjs/printer_safety_check.js +++ /dev/null @@ -1,18 +0,0 @@ -(function (global, factory) { - if (typeof define === "function" && define.amd) { - define(["OctoPrintClient"], factory); - } else { - factory(global.OctoPrintClient); - } -})(this, function(OctoPrintClient) { - var OctoPrintPrinterSafetyCheckClient = function(base) { - this.base = base; - }; - - OctoPrintPrinterSafetyCheckClient.prototype.get = function(opts) { - return this.base.get(this.base.getSimpleApiUrl("printer_safety_check"), opts); - }; - - OctoPrintClient.registerPluginComponent("printer_safety_check", OctoPrintPrinterSafetyCheckClient); - return OctoPrintPrinterSafetyCheckClient; -}); diff --git a/src/octoprint/plugins/printer_safety_check/static/css/printer_safety_check.css b/src/octoprint/plugins/printer_safety_check/static/css/printer_safety_check.css deleted file mode 100644 index b806ecf6a..000000000 --- a/src/octoprint/plugins/printer_safety_check/static/css/printer_safety_check.css +++ /dev/null @@ -1 +0,0 @@ -#sidebar_plugin_printer_safety_check_wrapper{border:1px solid #b94a48}#sidebar_plugin_printer_safety_check_wrapper .accordion-heading{background-color:#b94a48;font-weight:700;color:#fff}#sidebar_plugin_printer_safety_check_wrapper .accordion-heading .icon-black,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:active,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:hover,#sidebar_plugin_printer_safety_check_wrapper .accordion-heading a:visited{color:#fff} \ No newline at end of file diff --git a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js b/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js deleted file mode 100644 index 667a7999f..000000000 --- a/src/octoprint/plugins/printer_safety_check/static/js/printer_safety_check.js +++ /dev/null @@ -1,56 +0,0 @@ -$(function() { - function PrinterSafetyCheckViewModel(parameters) { - var self = this; - - self.loginState = parameters[0]; - self.printerState = parameters[1]; - self.access = parameters[2]; - - self.warnings = ko.observableArray([]); - - self.requestData = function() { - if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_PRINTER_SAFETY_CHECK_DISPLAY)) { - self.warnings([]); - return; - } - - OctoPrint.plugins.printer_safety_check.get() - .done(self.fromResponse) - .fail(function() { - self.warnings([]); - }); - }; - - self.fromResponse = function(data) { - var warnings = []; - _.each(data, function(message, warning_type) { - warnings.push({type: warning_type, message: gettext(message)}); - }); - self.warnings(warnings); - }; - - self.onStartup = function() { - self.requestData(); - }; - - self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() { - self.requestData(); - }; - - self.onDataUpdaterPluginMessage = function(plugin, data) { - if (plugin !== "printer_safety_check") return; - if (!data.hasOwnProperty("type")) return; - - if (data.type === "update") { - self.requestData(); - } - } - } - - OCTOPRINT_VIEWMODELS.push({ - construct: PrinterSafetyCheckViewModel, - dependencies: ["loginStateViewModel", "printerStateViewModel", "accessViewModel"], - elements: ["#sidebar_plugin_printer_safety_check_wrapper"] - }); -}); - diff --git a/src/octoprint/plugins/printer_safety_check/static/less/printer_safety_check.less b/src/octoprint/plugins/printer_safety_check/static/less/printer_safety_check.less deleted file mode 100644 index 3dc124f1b..000000000 --- a/src/octoprint/plugins/printer_safety_check/static/less/printer_safety_check.less +++ /dev/null @@ -1,15 +0,0 @@ -#sidebar_plugin_printer_safety_check_wrapper { - border: 1px solid #b94a48; - - .accordion-heading { - background-color: #b94a48; - font-weight: bold; - color: #fff; - a, a:hover, a:visited, a:active { - color: #fff; - } - .icon-black { - color: #fff; - } - } -} diff --git a/src/octoprint/plugins/printer_safety_check/templates/printer_safety_check_sidebar.jinja2 b/src/octoprint/plugins/printer_safety_check/templates/printer_safety_check_sidebar.jinja2 deleted file mode 100644 index a09f76812..000000000 --- a/src/octoprint/plugins/printer_safety_check/templates/printer_safety_check_sidebar.jinja2 +++ /dev/null @@ -1,7 +0,0 @@ -

{{ _('Warning!') }}

- -

-
- {{ _('Learn more...') }} -

- diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index aa0c50891..7312eceb2 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -282,7 +282,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin, "user": "foosel", "repo": "OctoPrint", "method": "pip", - "pip": "https://github.com/foosel/OctoPrint/archive/{target_version}.zip", + "pip": "https://github.com/OctoPrint/OctoPrint/archive/{target_version}.zip", "update_script": default_update_script, "restart": "octoprint", "stable_branch": dict(branch="master", commitish=["master"], name="Stable"), diff --git a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 index 022792cca..f743f749e 100644 --- a/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 +++ b/src/octoprint/plugins/softwareupdate/templates/softwareupdate_settings.jinja2 @@ -1,7 +1,7 @@
{% trans %} Please configure the checkout folder of OctoPrint, otherwise this plugin won't be able to update it. Click on the button - to do this. Also refer to the Documentation. + to do this. Also refer to the Documentation. {% endtrans %}
{% trans %}

diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 85fc7416d..3f495744c 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -206,11 +206,13 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, if not self._settings.get_boolean(["events", "pong"]): return + payload = self._get_environment_payload() + plugins = self._plugin_manager.enabled_plugins plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled] - payload = dict(plugins=",".join(map(lambda x: "{}:{}".format(x.key.lower(), - x.version.lower() if x.version else "?"), - plugins_thirdparty))) + payload["plugins"] = ",".join(map(lambda x: "{}:{}".format(x.key.lower(), + x.version.lower() if x.version else "?"), + plugins_thirdparty)) self._track("pong", body=True, **payload) @@ -218,19 +220,7 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, if not self._settings.get_boolean(["events", "startup"]): return - payload = dict(version=get_octoprint_version_string(), - os=self._environment["os"]["id"], - python=self._environment["python"]["version"], - pip=self._environment["python"]["pip"], - cores=self._environment["hardware"]["cores"], - freq=self._environment["hardware"]["freq"], - ram=self._environment["hardware"]["ram"]) - - if "plugins" in self._environment and "pi_support" in self._environment["plugins"]: - payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"] - - if "octopi_version" in self._environment["plugins"]["pi_support"]: - payload["octopi_version"] = self._environment["plugins"]["pi_support"]["octopi_version"] + payload = self._get_environment_payload() self._track("startup", **payload) @@ -439,6 +429,23 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, else: pass + def _get_environment_payload(self): + payload = dict(version=get_octoprint_version_string(), + os=self._environment["os"]["id"], + python=self._environment["python"]["version"], + pip=self._environment["python"]["pip"], + cores=self._environment["hardware"]["cores"], + freq=self._environment["hardware"]["freq"], + ram=self._environment["hardware"]["ram"]) + + if "plugins" in self._environment and "pi_support" in self._environment["plugins"]: + payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"] + + if "octopi_version" in self._environment["plugins"]["pi_support"]: + payload["octopi_version"] = self._environment["plugins"]["pi_support"]["octopi_version"] + + return payload + __plugin_name__ = "Anonymous Usage Tracking" __plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked" __plugin_url__ = "https://tracking.octoprint.org" diff --git a/src/octoprint/plugins/tracking/static/js/usage.js b/src/octoprint/plugins/tracking/static/js/usage.js index b8867d1a8..2086ca707 100644 --- a/src/octoprint/plugins/tracking/static/js/usage.js +++ b/src/octoprint/plugins/tracking/static/js/usage.js @@ -81,7 +81,7 @@ $(function() { "octoprint.log."); new PNotify({ title: gettext("Something went wrong"), - text: _.sprintf(message, {bugreport: "https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report", jsconsole: "https://webmasters.stackexchange.com/a/77337"}), + text: _.sprintf(message, {bugreport: "https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#how-to-file-a-bug-report", jsconsole: "https://webmasters.stackexchange.com/a/77337"}), type: "error", hide: false }); diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index 199c9ad45..76ba127a1 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -36,7 +36,7 @@ class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin): __plugin_name__ = "Virtual Printer" __plugin_author__ = "Gina Häußge, based on work by Daid Braam" -__plugin_homepage__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Virtual-Printer" +__plugin_homepage__ = "https://docs.octoprint.org/en/master/development/virtual_printer.html" __plugin_license__ = "AGPLv3" __plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes" diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index 6d810d7de..09b8e25d7 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -624,6 +624,9 @@ class PrinterCallback(object): bed: actual: target: + chamber: + actual: + target: Arguments: data (dict): A dict of all current temperatures in the format as specified above diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index e870c36e6..10ccd329d 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -888,9 +888,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None, printTimeLeftOrigin=printTimeLeftOrigin) - def _addTemperatureData(self, tools=None, bed=None, chamber=None): + def _addTemperatureData(self, tools=None, bed=None, chamber=None, custom=None): if tools is None: tools = dict() + if custom is None: + custom = dict() data = dict(time=int(time.time())) for tool in tools.keys(): @@ -899,12 +901,15 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): data["bed"] = self._dict(actual=bed[0], target=bed[1]) if chamber is not None and isinstance(chamber, tuple): data["chamber"] = self._dict(actual=chamber[0], target=chamber[1]) + for identifier, values in custom.items(): + data[identifier] = self._dict(actual=values[0], target=values[1]) self._temps.append(data) self._temp = tools self._bedTemp = bed self._chamberTemp = chamber + self._custom = custom self._stateMonitor.add_temperature(self._dict(**data)) @@ -1055,8 +1060,13 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): """ self._addLog(to_unicode(message, "utf-8", errors="replace")) - def on_comm_temperature_update(self, temp, bedTemp, chamberTemp): - self._addTemperatureData(tools=copy.deepcopy(temp), bed=copy.deepcopy(bedTemp), chamber=copy.deepcopy(chamberTemp)) + def on_comm_temperature_update(self, tools, bed, chamber, custom=None): + if custom is None: + custom = dict() + self._addTemperatureData(tools=copy.deepcopy(tools), + bed=copy.deepcopy(bed), + chamber=copy.deepcopy(chamber), + custom=copy.deepcopy(custom)) def on_comm_position_update(self, position, reason=None): payload = dict(reason=reason) diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py index d56a9300a..6ea51da02 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -41,7 +41,11 @@ def _clear_file_cache(): _file_cache.clear() def _create_lastmodified(path, recursive): - if path.endswith("/files"): + path = path[len("/api/files"):] + if path.startswith("/"): + path = path[1:] + + if path == "": # all storages involved lms = [0] for storage in fileManager.registered_storages: @@ -58,16 +62,13 @@ def _create_lastmodified(path, recursive): # if we reach this point, we return the maximum of all dates return max(lms) - elif path.endswith("/files/local"): - # only local storage involved - try: - return fileManager.last_modified(FileDestinations.LOCAL, recursive=recursive) - except Exception: - logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {}".format(FileDestinations.LOCAL)) - return None - else: - return None + storage, path_in_storage = path.split("/", 1) + try: + return fileManager.last_modified(storage, path=path_in_storage, recursive=recursive) + except Exception: + logging.getLogger(__name__).exception("There was an error retrieving the last modified data from storage {} and path {}".format(storage, path_in_storage)) + return None def _create_etag(path, filter, recursive, lm=None): @@ -85,7 +86,16 @@ def _create_etag(path, filter, recursive, lm=None): hash_update(str(filter)) hash_update(str(recursive)) - if path.endswith("/files") or path.endswith("/files/sdcard"): + path = path[len("/api/files"):] + if path.startswith("/"): + path = path[1:] + + if "/" in path: + storage, _ = path.split("/", 1) + else: + storage = path + + if path == "" or storage == FileDestinations.SDCARD: # include sd data in etag hash_update(repr(sorted(printer.get_sd_files(), key=lambda x: sv(x[0])))) @@ -141,6 +151,30 @@ def readGcodeFilesForOrigin(origin): return jsonify(files=files) +@api.route("/files//", methods=["GET"]) +@Permissions.FILES_LIST.require(403) +@with_revalidation_checking(etag_factory=lambda lm=None: _create_etag(request.path, + request.values.get("filter", False), + request.values.get("recursive", False), + lm=lm), + lastmodified_factory=lambda: _create_lastmodified(request.path, + request.values.get("recursive", False)), + unless=lambda: request.values.get("force", False) or request.values.get("_refresh", False)) +def readGcodeFile(target, filename): + if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: + return make_response("Unknown target: %s" % target, 404) + + recursive = False + if "recursive" in request.values: + recursive = request.values["recursive"] in valid_boolean_trues + + file = _getFileDetails(target, filename, recursive=recursive) + if not file: + return make_response("File not found on '%s': %s" % (target, filename), 404) + + return jsonify(file) + + def _getFileDetails(origin, path, recursive=True): parent, path = os.path.split(path) files = _getFileList(origin, path=parent, recursive=recursive) @@ -188,9 +222,10 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac with _file_cache_mutex: cache_key = "{}:{}:{}:{}".format(origin, path, recursive, filter) files, lastmodified = _file_cache.get(cache_key, ([], None)) - if not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=recursive): + # recursive needs to be True for lastmodified queries so we get lastmodified of whole subtree - #3422 + if not allow_from_cache or lastmodified is None or lastmodified < fileManager.last_modified(origin, path=path, recursive=True): files = list(fileManager.list_files(origin, path=path, filter=filter_func, recursive=recursive)[origin].values()) - lastmodified = fileManager.last_modified(origin, path=path, recursive=recursive) + lastmodified = fileManager.last_modified(origin, path=path, recursive=True) _file_cache[cache_key] = (files, lastmodified) def analyse_recursively(files, path=None): @@ -470,23 +505,6 @@ def uploadGcodeFile(target): return make_response("No file to upload and no folder to create", 400) -@api.route("/files//", methods=["GET"]) -@Permissions.FILES_LIST.require(403) -def readGcodeFile(target, filename): - if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target: %s" % target, 404) - - recursive = False - if "recursive" in request.values: - recursive = request.values["recursive"] in valid_boolean_trues - - file = _getFileDetails(target, filename, recursive=recursive) - if not file: - return make_response("File not found on '%s': %s" % (target, filename), 404) - - return jsonify(file) - - @api.route("/files//", methods=["POST"]) @no_firstrun_access def gcodeFileCommand(filename, target): diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 848c680ad..31864cdb1 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -187,6 +187,7 @@ def getSettings(): "blockWhileDwelling": s.getBoolean(["serial", "blockWhileDwelling"]), "useParityWorkaround": s.get(["serial", "useParityWorkaround"]), "sendM112OnError": s.getBoolean(["serial", "sendM112OnError"]), + "disableSdPrintingDetection": s.getBoolean(["serial", "disableSdPrintingDetection"]), "ackMax": s.getInt(["serial", "ackMax"]), "maxTimeoutsIdle": s.getInt(["serial", "maxCommunicationTimeouts", "idle"]), "maxTimeoutsPrinting": s.getInt(["serial", "maxCommunicationTimeouts", "printing"]), @@ -484,6 +485,7 @@ def _saveSettings(data): if value in ("always", "detect", "never"): s.set(["serial", "useParityWorkaround"], value) if "sendM112OnError" in data["serial"]: s.setBoolean(["serial", "sendM112OnError"], data["serial"]["sendM112OnError"]) + if "disableSdPrintingDetection" in data["serial"]: s.setBoolean(["serial", "disableSdPrintingDetection"], data["serial"]["disableSdPrintingDetection"]) if "ackMax" in data["serial"]: s.setInt(["serial", "ackMax"], data["serial"]["ackMax"]) if "logPositionOnPause" in data["serial"]: s.setBoolean(["serial", "logPositionOnPause"], data["serial"]["logPositionOnPause"]) if "logPositionOnCancel" in data["serial"]: s.setBoolean(["serial", "logPositionOnCancel"], data["serial"]["logPositionOnCancel"]) diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index 11e5ebfe3..4318a598e 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1385,7 +1385,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater): return False cache_key = ('octo', 'settings') - current_hash = webassets.utils.hash_func(json.dumps(settings().effective_yaml)) + current_hash = settings().effective_hash cached_hash = ctx.cache.get(cache_key) # This may seem counter-intuitive, but if no cache entry is found # then we actually return "no update needed". This is because @@ -1403,8 +1403,7 @@ class SettingsCheckUpdater(webassets.updater.BaseUpdater): return cache_key = ('octo', 'settings') - cache_value = webassets.utils.hash_func(json.dumps(settings().effective_yaml)) - ctx.cache.set(cache_key, cache_value) + ctx.cache.set(cache_key, settings().effective_hash) ##~~ core assets collector def collect_core_assets(enable_gcodeviewer=True, preferred_stylesheet="css"): diff --git a/src/octoprint/server/util/sockjs.py b/src/octoprint/server/util/sockjs.py index f051f63a0..83f4d0724 100644 --- a/src/octoprint/server/util/sockjs.py +++ b/src/octoprint/server/util/sockjs.py @@ -83,6 +83,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, _emit_permissions = {"connected": [], "reauthRequired": [], + "plugin": lambda payload: [] if payload.get("plugin") == "backup" and settings().getBoolean(["server", "firstRun"]) else [Permissions.STATUS], "*": [Permissions.STATUS]} _unauthed_backlog_max = 100 @@ -419,7 +420,7 @@ class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, if permissions is None: permissions = self._emit_permissions.get(type, self._emit_permissions["*"]) - permissions = [x() if callable(x) else x for x in permissions] + permissions = permissions(payload) if callable(permissions) else [x for x in permissions] if not self._user or not all(map(lambda p: self._user.has_permission(p), permissions)): if not self._authed: diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 60aa35401..94795e0eb 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -23,6 +23,7 @@ from octoprint.access.permissions import Permissions from octoprint.settings import settings from octoprint.filemanager import full_extension_tree, get_all_extensions from octoprint.util import to_unicode, to_bytes, sv +from octoprint.util.version import get_python_version_string import re import base64 @@ -198,6 +199,12 @@ def index(): enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"]) enable_timelapse = settings().getBoolean(["webcam", "timelapseEnabled"]) enable_loading_animation = settings().getBoolean(["devel", "showLoadingAnimation"]) + enable_sd_support = settings().get(["feature", "sdSupport"]) + enable_webcam = settings().getBoolean(["webcam", "webcamEnabled"]) and bool(settings().get(["webcam", "stream"])) + enable_temperature_graph = settings().get(["feature", "temperatureGraph"]) + gcode_mobile_threshold = settings().get(["gcodeViewer", "mobileSizeThreshold"]) + gcode_threshold = settings().get(["gcodeViewer", "sizeThreshold"]) + sockjs_connect_timeout = settings().getInt(["devel", "sockJsConnectTimeout"]) def default_template_filter(template_type, template_key): if template_type == "navbar": @@ -216,6 +223,12 @@ def index(): enable_gcodeviewer, enable_timelapse, enable_loading_animation, + enable_sd_support, + enable_webcam, + enable_temperature_graph, + gcode_mobile_threshold, + gcode_threshold, + sockjs_connect_timeout, wizard_active(_templates.get(locale))] + sorted(["{}:{}".format(to_unicode(k, errors="replace"), to_unicode(v, errors="replace")) for k, v in _plugin_vars.items()]) @@ -241,19 +254,6 @@ def index(): def cache_key(): return _cache_key(key, additional_key_data=additional_key_data) - def check_etag_and_lastmodified(): - files = collect_files() - lastmodified = compute_lastmodified(files) - lastmodified_ok = util.flask.check_lastmodified(lastmodified) - etag_ok = util.flask.check_etag(compute_etag(files=files, - lastmodified=lastmodified, - additional=[cache_key()] + additional_etag)) - return lastmodified_ok and etag_ok - - def validate_cache(cached): - etag_different = compute_etag(additional=[cache_key()] + additional_etag) != cached.get_etag()[0] - return force_refresh or etag_different - def collect_files(): if callable(custom_files): try: @@ -263,13 +263,11 @@ def index(): except Exception: _logger.exception("Error while trying to retrieve tracked files for plugin {}".format(key)) - templates = _get_all_templates() - assets = _get_all_assets() - translations = _get_all_translationfiles(g.locale.language if g.locale else "en", + files = _get_all_templates() + files += _get_all_assets() + files += _get_all_translationfiles(g.locale.language if g.locale else "en", "messages") - files = templates + assets + translations - if callable(additional_files): try: af = additional_files() @@ -280,7 +278,7 @@ def index(): return sorted(set(files)) - def compute_lastmodified(files=None): + def compute_lastmodified(files): if callable(custom_lastmodified): try: lastmodified = custom_lastmodified() @@ -289,11 +287,9 @@ def index(): except Exception: _logger.exception("Error while trying to retrieve custom LastModified value for plugin {}".format(key)) - if files is None: - files = collect_files() return _compute_date(files) - def compute_etag(files=None, lastmodified=None, additional=None): + def compute_etag(files, lastmodified, additional=None): if callable(custom_etag): try: etag = custom_etag() @@ -302,10 +298,6 @@ def index(): except Exception: _logger.exception("Error while trying to retrieve custom ETag value for plugin {}".format(key)) - if files is None: - files = collect_files() - if lastmodified is None: - lastmodified = compute_lastmodified(files) if lastmodified and not isinstance(lastmodified, basestring): from werkzeug.http import http_date lastmodified = http_date(lastmodified) @@ -317,6 +309,7 @@ def index(): def hash_update(value): hash.update(to_bytes(value, encoding="utf-8", errors="replace")) hash_update(octoprint.__version__) + hash_update(get_python_version_string()) hash_update(",".join(sorted(files))) if lastmodified: hash_update(lastmodified) @@ -324,9 +317,22 @@ def index(): hash_update(add) return hash.hexdigest() + current_files = collect_files() + current_lastmodified = compute_lastmodified(current_files) + current_etag = compute_etag(files=current_files, lastmodified=current_lastmodified, + additional=[cache_key()] + additional_etag) + + def check_etag_and_lastmodified(): + lastmodified_ok = util.flask.check_lastmodified(current_lastmodified) + etag_ok = util.flask.check_etag(current_etag) + return lastmodified_ok and etag_ok + + def validate_cache(cached): + return force_refresh or (current_etag != cached.get_etag()[0]) + decorated_view = view - decorated_view = util.flask.lastmodified(lambda _: compute_lastmodified())(decorated_view) - decorated_view = util.flask.etagged(lambda _: compute_etag(additional=[cache_key()] + additional_etag))(decorated_view) + decorated_view = util.flask.lastmodified(lambda _: current_lastmodified)(decorated_view) + decorated_view = util.flask.etagged(lambda _: current_etag)(decorated_view) decorated_view = util.flask.cached(timeout=-1, refreshif=validate_cache, key=cache_key, @@ -378,14 +384,15 @@ def index(): _plugin_vars, now) render_kwargs.update(dict( - enableWebcam=settings().getBoolean(["webcam", "webcamEnabled"]) and bool(settings().get(["webcam", "stream"])), - enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]), + enableWebcam=enable_webcam, + enableTemperatureGraph=enable_temperature_graph, enableAccessControl=enable_accesscontrol, accessControlActive=accesscontrol_active, enableLoadingAnimation=enable_loading_animation, - enableSdSupport=settings().get(["feature", "sdSupport"]), - gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]), - gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]), + enableSdSupport=enable_sd_support, + gcodeMobileThreshold=gcode_mobile_threshold, + gcodeThreshold=gcode_threshold, + sockJsConnectTimeout=sockjs_connect_timeout * 1000, wizard=wizard, now=now, )) @@ -476,6 +483,7 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now): debug=debug, firstRun=first_run, version=dict(number=VERSION, display=DISPLAY_VERSION, branch=BRANCH), + python_version=get_python_version_string(), templates=templates, pluginNames=plugin_names, locales=locales, @@ -963,9 +971,21 @@ def _compute_date_for_i18n(locale, domain): def _compute_date(files): + # Note, we do not expect everything in 'files' to exist. from datetime import datetime - timestamps = list(map(lambda path: os.stat(path).st_mtime, files)) + [0] if files else [] - max_timestamp = max(*timestamps) if timestamps else None + import stat + max_timestamp = 0 + for path in files: + try: + # try to stat file. If an exception is thrown, its because it does not exist. + s = os.stat(path) + if stat.S_ISREG(s.st_mode) and s.st_mtime > max_timestamp: + # is a regular file and has a newer timestamp + max_timestamp = s.st_mtime + except Exception: + # path does not exist. + continue + if max_timestamp: # we set the micros to 0 since microseconds are not speced for HTTP max_timestamp = datetime.fromtimestamp(max_timestamp).replace(microsecond=0) @@ -991,22 +1011,14 @@ def _get_all_templates(): def _get_all_assets(): from octoprint.util.jinja import get_all_asset_paths - return get_all_asset_paths(app.jinja_env.assets_environment) + return get_all_asset_paths(app.jinja_env.assets_environment, verifyExist=False) def _get_all_translationfiles(locale, domain): from flask import _request_ctx_stack def get_po_path(basedir, locale, domain): - path = os.path.join(basedir, locale) - if not os.path.isdir(path): - return None - - path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals())) - if not os.path.isfile(path): - return None - - return path + return os.path.join(basedir, locale, "LC_MESSAGES", "{domain}.po".format(**locals())) po_files = [] @@ -1018,13 +1030,7 @@ def _get_all_translationfiles(locale, domain): for name, plugin in plugins.items(): dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')] for dirname in dirs: - if not os.path.isdir(dirname): - continue - - po_file = get_po_path(dirname, locale, domain) - if po_file: - po_files.append(po_file) - break + po_files.append(get_po_path(dirname, locale, domain)) # core translations ctx = _request_ctx_stack.top @@ -1032,10 +1038,7 @@ def _get_all_translationfiles(locale, domain): dirs = [user_base_path, base_path] for dirname in dirs: - po_file = get_po_path(dirname, locale, domain) - if po_file: - po_files.append(po_file) - break + po_files.append(get_po_path(dirname, locale, domain)) return po_files diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index 9fea4198b..1b1f2ef22 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -153,6 +153,7 @@ default_settings = { "useParityWorkaround": "detect", "maxConsecutiveResends": 10, "sendM112OnError": True, + "disableSdPrintingDetection": False, "ackMax": 1, "capabilities": { @@ -315,7 +316,7 @@ default_settings = { "components": { "order": { "navbar": ["settings", "systemmenu", "plugin_announcements", "plugin_pi_support", "login"], - "sidebar": ["plugin_printer_safety_check", "connection", "state", "files"], + "sidebar": ["plugin_firmware_check", "connection", "state", "files"], "tab": ["temperature", "control", "gcodeviewer", "terminal", "timelapse"], "settings": [ "section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters", "gcodescripts", @@ -325,7 +326,7 @@ default_settings = { "plugin_pi_support" ], "usersettings": ["access", "interface"], - "wizard": ["access"], + "wizard": ["plugin_backup", "plugin_corewizard_acl"], "about": ["about", "plugin_pi_support", "supporters", "authors", "changelog", "license", "thirdparty", "plugin_pluginmanager"], "generic": [] }, @@ -413,6 +414,7 @@ default_settings = { }, "useFrozenDictForPrinterState": True, "showLoadingAnimation": True, + "sockJsConnectTimeout": 10, "virtualPrinter": { "enabled": False, "okAfterResend": False, @@ -645,6 +647,8 @@ class Settings(object): self._config = None self._dirty = False self._dirty_time = 0 + self._last_config_hash = None + self._last_effective_hash = None self._mtime = None self._get_preprocessors = dict( @@ -842,6 +846,15 @@ class Settings(object): return list(map(process_control, controls)) + def _forget_hashes(self): + self._last_config_hash = None + self._last_effective_hash = None + + def _mark_dirty(self): + self._dirty = True + self._dirty_time = time.time() + self._forget_hashes() + @property def effective(self): return self._map.deep_dict() @@ -853,10 +866,14 @@ class Settings(object): @property def effective_hash(self): + if self._last_effective_hash is not None: + return self._last_effective_hash + import hashlib hash = hashlib.md5() hash.update(self.effective_yaml.encode('utf-8')) - return hash.hexdigest() + self._last_effective_hash = hash.hexdigest() + return self._last_effective_hash @property def config_yaml(self): @@ -865,10 +882,14 @@ class Settings(object): @property def config_hash(self): + if self._last_config_hash: + return self._last_config_hash + import hashlib hash = hashlib.md5() hash.update(self.config_yaml.encode('utf-8')) - return hash.hexdigest() + self._last_config_hash = hash.hexdigest() + return self._last_config_hash @property def _config(self): @@ -933,6 +954,8 @@ class Settings(object): if migrate: self._migrate_config() + self._forget_hashes() + def load_overlay(self, overlay, migrate=True): config = None @@ -1603,8 +1626,7 @@ class Settings(object): del self._config["folder"][type] if not len(self._config["folder"]): del self._config["folder"] - self._dirty = True - self._dirty_time = time.time() + self._mark_dirty() self.save() except KeyError: pass @@ -1652,8 +1674,7 @@ class Settings(object): try: chain.del_by_path(path) - self._dirty = True - self._dirty_time = time.time() + self._mark_dirty() except KeyError: if error_on_path: raise NoSuchSettingsPath() @@ -1711,8 +1732,7 @@ class Settings(object): if not force and in_defaults and in_local and default_value == value: try: chain.del_by_path(path) - self._dirty = True - self._dirty_time = time.time() + self._mark_dirty() except KeyError: if error_on_path: raise NoSuchSettingsPath() @@ -1722,8 +1742,7 @@ class Settings(object): chain.del_by_path(path) else: chain.set_by_path(path, value) - self._dirty = True - self._dirty_time = time.time() + self._mark_dirty() def setInt(self, path, value, **kwargs): if value is None: @@ -1785,8 +1804,7 @@ class Settings(object): del self._config["folder"][type] if not self._config["folder"]: del self._config["folder"] - self._dirty = True - self._dirty_time = time.time() + self._mark_dirty() elif (path != currentPath and path != defaultPath) or force: if validate: _validate_folder(path, check_writable=True, deep_check_writable=True) @@ -1794,8 +1812,7 @@ class Settings(object): if "folder" not in self._config: self._config["folder"] = {} self._config["folder"][type] = path - self._dirty = True - self._dirty_time = time.time() + self._mark_dirty() def saveScript(self, script_type, name, script): script_folder = self.getBaseFolder("scripts") diff --git a/src/octoprint/static/js/app/client/socket.js b/src/octoprint/static/js/app/client/socket.js index b13e1ec14..e2e835e9c 100644 --- a/src/octoprint/static/js/app/client/socket.js +++ b/src/octoprint/static/js/app/client/socket.js @@ -120,6 +120,12 @@ url += "/"; } + var timeout = self.options.connectTimeout; + if (opts.hasOwnProperty("connectTimeout")) { + timeout = opts.connectTimeout; + delete opts.connectTimeout; + } + var onOpen = function() { self.reconnecting = false; self.reconnectTrial = 0; @@ -155,9 +161,11 @@ if (self.connectTimeout) { clearTimeout(self.connectTimeout); } - self.connectTimeout = setTimeout(function() { - self.onConnectTimeout(); - }, self.options.connectTimeout); + if (timeout > 0) { + self.connectTimeout = setTimeout(function() { + self.onConnectTimeout(); + }, timeout); + } self.socket = new SockJS(url + "sockjs", undefined, opts); self.socket.onopen = onOpen; diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 9f2b77a48..7e88e68bf 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -48,7 +48,7 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) { self._connectedDeferred.reject("reconnect"); } self._connectedDeferred = $.Deferred(); - OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG}); + OctoPrint.socket.connect({debug: !!SOCKJS_DEBUG, connectTimeout: SOCKJS_CONNECT_TIMEOUT}); return self._connectedDeferred.promise(); }; diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index c90decd0b..8fd9f46c9 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -320,7 +320,7 @@ $(function() { log.error("At least one folder doesn't have a 'children' element defined. That means the file list request " + "wasn't actually made with 'recursive=true' in the query.\n\n" + "This can happen on wrong reverse proxy configs that " + - "swallow up query parameters, see https://github.com/foosel/OctoPrint/issues/2572"); + "swallow up query parameters, see https://github.com/OctoPrint/OctoPrint/issues/2572"); } if (!switchToPath) { @@ -648,8 +648,7 @@ $(function() { }; self.enableSelectAndPrint = function(data, printAfterSelect) { - var isLoadAndPrintActionPossible = self.isLoadAndPrintActionPossible(); - return isLoadAndPrintActionPossible && !self.listHelper.isSelected(data); + return self.isLoadAndPrintActionPossible(); }; diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 0aee4bf56..17dfef460 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -377,8 +377,8 @@ $(function() { } else { showConfirmationDialog({ message: gettext("This will cancel your print."), - cancel: gettext("No"), - proceed: gettext("Yes"), + cancel: gettext("No, continue the print"), + proceed: gettext("Yes, cancel the print"), onproceed: function() { OctoPrint.job.cancel(); }, diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index 597b3af02..499fdf96b 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -207,6 +207,7 @@ $(function() { self.serial_capBusyProtocol = ko.observable(undefined); self.serial_capEmergencyParser = ko.observable(undefined); self.serial_sendM112OnError = ko.observable(undefined); + self.serial_disableSdPrintingDetection = ko.observable(undefined); self.serial_ackMax = ko.observable(undefined); self.folder_uploads = ko.observable(undefined); diff --git a/src/octoprint/static/js/lib/bootstrap/bootstrap.js b/src/octoprint/static/js/lib/bootstrap/bootstrap.js index 94c4b9f38..494820b0d 100644 --- a/src/octoprint/static/js/lib/bootstrap/bootstrap.js +++ b/src/octoprint/static/js/lib/bootstrap/bootstrap.js @@ -688,7 +688,7 @@ if ('ontouchstart' in document.documentElement) { // if mobile we we use a backdrop because click events don't delegate - // PATCH by foosel based on CapnBry's suggestion - see foosel/OctoPrint#2059 for details + // PATCH by foosel based on CapnBry's suggestion - see OctoPrint/OctoPrint#2059 for details //$('

+
+
+ +
+