Merge branch 'maintenance' into pr/3497

This commit is contained in:
Gina Häußge committed 2020-04-07 12:45:30 +02:00
commit 8604b5c105
60 files changed
+410 -821

No files matched your search

+5 -5
View File
@@ -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
+2
View File
@@ -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
+8 -8
View File
@@ -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`.
+7
View File
@@ -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 <https://github.com/OctoPrint/OctoPrint-FirmwareCheck>`_.
@@ -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 <https://faq.octoprint.org/warning-firmware-unsafe>`_
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 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
.. 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 <https://www.thissmarthouse.net/dont-burn-your-house-down-3d-printing-a-cautionary-tale/>`_
`results <https://www.reddit.com/r/3Dprinting/comments/6cekgk/house_fire_thanks_to_cheap_printer_from_china/>`_.
.. _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``.
+4 -4
View File
@@ -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 <https://github.com/foosel/OctoPrint/wiki/Using-Release-Channels>`_.
"Stable". `Read more about Release Channels here <https://community.octoprint.org/t/how-to-use-the-release-channels-to-help-test-release-candidates/402>`_.
* **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 <https://github.com/foosel/OctoPrint/wiki/Setup-on-a-Raspberry-Pi-running-Raspbian>`_).
(``/home/pi/OctoPrint`` for OctoPi or `manual installs following the Raspberry Pi setup guide <https://community.octoprint.org/t/setting-up-octoprint-on-a-raspberry-pi-running-raspbian/2337/>`_).
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
+1 -1
View File
@@ -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 <https://github.com/foosel/OctoPrint/wiki/Reverse-proxy-configuration-examples>`_ for some
`into OctoPrint's wiki <https://community.octoprint.org/t/reverse-proxy-configuration-examples/1107>`_ for some
examples on how to configure this.
.. _sec-configuration-config_yaml-slicing:
+7 -7
View File
@@ -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 <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ 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 <https://github.com/foosel/OctoPrint/wiki/Setup-on-Mac/>`_.
This guide is based on the `Setup Guide for Mac OS X on OctoPrint's Community Forum <https://community.octoprint.org/t/setting-up-octoprint-on-macos/13425>`_.
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 <https://github.com/foosel/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
`Pull Request <https://github.com/OctoPrint/OctoPrint/blob/master/CONTRIBUTING.md#pull-requests>`_ to get the necessary
steps into this guide!
.. _sec-development-environment-ides-pycharm:
+1 -1
View File
@@ -28,7 +28,7 @@ Finding Plugins
The official OctoPrint Plugin Repository can be found at `plugins.octoprint.org <http://plugins.octoprint.org>`_.
Some plugins may also be found in the list provided in `the OctoPrint wiki <https://github.com/foosel/OctoPrint/wiki#plugins>`_
Some plugins may also be found in the list provided in `the OctoPrint wiki <https://github.com/OctoPrint/OctoPrint/wiki#plugins>`_
and on the `OctoPrint organization Github page <https://github.com/OctoPrint>`_.
.. _sec-features-plugins-installing:
+3 -3
View File
@@ -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 ``<plugin identifier>.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 <https://github.com/foosel/OctoPrint/wiki/Plugin:-Plugin-Manager>`_
install directly via `OctoPrint's built-in Plugin Manager <https://docs.octoprint.org/en/master/bundledplugins/pluginmanager.html>`_
or alternatively manually utilizing Python's standard package manager ``pip`` directly.
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins
@@ -1091,7 +1091,7 @@ you haven't seen yet, :ref:`take a look at the available plugin mixins <sec-plug
For some insight on how to create plugins that react to various events within OctoPrint,
`the Growl Plugin <https://github.com/OctoPrint/OctoPrint-Growl>`_ might be a good example to learn from. For how to
add support for a slicer, OctoPrint's own bundled `CuraEngine plugin <https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura>`_
add support for a slicer, the `CuraEngine Legacy plugin <https://github.com/OctoPrint/OctoPrint-CuraEngineLegacy>`_
might give some hints. For extending OctoPrint's interface, the `NavbarTemp plugin <https://github.com/imrahil/OctoPrint-NavbarTemp>`_
might show what's possible with a few lines of code already. Finally, just take a look at the
`official Plugin Repository <http://plugins.octoprint.org>`_ if you are looking for examples.
+1 -1
View File
@@ -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 <https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery>`_,
`Discovery Plugin <https://docs.octoprint.org/en/master/bundledplugins/discovery.html>`_,
which provides its SSDP browsing and Zeroconf browsing and publishing functions as helper methods.
.. code-block:: python
+2 -2
View File
@@ -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 <https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate>`_
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html>`_
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_<PLUGIN IDENTIFIER>_`` before being made available on ``octoprint.access.permissions.Permissions``,
and prefixed with ``PLUGIN_<PLUGIN IDENTIFIER>_`` 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 _.
+1 -1
View File
@@ -438,7 +438,7 @@ Web interface reconnect
.. seealso::
`OctoPrint's core viewmodels <https://github.com/foosel/OctoPrint/tree/devel/src/octoprint/static/js/app/viewmodels>`_
`OctoPrint's core viewmodels <https://github.com/OctoPrint/OctoPrint/tree/master/src/octoprint/static/js/app/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 <http://knockoutjs.com/documentation/introduction.html>`_
+3
View File
@@ -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
+7 -1
View File
@@ -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:
+13 -8
View File
@@ -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)
@@ -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
+33 -4
View File
@@ -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
@@ -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"]
});
});
@@ -96,26 +96,8 @@
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Backup file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
</span>
<span class="add-on" data-bind="text: backupUploadName"></span>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
</div>
</div>
</form>
{% set plugin_backup_upload_form_id='settings-backup-upload' %}
{% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %}
</div>
<div data-bind="visible: !restoreSupported()">
@@ -0,0 +1,8 @@
<h3>{{ _('Restore from a backup?') }}</h3>
{% trans %}<p>
If you would like to restore OctoPrint configuration from a backup now is the time.
</p>{% endtrans %}
{% set plugin_backup_upload_form_id='wizard-backup-upload' %}
{% include "snippets/plugin/backup/backup_plugin_upload_form.jinja2" %}
@@ -0,0 +1,20 @@
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Backup file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="{{ plugin_backup_upload_form_id }}" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
</span>
<span class="add-on" data-bind="text: backupUploadName"></span>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
</div>
</div>
</form>
@@ -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())
@@ -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 = $("<span id='octopi_support_footer'> " + gettext("running on") + " " + gettext("OctoPi")
+ " <span class='octopi_version'>" + response.octopi_version + "</span></span>");
$(octoPiVersion).insertAfter(octoPrintVersion);
var octoPiVersion = $("<li id='pi_support_footer'><small>" + gettext("OctoPi") + " " + "<span class='octopi_version'>" + response.octopi_version + "</span></small></li>");
$("#footer_version").append(octoPiVersion);
})
};
@@ -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,
@@ -91,6 +91,7 @@
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small data-bind="visible: python"><i class="fa fa-cog"></i> Python <span data-bind="text: python"></span></small>
<small>&nbsp;</small>
</div>
</td>
@@ -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
}
@@ -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
@@ -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
@@ -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;
});
@@ -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}
@@ -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"]
});
});
@@ -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;
}
}
}
@@ -1,7 +0,0 @@
<p><strong>{{ _('Warning!') }}</strong></p>
<!-- ko foreach: warnings -->
<p class="printer_safety_warning">
<span data-bind="text: message"></span><br>
<a target="_blank" rel="noreferrer noopener" data-bind="attr: {href: 'https://faq.octoprint.org/warning-' + type}">{{ _('Learn more...') }}</a>
</p>
<!-- /ko -->
@@ -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"),
@@ -1,7 +1,7 @@
<div class="alert" data-bind="visible: octoprintUnconfigured()">{% trans %}
Please configure the <strong>checkout folder</strong> of OctoPrint, otherwise
this plugin won't be able to update it. Click on the <i class="fa fa-wrench"></i> button
to do this. Also refer to the <a href="https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update" target="_blank">Documentation</a>.
to do this. Also refer to the <a href="https://docs.octoprint.org/en/master/bundledplugins/softwareupdate.html" target="_blank">Documentation</a>.
{% endtrans %}</div>
<div class="alert" data-bind="visible: !octoprintUnconfigured() && octoprintUnreleased()">{% trans %}
<p>
+23 -16
View File
@@ -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"
@@ -81,7 +81,7 @@ $(function() {
"<code>octoprint.log</code>.");
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
});
@@ -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"
+3
View File
@@ -624,6 +624,9 @@ class PrinterCallback(object):
bed:
actual: <temperature of the bed, in degC>
target: <target temperature of the bed, in degC>
chamber:
actual: <temperature of the chamber, in degC>
target: <target temperature of the chamber, in degC>
Arguments:
data (dict): A dict of all current temperatures in the format as specified above
+13 -3
View File
@@ -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)
+48 -30
View File
@@ -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/<string:target>/<path:filename>", 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/<string:target>/<path:filename>", 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/<string:target>/<path:filename>", methods=["POST"])
@no_firstrun_access
def gcodeFileCommand(filename, target):
+2
View File
@@ -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"])
+2 -3
View File
@@ -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"):
+2 -1
View File
@@ -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:
+59 -56
View File
@@ -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
+33 -16
View File
@@ -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")
+11 -3
View File
@@ -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;
+1 -1
View File
@@ -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();
};
@@ -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();
};
@@ -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();
},
@@ -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);
+1 -1
View File
@@ -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
//$('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus)
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
// /PATCH
@@ -9,8 +9,8 @@
<li><i class="fa-li fa fa-users"></i> Community Forum: <a href="https://community.octoprint.org" target="_blank" rel="noreferrer noopener">community.octoprint.org</a></li>
<li><i class="fa-li fa fa-question-circle"></i> FAQ: <a href="https://faq.octoprint.org" target="_blank" rel="noreferrer noopener">faq.octoprint.org</a></li>
<li><i class="fa-li fa fa-book"></i> Documentation: <a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
<li><i class="fa-li fa fa-github"></i> Source Code: <a href="https://github.com/foosel/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/foosel/OctoPrint</a></li>
<li><i class="fa-li fa fa-code-fork"></i> Changelog: <a href="https://github.com/foosel/OctoPrint/releases" target="_blank" rel="noreferrer noopener">github.com/foosel/OctoPrint/releases</a></li>
<li><i class="fa-li fa fa-github"></i> Source Code: <a href="https://github.com/OctoPrint/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/OctoPrint/OctoPrint</a></li>
<li><i class="fa-li fa fa-code-fork"></i> Changelog: <a href="https://github.com/OctoPrint/OctoPrint/releases" target="_blank" rel="noreferrer noopener">github.com/OctoPrint/OctoPrint/releases</a></li>
</ul>
<p>
@@ -76,7 +76,7 @@
<strong>{{ _('There is currently no central repository for language packs like there is for plugins - any help to change that is appreciated!') }}</strong>
</p>
<p>
{{ _('Until a repository is available, please see <a href="%(url)s" target="_blank" >the wiki</a> for language packs provided by the community.', url = "https://github.com/foosel/OctoPrint/wiki#language-packs") }}
{{ _('Until a repository is available, please see <a href="%(url)s" target="_blank" >the wiki</a> for language packs provided by the community.', url = "https://github.com/OctoPrint/OctoPrint/wiki#language-packs") }}
</p>
<h4>{{ _('Available Language Packs') }}</h4>
@@ -244,6 +244,13 @@
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_disableSdPrintingDetection" id="settings-disableSdPrintingDetection"> {{ _('Disable SD printing detection') }} <span class="label">{{ _('Ultimaker 2/2+') }}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
+1
View File
@@ -154,6 +154,7 @@
<div class="footer">
<ul id="footer_version" class="pull-left muted">
<li><small>{{ _('OctoPrint') }} <span class="version">{{ display_version|e }}</span></small></li>
<li><small>{{ _('Python') }} <span class="python_version">{{ python_version|e }}</span></small></li>
</ul>
<ul id="footer_links" class="pull-right">
<li><a href="https://octoprint.org" target="_blank" rel="noreferrer noopener"><i class="fa fa-home"></i> {{ _('Homepage') }}</a></li>
@@ -24,6 +24,7 @@
var SOCKJS_URI = "{{ url_for('index') }}" + "sockjs";
var SOCKJS_DEBUG = CONFIG_DEBUG;
var SOCKJS_CONNECT_TIMEOUT = {{ sockJsConnectTimeout }};
// sockjs should define CLOSE_NORMAL for us, but they don't (from ws spec)
var SOCKJS_CLOSE_NORMAL = 1000;
+44 -11
View File
@@ -279,10 +279,13 @@ class PositionRecord(object):
return dict((attr, getattr(self, attr)) for attr in attrs)
class TemperatureRecord(object):
RESERVED_IDENTIFIER_REGEX = re.compile("[0-9]+|[bc]")
def __init__(self):
self._tools = dict()
self._bed = (None, None)
self._chamber = (None, None)
self._custom = dict()
def copy_from(self, other):
self._tools = other.tools
@@ -300,6 +303,12 @@ class TemperatureRecord(object):
current = self._chamber
self._chamber = self._to_new_tuple(current, actual, target)
def set_custom(self, identifier, actual=None, target=None):
if self.RESERVED_IDENTIFIER_REGEX.match(identifier):
raise ValueError("{} is a reserved identifier".format(identifier))
current = self._custom.get(identifier, (None, None))
self._custom[identifier] = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@@ -312,6 +321,10 @@ class TemperatureRecord(object):
def chamber(self):
return self._chamber
@property
def custom(self):
return dict(self._custom)
def as_script_dict(self):
result = dict()
@@ -328,6 +341,11 @@ class TemperatureRecord(object):
result["c"] = dict(actual=chamber[0],
target=chamber[1])
custom = self.custom
for identifier, data in custom.items():
result[identifier] = dict(actual=data[0],
target=data[1])
return result
@classmethod
@@ -457,6 +475,7 @@ class MachineCom(object):
self._sdRelativePath = settings().getBoolean(["serial", "sdRelativePath"])
self._blockWhileDwelling = settings().getBoolean(["serial", "blockWhileDwelling"])
self._send_m112_on_error = settings().getBoolean(["serial", "sendM112OnError"])
self._disable_sd_printing_detection = settings().getBoolean(["serial", "disableSdPrintingDetection"])
self._current_line = 1
self._line_mutex = threading.RLock()
self._resendDelta = None
@@ -1579,22 +1598,31 @@ class MachineCom(object):
if not tool in parsedTemps:
if shared_nozzle:
actual, target = parsedTemps[current_tool_key]
del parsedTemps[current_tool_key]
else:
continue
else:
actual, target = parsedTemps[tool]
del parsedTemps[tool]
self.last_temperature.set_tool(n, actual=actual, target=target)
# bed temperature
if "B" in parsedTemps:
actual, target = parsedTemps["B"]
del parsedTemps["B"]
self.last_temperature.set_bed(actual=actual, target=target)
# chamber temperature
if "C" in parsedTemps and (self._capability_supported(self.CAPABILITY_CHAMBER_TEMP) or self._printerProfileManager.get_current_or_default()["heatedChamber"]):
actual, target = parsedTemps["C"]
del parsedTemps["C"]
self.last_temperature.set_chamber(actual=actual, target=target)
# all other injected temperatures
for key in parsedTemps.keys():
actual, target = parsedTemps[key]
self.last_temperature.set_custom(key, actual=actual, target=target)
##~~ Serial monitor processing received messages
def _monitor(self):
@@ -1865,7 +1893,7 @@ class MachineCom(object):
self._heatupWaitStartTime = monotonic_time()
self._processTemperatures(line)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber, self.last_temperature.custom)
elif supportRepetierTargetTemp and ('TargetExtr' in line or 'TargetBed' in line):
matchExtr = regex_repetierTempExtr.match(line)
@@ -1876,14 +1904,14 @@ class MachineCom(object):
try:
target = float(matchExtr.group(2))
self.last_temperature.set_tool(toolNum, target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber, self.last_temperature.custom)
except ValueError:
pass
elif matchBed is not None:
try:
target = float(matchBed.group(1))
self.last_temperature.set_bed(target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber, self.last_temperature.custom)
except ValueError:
pass
@@ -1956,6 +1984,11 @@ class MachineCom(object):
self._unknownCommandsNeedAck = True
elif "ultimaker2" in firmware_name.lower():
self._logger.info("Detected Ultimaker2 firmware, enabling relevant features for issue free communication")
self._disable_sd_printing_detection = True
self._firmware_info_received = True
self._firmware_info = data
self._firmware_name = firmware_name
@@ -2444,7 +2477,7 @@ class MachineCom(object):
if self.isOperational() \
and not self._sdstatus_autoreporting \
and not self._connection_closing \
and self.isSdFileSelected() \
and (self.isSdFileSelected() and not self._disable_sd_printing_detection or self.isSdPrinting()) \
and not self._long_running_command \
and not self._dwelling_until \
and not self._heating:
@@ -2537,7 +2570,7 @@ class MachineCom(object):
tools = self.last_temperature.tools
for temp in [tools[k][1] for k in tools.keys()]:
if temp > self._temperatureTargetSetThreshold:
if temp and temp > self._temperatureTargetSetThreshold:
return get("temperatureTargetSet", target_default)
bed = self.last_temperature.bed
@@ -2698,7 +2731,7 @@ class MachineCom(object):
self._logger.exception(error_message)
if "failed to set custom baud rate" in exception_string.lower():
self._log("Your installation does not support custom baudrates (e.g. 250000) for connecting to your printer. This is a problem of the pyserial library that OctoPrint depends on. Please update to a pyserial version that supports your baudrate or switch your printer's firmware to a standard baudrate (e.g. 115200). See https://github.com/foosel/OctoPrint/wiki/OctoPrint-support-for-250000-baud-rate-on-Raspbian")
self._log("Your installation does not support custom baudrates (e.g. 250000) for connecting to your printer. This is a problem of the pyserial library that OctoPrint depends on. Please update to a pyserial version that supports your baudrate or switch your printer's firmware to a standard baudrate (e.g. 115200). See https://github.com/OctoPrint/OctoPrint/wiki/OctoPrint-support-for-250000-baud-rate-on-Raspbian")
return False
@@ -3660,7 +3693,7 @@ class MachineCom(object):
try:
target = float(match.group("value"))
self.last_temperature.set_tool(toolNum, target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber, self.last_temperature.custom)
except ValueError:
pass
@@ -3673,7 +3706,7 @@ class MachineCom(object):
try:
target = float(match.group("value"))
self.last_temperature.set_bed(target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber, self.last_temperature.custom)
except ValueError:
pass
@@ -3686,7 +3719,7 @@ class MachineCom(object):
try:
target = float(match.group("value"))
self.last_temperature.set_chamber(target=target)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber)
self._callback.on_comm_temperature_update(self.last_temperature.tools, self.last_temperature.bed, self.last_temperature.chamber, self.last_temperature.custom)
except ValueError:
pass
@@ -3874,7 +3907,7 @@ class MachineComPrintCallback(object):
def on_comm_log(self, message):
pass
def on_comm_temperature_update(self, temp, bedTemp, chamberTemp):
def on_comm_temperature_update(self, temp, bedTemp, chamberTemp, customTemp):
pass
def on_comm_position_update(self, position, reason=None):
@@ -4078,7 +4111,7 @@ class PrintingGcodeFileInformation(PrintingFileInformation):
"""
PrintingFileInformation.start(self)
with self._handle_mutex:
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace")
self._handle = bom_aware_open(self._filename, encoding="utf-8", errors="replace", newline="")
self._pos = self._handle.tell()
if self._handle.encoding.endswith("-sig"):
# Apparently we found an utf-8 bom in the file.
+2 -2
View File
@@ -150,7 +150,7 @@ def get_all_template_paths(loader):
return collect_templates_for_loader(loader)
def get_all_asset_paths(env):
def get_all_asset_paths(env, verifyExist=True):
result = []
def get_paths(bundle):
@@ -163,7 +163,7 @@ def get_all_asset_paths(env):
r += get_paths(content[1])
else:
path = content[1]
if not os.path.isfile(path):
if verifyExist is True and not os.path.isfile(path):
continue
r.append(path)
except IndexError: