Merge branch 'devel' into dev/gcodeScripts

Conflicts:
	src/octoprint/server/__init__.py
	src/octoprint/server/api/settings.py
	src/octoprint/static/css/octoprint.css
	src/octoprint/static/js/app/viewmodels/settings.js
This commit is contained in:
Gina Häußge committed 2015-02-18 17:18:22 +01:00
commit 654e255b68
65 files changed
+3278 -1120

No files matched your search

+7 -2
View File
@@ -120,6 +120,7 @@
* GCODE viewer now doesn't stumble over completely extrusionless GCODE files
* Do not deliver the API key on settings API unless user has admin rights
* Don't hiccup on slic3r filament_diameter comments in GCODE generated for multi extruder setups
* Color code successful or failed print results directly in file list, not just after a reload
([Commits](https://github.com/foosel/OctoPrint/compare/master...devel))
@@ -130,6 +131,7 @@
* Added deletion of `*.pyc` files to `python setup.py clean` command, should help tremendously when switching branches (backported
from [9e014eb](https://github.com/foosel/OctoPrint/commit/9e014eba1feffde11ed0601d9c911b8cac9f3fb0))
* Increased default communication and connection timeouts
* [#706](https://github.com/foosel/OctoPrint/issues/706) - Do not truncate error reported from printer
### Bug Fixes
@@ -137,8 +139,9 @@
by versioneer
* [#679](https://github.com/foosel/OctoPrint/issues/679) - Fix error where API state is requested and printer is offline
(backport of [619fe9a](https://github.com/foosel/OctoPrint/commit/619fe9a0e78826bd1524b235a910156439bcb6d7)).
* [IRC] - Don't hiccup on slic3r filament_diameter comments generated for multi extruder setups
* [ML] - Fixed relative URL to sockjs endpoint, wasn't yet using the proper base url
* [#719](https://github.com/foosel/OctoPrint/issues/719) - Properly center print bed in GCODE viewer
* [IRC] - Don't hiccup on slic3r ``filament_diameter`` comments generated for multi extruder setups
* [ML] - Fixed relative URL to SockJS endpoint, wasn't yet using the proper base url
* [unreported] & [#698](https://github.com/foosel/OctoPrint/issues/698) - Generated URLs now take X-Forwarded-Host header
sent by proxies into account for included host and port, also fixed [#698](https://github.com/foosel/OctoPrint/issues/698)
introduced by this
@@ -150,6 +153,8 @@
- [unreported] Synchronize image counter decrementing as well as incrementing to prevent rare race conditions when generating the
image file names
([Commits](https://github.com/foosel/OctoPrint/compare/1.1.1...master))
## 1.1.1 (2014-10-27)
### Improvements
+10
View File
@@ -0,0 +1,10 @@
.. _sec-development:
###########
Development
###########
.. toctree::
:maxdepth: 3
interface/index.rst
@@ -0,0 +1,35 @@
.. _sec-development-interface-filemanager:
``octoprint.filemanager``
-------------------------
.. automodule:: octoprint.filemanager
:members:
:undoc-members:
.. _sec-development-interface-filemanager-analysis:
``octoprint.filemanager.analysis``
----------------------------------
.. automodule:: octoprint.filemanager.analysis
:members:
:undoc-members:
.. _sec-development-interface-filemanager-destinations:
``octoprint.filemanager.destinations``
--------------------------------------
.. automodule:: octoprint.filemanager.destinations
:members:
:undoc-members:
.. _sec-development-interface-filemanager-storage:
``octoprint.filemanager.storage``
---------------------------------
.. automodule:: octoprint.filemanager.storage
:members: StorageInterface, LocalFileStorage
+11
View File
@@ -0,0 +1,11 @@
.. _sec-development-interface:
Interfaces
==========
.. toctree::
:maxdepth: 3
filemanager.rst
plugin.rst
printer.rst
+8
View File
@@ -0,0 +1,8 @@
.. _sec-development-interface-plugin:
``octoprint.plugin``
--------------------
.. automodule:: octoprint.plugin
:members: plugin_manager, plugin_settings, call_plugin, PluginSettings
:undoc-members:
+8
View File
@@ -0,0 +1,8 @@
.. _sec-development-interface-plugin:
``octoprint.printer``
---------------------
.. automodule:: octoprint.printer
:members: Printer
:undoc-members:
+1 -1
View File
@@ -56,7 +56,7 @@ Example
Placeholders
============
You can use the following generic placeholders in your events:
You can use the following generic placeholders in your event hooks:
* ``{__currentZ}``: the current Z position of the head if known, -1 if not available
* ``{__filename}``: filename of the currently selected file, "NO FILE" if not available
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

+1
View File
@@ -19,4 +19,5 @@ Contents
api/index.rst
events/index.rst
plugins/index.rst
development/index.rst
-98
View File
@@ -1,98 +0,0 @@
.. _sec-plugins-developing:
******************
Developing Plugins
******************
.. todo::
A section on how to develop plugins yourself, including a tutorial creating an exemplary plugin as well as
a documentation of the plugin API, will be added in the near future.
.. note::
This section is still a heavy WIP, so take it with a bit of caution ;)
.. _sec-plugins-developing-structure:
OctoPrint Plugin Structure
==========================
OctoPrint plugins are simple `Python modules or packages <https://docs.python.org/2/tutorial/modules.html>`_ providing
a couple of properties describing the module:
``__plugin_name__``
Name of your plugin
``__plugin_version__``
Version of your plugin
``__plugin_description__``
Description of your plugin
``__plugin_implementations__``
Instances of one or more of the various :ref:`plugin mixins <sec-plugins-developing-mixins>`
``__plugin_hooks__``
Handlers for one or more of the various :ref:`plugin hooks <sec-plugins-developing-hooks>`
``__plugin_check__``
Method called upon discovery of the plugin by the plugin subsystem, should return ``True`` if the
plugin can be instantiated later on, ``False`` if there are reasons why not, e.g. if dependencies
are missing.
``__plugin_init__``
Method called upon initializing of the plugin by the plugin subsystem, can be used to instantiate
plugin implementations, connecting them to hooks etc.
A very simple example plugin which only hooks into OctoPrint's startup sequence and logs "Oh hello!" would
be the following snippet:
.. code-block:: python
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
__plugin_name__ = "Example Plugin"
__plugin_version__ = "0.1"
__plugin_description__ = "Logs \"Oh hello!\" upon OctoPrint's startup"
def __plugin_init__():
global __plugin_implementations__
__plugin_implementations__ = [ExamplePlugin()]
class ExamplePlugin(octoprint.plugin.StartupPlugin):
def on_startup(self, host, port):
self._logger.info("Oh hello!")
.. _sec-plugins-developing-distribution:
Distributing your plugin
========================
You can distribute a plugin with OctoPrint via two ways:
- You can have your users copy it to OctoPrint's plugin folder (normally located at ``~/.octoprint/plugins`` under Linux,
``%APPDATA%\OctoPrint\plugins`` on Windows and ... on Mac). In this case your plugin will be distributed directly
as a Python module (a single ``.py`` file containing all of your plugin's code directly and named
like your plugin) or a package (a folder named like your plugin + ``__init.py__`` contained within).
- You can have your users install it via ``pip`` and register it for the `entry point <https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins>`_ ``octoprint.plugin`` via
your plugin's ``setup.py``, this way it will be found automatically by OctoPrint upon initialization of the
plugin subsystem [#f1]_.
For an example of how the directory structure and related files would look like in this case, please take a
look at the `helloworld example from OctoPrint's example plugins <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
This variant is highly recommended for pretty much any plugin besides the most basic ones since it also allows
requirements management and pretty much any thing else that Python's setuptools provide to the developer.
.. rubric:: Footnotes
.. [#f1] The automatic registration will only work within the same Python installation (this also includes virtual
environments), so make sure to instruct your users to use the exact same Python installation for installing
the plugin that they also used for installing & running OctoPrint.
.. _sec-plugins-developing-mixins:
Available plugin mixins
=======================
.. automodule:: octoprint.plugin.types
:members:
:undoc-members:
+27
View File
@@ -0,0 +1,27 @@
.. _sec-plugins-distribution:
Distributing your plugin
========================
You can distribute a plugin with OctoPrint via two ways:
- You can have your users copy it to OctoPrint's plugin folder (normally located at ``~/.octoprint/plugins`` under Linux,
``%APPDATA%\OctoPrint\plugins`` on Windows and ... on Mac). In this case your plugin will be distributed directly
as a Python module (a single ``.py`` file containing all of your plugin's code directly and named
like your plugin) or a package (a folder named like your plugin + ``__init.py__`` contained within).
- You can have your users install it via ``pip`` and register it for the `entry point <https://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins>`_ ``octoprint.plugin`` via
your plugin's ``setup.py``, this way it will be found automatically by OctoPrint upon initialization of the
plugin subsystem [#f1]_.
For an example of how the directory structure and related files would look like in this case, please take a
look at the `helloworld example from OctoPrint's example plugins <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
This variant is highly recommended for pretty much any plugin besides the most basic ones since it also allows
requirements management and pretty much any thing else that Python's setuptools provide to the developer.
.. rubric:: Footnotes
.. [#f1] The automatic registration will only work within the same Python installation (this also includes virtual
environments), so make sure to instruct your users to use the exact same Python installation for installing
the plugin that they also used for installing & running OctoPrint.
+906
View File
@@ -0,0 +1,906 @@
.. _sec-plugins-gettingstarted:
Getting Started
===============
Over the course of this little tutorial we'll build a full fledged, installable OctoPrint plugin that displays "Hello World!"
at some locations throughout OctoPrint and also offers some other basic functionality to give you an idea of what
you can achieve with OctoPrint's plugin system.
We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code:
.. code-block:: python
:linenos:
# coding=utf-8
from __future__ import absolute_import
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
2015-01-27 11:14:35,124 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch)
2015-01-27 11:14:35,124 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages...
2015-01-27 11:14:36,135 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1)
OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log
entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from
``__plugin_description__`` and stored it in an internal data structure, but we'll just ignore this for now.
.. _sec-plugins-gettingstarted-sayinghello:
Saying hello: How to make the plugin actually do something
----------------------------------------------------------
Apart from being discovered by OctoPrint, our plugin does nothing yet. We want to change that. Let's make it print
"Hello World!" to the log upon server startup. Modify our ``helloworld.py`` like this:
.. code-block:: python
:emphasize-lines: 4-8,13
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
def on_after_startup(self):
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
__plugin_implementations__ = [HelloWorldPlugin()]
and restart OctoPrint. You now get this output in the log::
2015-01-27 11:17:10,792 - octoprint.plugins.helloworld - INFO - Hello World!
Neat, isn't it? We added a custom class that subclasses one of OctoPrint's :ref:`plugin mixins <sec-plugins-mixins>`
with :class:`~octoprint.plugin.StartupPlugin` and another control property, ``__plugin_implementations__``, that instantiates
our plugin class and tells OctoPrint about it. Taking a look at the documentation of :class:`~octoprint.plugin.StartupPlugin` we see that
this mixin offers two methods that get called by OctoPrint during startup of the server, :func:`~octoprint.plugin.StartupPlugin.on_startup` and
:func:`~octoprint.plugin.StartupPlugin.on_after_startup`. We decided to add our logging output by overriding :func:`~octoprint.plugin.StartupPlugin.on_after_startup`, but we could also have
used :func:`~octoprint.plugin.StartupPlugin.on_startup` instead, in which case our logging statement would be executed before the server was done starting
up and ready to serve requests.
You'll also note that we are using ``self._logger`` for logging. Where did that one come from? OctoPrint's plugin system
injects :ref:`a couple of useful objects <sec-plugins-infrastructure-injections>` into our plugin implementation classes,
one of those being a fully instantiated `python logger <https://docs.python.org/2/library/logging.html>`_ ready to be
used by your plugin. As you can see in the log output above, that logger uses the namespace ``octoprint.plugins.helloworld``
for our little plugin here, or more generally ``octoprint.plugins.<plugin identifier>``.
.. _sec-plugins-gettingstarted-growingup:
Growing up: How to make it distributable
----------------------------------------
If you now want to distribute this plugin to other OctoPrint users (since it is so awesome to be greeted upon server
startup), let's take a look at how you'd go about that now before our plugin gets more complicated.
You basically have two options to distribute your plugin. One would be about the exact same way we are using it now,
as a simple python file following the naming convention ``<plugin identifier>.py`` that your users add to their
``~/.octoprint/plugins`` folder. You already know how that works. But let's say you have more than just a simple plugin
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 (see :ref:`the plugin distribution
documentation <sec-plugins-distribution>` if you want to take a closer look at that option), 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 Python's standard package manager ``pip`` or alternatively via `OctoPrint's own plugin manager <https://github.com/OctoPrint/OctoPrint-PluginManager>`_.
So let's begin. First checkout the `Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_ and rename
the ``octoprint_skeleton`` folder to something better suited to our "Hello World" plugin::
$ git clone https://github.com/OctoPrint/OctoPrint-PluginSkeleton.git OctoPrint-HelloWorld
Cloning into 'OctoPrint-HelloWorld'...
[...]
$ cd OctoPrint-HelloWorld
$ mv octoprint_skeleton octoprint_helloworld
Then edit the configuration in the ``setup.py`` file to mirror our own "Hello World" plugin. The configuration should
look something like this:
.. code-block:: python
:linenos:
plugin_identifier = "helloworld"
plugin_name = "OctoPrint-HelloWorld"
plugin_version = "1.0"
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
plugin_author = "You"
plugin_author_email = "you@somewhere.net"
plugin_url = "https://github.com/you/OctoPrint-HelloWorld"
Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_helloworld`` folder and renaming it to
``__init__.py``. Make sure to delete the copy under ``~/.octoprint/plugins`` in the process, including the `.pyc` file!
The plugin is now ready to be installed via ``python setup.py install``. However, since we are still
working on our plugin, it makes more sense to use ``python setup.py develop`` for now -- this way the plugin becomes
discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do::
$ python setup.py develop
running develop
running egg_info
creating OctoPrint_HelloWorld.egg-info
[...]
Finished processing dependencies for OctoPrint-HelloWorld==1.0
Restart OctoPrint. Your plugin should still be properly discovered and the log line should be printed::
2015-01-27 13:43:34,134 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch)
2015-01-27 13:43:34,134 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages...
2015-01-27 13:43:34,818 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1)
[...]
2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World!
Looks like it still works!
Something is still a bit ugly though. Take a look into ``__init__.py`` and ``setup.py``. It seems like we have a bunch
of information now defined twice:
.. code-block:: python
:linenos:
# __init__.py:
__plugin_name__ = "Hello World"
__plugin_version__ = "1.0"
__plugin_description__ = "A quick \"Hello World\" example plugin for OctoPrint"
# setup.py
plugin_name = "OctoPrint-HelloWorld"
plugin_version = "1.0"
plugin_description = "A quick \"Hello World\" example plugin for OctoPrint"
The nice thing about our plugin now being a proper python package is that OctoPrint can and will access the metadata defined
within ``setup.py``! So, we don't really need to define all this data twice. Remove ``__plugin_name__``, ``__plugin_version__``
and ``__plugin_description__``:
.. code-block:: python
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
def on_after_startup(self):
self._logger.info("Hello World!")
__plugin_implementations__ = [HelloWorldPlugin()]
and restart OctoPrint::
2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - Found 3 plugin(s): OctoPrint-HelloWorld (1.0), CuraEngine (0.1), Discovery (0.1)
Our "Hello World" Plugin still gets detected fine, but it's now listed under the same name it's installed under,
"OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again:
.. code-block:: python
:emphasize-lines: 10
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin):
def on_after_startup(self):
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Restart OctoPrint again::
2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - Found 3 plugin(s): Hello World (1.0), CuraEngine (0.1), Discovery (0.1)
Much better! You can override pretty much all of the metadata defined within ``setup.py`` from within your Plugin itself --
take a look at :ref:`the available control properties <sec-plugins-infrastructure-controlproperties>` for all available
overrides.
Following the README of the `Plugin Skeleton <https://github.com/OctoPrint/OctoPrint-PluginSkeleton>`_ you could now
already publish your plugin on Github and it would be directly installable by others using pip::
pip install https://github.com/you/OctoPrint-HelloWorld/archive/master.zip
But let's add some more features instead.
.. _sec-plugins-gettingstarted-templates:
Frontend fun: How to add functionality to OctoPrint's web interface
-------------------------------------------------------------------
Outputting a log line upon server startup is all nice and well, but we want to greet not only the administrator of
our OctoPrint instance but actually everyone that opens OctoPrint in their browser. Therefore, we need to modify
OctoPrint's web interface itself.
We can do this using the :class:`TemplatePlugin` mixin. For now, let's start with a little "Hello World!" in OctoPrint's
navigation bar right at the top that links to the Wikipedia node about "Hello World" programs. For this we'll first
add the :class:`TemplatePlugin` to our ``HelloWorldPlugin`` class:
.. code-block:: python
:emphasize-lines: 7
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin):
def on_after_startup(self):
self._logger.info("Hello World!")
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Next, we'll create a sub folder ``templates`` underneath our ``octoprint_helloworld`` folder, and within that a file
``helloworld_navbar.jinja2`` like so:
.. code-block:: html
:linenos:
<a href="https://en.wikipedia.org/wiki/Hello_world">Hello World!</a>
Our plugin's directory structure should now look like this::
octoprint_helloworld/
templates/
helloworld_navbar.jinja2
__init__.py
README.md
requirements.txt
setup.py
Restart OctoPrint and open the web interface in your browser (make sure to clear your browser's cache!).
.. _fig-plugins-gettingstarted-helloworld_navbar:
.. figure:: ../images/plugins_gettingstarted_helloworld_navbar.png
:align: center
:alt: Our "Hello World" navigation bar element in action
Now look at that!
.. _sec-plugins-gettingstarted-settings:
Settings Galore: How to make parts of your plugin user adjustable
-----------------------------------------------------------------
Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But
what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node
about "Hello World" programs instead?
To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin`
mixin and override it's :func:`~octoprint.plugin.SettingsPlugin.get_settings_defaults` method. We'll save the URL to
inject into the link under the key ``url`` in our plugin's settings and set it to the old value by default. We'll therefore
return just a single key in our default settings dictionary. To be able to quickly see if we've done that right we'll
extend our little startup message to also log the current setting to the console. We can access that via ``self._settings``,
which is a little settings manager OctoPrint conveniently injects into our Plugin when we include the :class:`~octoprint.plugin.SettingsPlugin`
mixin.
Let's take a look at how all that would look in our plugin's ``__init__.py``:
.. code-block:: python
:emphasize-lines: 8, 10, 12-13
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin):
def on_after_startup(self):
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
def get_settings_defaults(self):
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Restart OctoPrint. You should see something like this::
2015-01-30 11:41:06,058 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://en.wikipedia.org/wiki/Hello_world)
So far so good. But how do we now get that value into our template? We have two options, the
static one using so called template variables and a dynamic one which retrieves that data from the backend and binds it
into the template using `Knockout data bindings <http://knockoutjs.com/documentation/introduction.html>`_. First let's
take a look at the static version using template variables. We already have the :class:`~octoprint.plugin.TemplatePlugin`
mixin included in our plugin, we just need to override its method :func:`~octoprint.plugin.TemplatePlugin.get_template_vars`
to add our URL as a template variable.
Adjust your plugin's ``__init__.py`` like this:
.. code-block:: python
:emphasize-lines: 15-16
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin):
def on_after_startup(self):
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
def get_settings_defaults(self):
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
def get_template_vars(self):
return dict(url=self._settings.get(["url"]))
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Also adjust your plugin's ``templates/helloworld_navbar.jinja2`` like this:
.. code-block:: html
:linenos:
<a href="{{ plugin_helloworld_url|escape }}">Hello World!</a>
OctoPrint injects the template variables that your plugin defines prefixed with ``plugin_<plugin identifier>_`` into
the template renderer, so your ``url`` got turned into ``plugin_helloworld_url`` which you can now use as a simple
`Jinja2 Variable <http://jinja.pocoo.org/docs/dev/templates/#variables>`_ in your plugin's template.
Restart OctoPrint and shift-reload the page in your browser (to make sure you really get a fresh copy). The link should
still work and point to the URL we defined as default.
Let's change the URL! Open up your OctoPrint instance's ``config.yaml`` file and add the following to it (if a ``plugins``
section doesn't yet exist in the file, create it):
.. code-block:: yaml
:emphasize-lines: 3-4
# [...]
plugins:
helloworld:
url: https://de.wikipedia.org/wiki/Hallo-Welt-Programm
# [...]
Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after
a proper shift-reload) point to the german Wikipedia node about "Hello World" programs::
2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm)
Nice! But not very user friendly. We don't have any way yet to edit the URL from within OctoPrint and have to restart
the server and reload the page every time we want a value change to take effect. Let's try adding a little settings dialog
for our plugin in which we can edit the URL and take any changes take immediate effect.
First of all, we'll create the settings dialog. You might already have guessed that we'll need another template for that.
So in your plugin's ``templates`` folder create a new file ``helloworld_settings.jinja2`` and put the following content
into it:
.. code-block:: html
:linenos:
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.helloworld.url">
</div>
</div>
</form>
Note how we access our plugin's property via ``settings.plugins.helloworld.url``. The ``settings`` observable is made
available in the ``SettingsViewModel`` and holds the exact data structure returned from the server for all of
OctoPrint's settings. Accessing plugin settings hence works by following the path under which they are stored in
OctoPrint's internal settings data model (made public via the ``config.yaml``), ``plugins.<plugin identifier>.<configuration key>``.
We'll bind our own settings dialog to the existing ``SettingsViewModel``, so this will be the way we'll access our
property.
Now adjust your ``templates/helloworld_navbar.jinja2`` file to use a ``data-bind`` attribute to set the value from the
settings view model into the ``href`` attribute of the link tag:
.. code-block:: html
:linenos:
<a href="#" data-bind="attr: {href: settings.settings.plugins.helloworld.url}">Hello World!</a>
You might have noticed the quite ugly way to access our plugin's ``url`` property here: ``settings.settings.plugins.helloworld.url``.
The reason for this is that we'll make our plugin use the existing ``NavigationViewModel`` which holds the
``SettingsViewModel`` as a property called ``settings``. So to get to the ``settings`` property of the ``SettingsViewModel``
from the ``NavigationViewModel``, we'll need to first "switch" to the ``SettingsViewModel`` using its property name. Hence
the ugly access string.
If you were now to restart OctoPrint and reload the web interface, you'll get the settings dialog placed just fine
in OctoPrint's settings, and the link would also still show up in the navigation bar, but both the input field of the
settings dialog as well as the link's ``href`` attribute would not show our link. The reason for this is that OctoPrint
by default assumes that you'll want to bind your own view models to your templates and hence "unbinds" the included
templates from the templates that are in place at the injected location already. In order to tell OctoPrint to please
don't do this here (since we *do* want to use both ``NavigationViewModel`` and ``SettingsViewModel``), we'll need to
override the default template configuration using the :class:`~octoprint.plugin.TemplatePlugin`s
:func:`~octoprint.plugin.TemplatePlugin.get_template_configs` method. We'll tell OctoPrint to use no custom bindings
for both our ``navbar`` and our ``settings`` plugin. We'll also remove the override of :func:`octoprint.plugin.TemplatePlugin.get_template_vars`
again since we don't use that anymore:
.. code-block:: python
:emphasize-lines: 15-19
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin):
def on_after_startup(self):
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
def get_settings_defaults(self):
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
def get_template_configs(self):
return [
dict(type="navbar", custom_bindings=False),
dict(type="settings", custom_bindings=False)
]
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Restart OctoPrint and shift-reload your browser. Your link in the navigation bar should still point to the URL we
defined in ``config.yaml`` earlier. Open the "Settings" and click on the new "Hello World" entry that shows up under
"Plugins".
.. _fig-plugins-gettingstarted-helloworld_settings:
.. figure:: ../images/plugins_gettingstarted_helloworld_settings.png
:align: center
:alt: Our "Hello World" navigation bar element in action
Nice! Edit the value, then click "Save". Your link in the navigation bar should now have been updated as well.
.. note::
The way we've done our data binding and how OctoPrint currently works, your link's target will update immediately
when you update the value in the settings dialog. Even if you click Cancel instead of Save, the change will still
be reflected in the UI but will be overwritten again by the stored data upon a reload. This is caused by OctoPrint
not storing a copy of the settings data while it is being edited, which might be changed in the future to
prevent this unexpected behaviour from occurring.
Congratulations, you've just made your Plugin configurable :)
More frontend fun: Adding custom javascript to your frontend components
-----------------------------------------------------------------------
In the previous section we set that ``custom_bindings`` parameter to ``False`` since we wanted OctoPrint to bind the
``SettingsViewModel`` to our settings dialog and the ``NavigationViewModel`` to our entry in the nav bar.
But what if we want to define our own, with more functionality that is already available? Let's take a look. We'll now
add an additional UI component to our OctoPrint interface, a custom tab. It will act as a little internal web browser,
showing the website behind the URL from the settings in an IFrame but also allowing the user to load a different URL
without having to change the settings.
First let us create the Jinja2 template for our tab. In your plugin's ``templates`` folder create a new file
``helloworld_tab.jinja2`` like so:
.. code-block:: html
:linenos:
<div class="input-append">
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
</div>
<iframe data-bind="attr: {src: currentUrl}" style="width: 100%; height: 600px; border: 1px solid #808080"></iframe>
Then we create a new folder in your plugin's root called ``static`` and within that folder another folder by the name of
``js``. Finally, within that folder create a file ``helloworld.js``. Our plugin's folder structure should now
look like this::
octoprint_helloworld/
static/
js/
helloworld.js
templates/
helloworld_navbar.jinja2
helloworld_settings.jinja2
helloworld_tab.jinja2
__init__.py
README.md
requirements.txt
setup.py
We need to tell OctoPrint about this new static asset so that it will properly inject it into the page. For this we
just need to subclass :class:`~octoprint.plugin.AssetPlugin` and override its method :func:`~octoprint.plugin.AssetPlugin.get_assets`
like so:
.. code-block:: python
:emphasize-lines: 9,22-25
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin):
def on_after_startup(self):
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
def get_settings_defaults(self):
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
def get_template_configs(self):
return [
dict(type="navbar", custom_bindings=False),
dict(type="settings", custom_bindings=False)
]
def get_assets(self):
return dict(
js=["js/helloworld.js"]
)
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Note how we did not add another entry to the return value of :func:`~octoprint.plugin.TemplatePlugin.get_template_configs`.
Remember how we only added those since we wanted OctoPrint to use existing bindings on our navigation bar and settings
menu entries? We don't want this this time, and we named our tab template such that OctoPrint will pick it up automatically
so we don't have to do anything here.
Then we'll create our custom `Knockout <http://knockoutjs.com/documentation/introduction.html>`_ view model in ``helloworld.js``
like so:
.. code-block:: javascript
:linenos:
$(function() {
function HelloWorldViewModel(parameters) {
var self = this;
self.settings = parameters[0];
// this will hold the URL currently displayed by the iframe
self.currentUrl = ko.observable();
// this will hold the URL entered in the text field
self.newUrl = ko.observable();
// this will be called when the user clicks the "Go" button and set the iframe's URL to
// the entered URL
self.goToUrl = function() {
self.currentUrl(self.newUrl());
};
// This will get called before the HelloWorldViewModel gets bound to the DOM, but after its
// dependencies have already been initialized. It is especially guaranteed that this method
// gets called _after_ the settings have been retrieved from the OctoPrint backend and thus
// the SettingsViewModel been properly populated.
self.onBeforeBinding = function() {
self.newUrl(self.settings.settings.plugins.helloworld.url());
self.goToUrl();
}
}
// This is how our plugin registers itself with the application, by adding some configuration
// information to the global variable ADDITIONAL_VIEWMODELS
ADDITIONAL_VIEWMODELS.push([
// This is the constructor to call for instantiating the plugin
HelloWorldViewModel,
// This is a list of dependencies to inject into the plugin, the order which you request
// here is the order in which the dependencies will be injected into your view model upon
// instantiation via the parameters argument
["settingsViewModel"],
// Finally, this is the list of all elements we want this view model to be bound to.
[document.getElementById("tab_plugin_helloworld")]
]);
});
Take a close look at lines 31 to 42. This is how our plugin tells OctoPrint about our new view model, how to
instantiate it, which dependencies to inject and to which elements in the final page to bind. Since we want to access
the URL from the settings of our plugin, we'll have OctoPrint inject the ``SettingsViewModel`` into our own view model,
which is registered within OctoPrint under the name ``settingsViewModel``. We'll only bind to our custom tab
for now, which OctoPrint will make available in a container with the id ``tab_plugin_helloworld`` (unless otherwise
configured).
Our view model defines two observables: ``newUrl``, which we bound to the input field in our template, and ``currentUrl``
which we bound to the ``src`` attribute of the "browser iframe" in our template. There's also a function ``goToUrl``
which we bound to the click event of the "Go" button in our template.
Restart OctoPrint and shift-reload the browser. You should see a shiny new "Hello World" tab right at the end of the
tab bar. Click on it!
.. _fig-plugins-gettingstarted-helloworld_tab:
.. figure:: ../images/plugins_gettingstarted_helloworld_tab.png
:align: center
:alt: Our "Hello World" tab in action
The desktop version of that article looks a bit squished in there, so let's enter ``https://de.m.wikipedia.org/wiki/Hallo-Welt-Programm``
into the input field and click the "Go" button. The page inside the iframe should be replaced with the mobile version
of the same article.
Style matters: Injecting custom CSS into the page
-------------------------------------------------
So it appears that this stuff is working great already. Only one thing is a bit ugly, let's take another look at
our ``helloworld_tab.jinja2``:
.. code-block:: html
:linenos:
:emphasize-lines: 6
<div class="input-append">
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
</div>
<iframe data-bind="attr: {src: currentUrl}" style="width: 100%; height: 600px; border: 1px solid #808080"></iframe>
We hardcoded some ``style`` on our ``iframe`` in line 6, to make it look a bit better. It would be nicer if that was actually
located inside a stylesheet instead of directly inside our HTML template. Of course that's no problem, we'll just
add a CSS file to our plugin's provided static assets.
First we'll create a new folder within our plugin's ``static`` folder called ``css`` and within that folders a file
``helloworld.css``. Our plugin's file structure should now look like this::
octoprint_helloworld/
static/
css/
helloworld.css
js/
helloworld.js
templates/
helloworld_navbar.jinja2
helloworld_settings.jinja2
helloworld_tab.jinja2
__init__.py
README.md
requirements.txt
setup.py
Put something like the following into ``helloworld.css``:
.. code-block:: css
:linenos:
#tab_plugin_helloworld {
iframe {
width: 100%;
height: 600px;
border: 1px solid #808080;
}
}
Don't forget to remove the ``style`` attribute from the ``iframe`` tag in ``helloworld_tab.jinja2``:
.. code-block:: html
:linenos:
:emphasize-lines: 6
<div class="input-append">
<input type="text" class="input-xxlarge" data-bind="value: newUrl">
<button class="btn btn-primary" data-bind="click: goToUrl">{{ _('Go') }}</button>
</div>
<iframe data-bind="attr: {src: currentUrl}"></iframe>
Then adjust our plugin's ``__init__.py`` so that the :func:`~octoprint.plugin.AssetPlugin.get_assets` method returns
a reference to our CSS file:
.. code-block:: python
:emphasize-lines: 26
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin):
def on_after_startup(self):
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
def get_settings_defaults(self):
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
def get_template_configs(self):
return [
dict(type="navbar", custom_bindings=False),
dict(type="settings", custom_bindings=False)
]
def get_assets(self):
return dict(
js=["js/helloworld.js"],
css=["css/helloworld.css"]
)
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
Restart OctoPrint, shift-reload your browser and take a look. Everything should still look like before, but now
OctoPrint linked to our stylesheet and the style information for the ``iframe`` is taken from that instead of
hardcoded in our template. Way better!
Now, if you had something more complicated than just the couple of line of CSS we used here, you might want to use
something like LESS for generating your CSS from. If you use `LESS <http://lesscss.org/>`_, which is what OctoPrint
uses for that purpose, you can even put OctoPrint into a mode where it directly uses your LESS files instead of the
generated CSS files (and compiles them on the fly in your browser using `lessjs <http://lesscss.org/#client-side-usage>`_),
which makes development so much easier. Let's try that, so you know how it works for future bigger projects.
Add another folder to our ``static`` folder called ``less`` and within that create a file ``helloworld.less``. Put
into that the same content as into our CSS file. Compile that LESS file to CSS [#f1]_, overwriting our old ``helloworld.css``
in the process. The folder structure of our plugin should now look like this::
octoprint_helloworld/
static/
css/
helloworld.css
js/
helloworld.js
less/
helloworld.less
templates/
helloworld_navbar.jinja2
helloworld_settings.jinja2
helloworld_tab.jinja2
__init__.py
README.md
requirements.txt
setup.py
Then adjust our returned assets to include our LESS file as well:
.. code-block:: python
:emphasize-lines: 27
:linenos:
# coding=utf-8
from __future__ import absolute_import
import octoprint.plugin
class HelloWorldPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin):
def on_after_startup(self):
self._logger.info("Hello World! (more: %s)" % self._settings.get(["url"]))
def get_settings_defaults(self):
return dict(url="https://en.wikipedia.org/wiki/Hello_world")
def get_template_configs(self):
return [
dict(type="navbar", custom_bindings=False),
dict(type="settings", custom_bindings=False)
]
def get_assets(self):
return dict(
js=["js/helloworld.js"],
css=["css/helloworld.css"],
less=["less/helloworld.less"]
)
__plugin_name__ = "Hello World"
__plugin_implementations__ = [HelloWorldPlugin()]
and enable LESS mode by adjusting one of OctoPrint's ``devel`` flags via the ``config.yaml`` file:
.. code-block:: yaml
:emphasize-lines: 2-3
# [...]
devel:
stylesheet: less
# [...]
Restart OctoPrint and shift-reload. Your "Hello World" tab should still look like before. Take a look at the site's
source code. In the ``head`` section of the page you'll see that instead of your ``helloworld.css`` OctoPrint now
embedded the ``helloworld.less`` file instead:
.. code-block:: html
:linenos:
:emphasize-lines: 7
<head>
<!-- [...] -->
<link href="/static/less/octoprint.less" rel="stylesheet/less" type="text/css" media="screen">
<!-- Plugin files -->
<!-- [...] -->
<link href="/plugin_assets/helloworld/less/helloworld.less" rel="stylesheet/less" type="text/css" media="screen">
<!-- [...] -->
<!-- /Plugin files -->
<script src="/static/js/lib/less.min.js" type="text/javascript"></script>
<!-- [...] -->
</head>
Switch your config back to CSS mode by either removing the ``stylesheet`` setting we just added to ``config.yaml`` or
setting it to ``css``, e.g.
.. code-block:: yaml
:emphasize-lines: 3
# [...]
devel:
stylesheet: css
# [...]
Restart and shift-reload and take another look at the ``head``:
.. code-block:: html
:linenos:
:emphasize-lines: 7
<head>
<!-- [...] -->
<link href="/static/css/octoprint.css" rel="stylesheet" type="text/css" media="screen">
<!-- Plugin files -->
<!-- [...] -->
<link href="/plugin_assets/helloworld/css/helloworld.css" rel="stylesheet" type="text/css" media="screen">
<!-- [...] -->
<!-- /Plugin files -->
<!-- [...] -->
</head>
Now the CSS file is linked and no trace of the LESS links is left in the source. This should help to speed up your development
tremendously when you have to work with complex stylesheets, just don't forgot to check the generated CSS file in with
the rest of your plugin or people will miss it when trying to run your plugin!
.. note::
If your plugin only provides CSS files, OctoPrint will detect this when switched to LESS mode and include your
CSS files instead of any non-existing LESS files. So you don't really *have* to use LESS if you don't want, but
as soon as you need it just switch over.
The same thing works the other way around too btw. If your plugin only provides LESS files, OctoPrint will link to
those and add lessjs to the page as well. Please keep in mind though that also providing CSS files is the cleaner
way.
Where do we go from here?
-------------------------
You've now seen how easy it is to add functionality to OctoPrint with this little tutorial. You can find the full
source code of the little Hello World plugin we built together here `on Github <https://github.com/OctoPrint/Plugin-Examples/tree/master/helloworld>`_.
But I want to invite you to dive deeper into OctoPrint's plugin system. To get an idea of all the other various plugin types
you haven't seen yet, :ref:`take a look at the available plugin mixins <sec-plugins-mixins>`.
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>`_
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
`list of available plugins <https://github.com/foosel/OctoPrint/wiki#plugins>`_ on the OctoPrint wiki if you are
looking for examples.
.. rubric:: Footnotes
.. [#f1] Refer to the `LESS documentation <http://lesscss.org/#using-less>`_ on how to do that. If you are developing
your plugin under Windows you might also want to give `WinLESS <http://winless.org/>`_ a look which will run
in the background and keep your CSS files up to date with your various project's LESS files automatically.
+8
View File
@@ -0,0 +1,8 @@
.. _sec-plugins-hooks:
Available plugin hooks
======================
.. todo::
Needs to be documented
+7 -1
View File
@@ -1,3 +1,5 @@
.. automodule:: octoprint.plugin.types
.. _sec-plugins:
#######
@@ -15,4 +17,8 @@ additional slicers. More plugin types are planned for the future.
:maxdepth: 3
using.rst
developing.rst
gettingstarted.rst
infrastructure.rst
distributing.rst
mixins.rst
hooks.rst
+70
View File
@@ -0,0 +1,70 @@
.. _sec-plugins-infrastructure:
Plugin Infrastructure
=====================
.. _sec-plugins-infrastructure-controlproperties:
Control Properties
------------------
``__plugin_name__``
Name of your plugin, optional, overrides the name specified in ``setup.py`` if provided.
``__plugin_version__``
Version of your plugin, optional, overrides the version specified in ``setup.py`` if provided.
``__plugin_description__``
Description of your plugin, optional, overrides the description specified in ``setup.py`` if provided.
``__plugin_author__``
Author of your plugin, optional, overrides the author specified in ``setup.py`` if provided.
``__plugin_url__``
URL of the webpage of your plugin, e.g. the Github repository, optional, overrides the URL specified in ``setup.py`` if
provided.
``__plugin_license__``
License of your plugin, optional, overrides the license specified in ``setup.py`` if provided.
``__plugin_implementations__``
Instances of one or more of the various :ref:`plugin mixins <sec-plugins-mixins>`
``__plugin_hooks__``
Handlers for one or more of the various :ref:`plugin hooks <sec-plugins-hooks>`
``__plugin_check__``
Method called upon discovery of the plugin by the plugin subsystem, should return ``True`` if the
plugin can be instantiated later on, ``False`` if there are reasons why not, e.g. if dependencies
are missing.
``__plugin_init__``
Method called upon initializing of the plugin by the plugin subsystem, can be used to instantiate
plugin implementations, connecting them to hooks etc.
.. _sec-plugins-infrastructure-injections:
Injected Properties
-------------------
``self._identifier``
The plugin's identifier.
``self._plugin_name``
The plugin's name, as taken from either the ``__plugin_name__`` control property or the package info.
``self._plugin_version``
The plugin's version, as taken from either the ``__plugin_version__`` control property or the package info.
``self._basefolder``
The plugin's base folder where it's installed. Can be used to refer to files relative to the plugin's installation
location, e.g. included scripts, templates or assets.
``self._logger``
A `python logger instance <https://docs.python.org/2/library/logging.html>`_ logging to the log target
``octoprint.plugin.<plugin identifier>``.
``self._settings``
The plugin's personalized settings manager, injected only into plugins that include the :class:`SettingsPlugin` mixin.
``self._plugin_manager``
OctoPrint's plugin manager.
``self._printer_profile_manager``
OctoPrint's printer profile manager.
``self._event_bus``
OctoPrint's event bus.
``self._analysis_queue``
OctoPrint's analysis queue for analyzing GCODEs or other files.
``self._slicing_manager``
OctoPrint's slicing manager.
``self._file_manager``
OctoPrint's file manager.
``self._printer``
OctoPrint's printer management object.
``self._app_session_manager``
OctoPrint's application session manager.
+9
View File
@@ -0,0 +1,9 @@
.. _sec-plugins-mixins:
Available plugin mixins
=======================
.. automodule:: octoprint.plugin
:members: AppPlugin, AssetPlugin, BlueprintPlugin, EventHandlerPlugin, ProgressPlugin, SettingsPlugin, ShutdownPlugin, SimpleApiPlugin, SlicerPlugin, StartupPlugin, TemplatePlugin
:undoc-members:
+2 -1
View File
@@ -9,7 +9,8 @@ Flask-Babel==0.9
pyserial
netaddr
watchdog
sarge
sarge>=0.1.4
netifaces
pylru
rsa
pkginfo
+6 -6
View File
@@ -157,7 +157,7 @@ class FileManager(object):
def slice(self, slicer_name, source_location, source_path, dest_location, dest_path,
position=None, profile=None, printer_profile_id=None, overrides=None, callback=None, callback_args=None):
absolute_source_path = self.get_absolute_path(source_location, source_path)
absolute_source_path = self.path_on_disk(source_location, source_path)
def stlProcessed(source_location, source_path, tmp_path, dest_location, dest_path, start_time, printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
@@ -291,7 +291,7 @@ class FileManager(object):
printer_profile = self._printer_profile_manager.get_current_or_default()
file_path = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite)
absolute_path = self._storage(destination).get_absolute_path(file_path)
absolute_path = self._storage(destination).path_on_disk(file_path)
if analysis is None:
file_type = get_file_type(absolute_path)
@@ -343,8 +343,8 @@ class FileManager(object):
def remove_additional_metadata(self, destination, path, key):
self._storage(destination).remove_additional_metadata(path, key)
def get_absolute_path(self, destination, path):
return self._storage(destination).get_absolute_path(path)
def path_on_disk(self, destination, path):
return self._storage(destination).path_on_disk(path)
def sanitize(self, destination, path):
return self._storage(destination).sanitize(path)
@@ -361,8 +361,8 @@ class FileManager(object):
def join_path(self, destination, *path):
return self._storage(destination).join_path(*path)
def rel_path(self, destination, path):
return self._storage(destination).rel_path(path)
def path_in_storage(self, destination, path):
return self._storage(destination).path_in_storage(path)
def _storage(self, destination):
if not destination in self._storage_managers:
+353 -228
View File
@@ -15,73 +15,289 @@ import octoprint.filemanager
from octoprint.util import safeRename
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
yield
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"type": "folder",
"children": {
"some_sub_folder": {
"type": "folder",
"children": { ... }
},
"some_file.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
def add_folder(self, path, ignore_existing=True):
"""
Adds a folder as ``path``. The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``.
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``. Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
refering to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def rel_path(self, path):
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def get_absolute_path(self, path):
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames
stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.
This storage type implements :func:`path_on_disk`.
"""
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
:param string basefolder: the path to the folder under which to create the storage
:param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise
"""
self._logger = logging.getLogger(__name__)
self.basefolder = os.path.realpath(os.path.abspath(basefolder))
@@ -131,55 +347,6 @@ class LocalFileStorage(StorageInterface):
return os.path.exists(file_path) and os.path.isfile(file_path)
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"type": "folder",
"children": {
"some_sub_folder": {
"type": "folder",
"children": { ... }
},
"some_file.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"type": "machinecode",
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"type": "model",
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param path: base path from which to recursively list all files, optional, if not supplied listing will start
from root of base folder
:param filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param recursive: will also step into sub folders for building the complete list if set to True
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
if path:
path = self.sanitize_path(path)
else:
@@ -187,14 +354,6 @@ class LocalFileStorage(StorageInterface):
return self._list_folder(path, filter=filter, recursive=recursive)
def add_folder(self, path, ignore_existing=True):
"""
Adds a folder as ``path``. The ``path`` will be sanitized.
:param path: the path of the new folder
:param ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:return: the sanitized name of the new folder to be used for future references to the folder
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
@@ -204,17 +363,9 @@ class LocalFileStorage(StorageInterface):
else:
os.mkdir(folder_path)
return self.rel_path((path, name))
return self.path_in_storage((path, name))
def remove_folder(self, path, recursive=True):
"""
Removes the folder at ``path``.
:param path: the path of the folder to remove
:param recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
"""
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
@@ -231,19 +382,6 @@ class LocalFileStorage(StorageInterface):
shutil.rmtree(folder_path)
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
:param path: the file's new path, will be sanitized
:param file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param printer_profile: the printer profile associated with this file (if any)
:param links: any links to add with the file
:param allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:return: the sanitized name of the file to be used for future references to it
"""
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
raise RuntimeError("{name} is an unrecognized file type".format(**locals()))
@@ -284,16 +422,9 @@ class LocalFileStorage(StorageInterface):
self._add_links(name, path, links)
return self.rel_path((path, name))
return self.path_in_storage((path, name))
def remove_file(self, path):
"""
Removes the file at ``path``. Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param path: path of the file to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
@@ -322,13 +453,6 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
@@ -343,43 +467,10 @@ class LocalFileStorage(StorageInterface):
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
refering to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` refering to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
path, name = self.sanitize(path)
self._add_links(name, path, [(rel, data)])
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
path, name = self.sanitize(path)
self._remove_links(name, path, [(rel, data)])
@@ -396,22 +487,6 @@ class LocalFileStorage(StorageInterface):
self._update_history(name, path, index)
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
metadata_dirty = False
@@ -437,13 +512,6 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
@@ -457,13 +525,6 @@ class LocalFileStorage(StorageInterface):
self._save_metadata(path, metadata)
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
split = path.split("/")
if len(split) == 1:
return "", split[0]
@@ -471,21 +532,143 @@ class LocalFileStorage(StorageInterface):
return self.join_path(*split[:-1]), split[-1]
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
return "/".join(path)
def get_absolute_path(self, path):
def sanitize(self, path):
"""
Retrieves the absolute path on disk for ``path``
Returns a ``(path, name)`` tuple derived from the provided ``path``.
:param path: the virtual path for which to retrieve the absolute path on disk
:return: the absolute path on disk to ``path``
``path`` may be:
* a storage path
* an absolute file system path
* a tuple or list containing all individual path elements
* a string representation of the path
* with or without a file name
Note that for a ``path`` without a trailing slash the last part will be considered a file name and
hence be returned at second position. If you only need to convert a folder path, be sure to
include a trailing slash for a string ``path`` or an empty last element for a list ``path``.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize("some/folder/and/some file.gco")
("/some/base/folder/some/folder/and", "some_file.gco")
>>> storage.sanitize(("some", "folder", "and", "some file.gco"))
("/some/base/folder/some/folder/and", "some_file.gco")
>>> storage.sanitize("some file.gco")
("/some/base/folder", "some_file.gco")
>>> storage.sanitize(("some file.gco",))
("/some/base/folder", "some_file.gco")
>>> storage.sanitize("")
("/some/base/folder", "")
>>> storage.sanitize("some/folder/with/trailing/slash/")
("/some/base/folder/some/folder/with/trailing/slash", "")
>>> storage.sanitize("some", "folder", "")
("/some/base/folder/some/folder", "")
"""
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def sanitize_name(self, name):
"""
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise strips any characters from the
given ``name`` that are not any of the ASCII characters, digits, ``-``, ``_``, ``.``, ``(``, ``)`` or space and
replaces and spaces with ``_``.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize_name("some_file.gco")
"some_file.gco"
>>> storage.sanitize_name("some_file with (parentheses) and ümläuts and digits 123.gco")
"some_file_with_(parentheses)_and_mluts_and_digits_123.gco"
>>> storage.sanitize_name("pengüino pequeño.stl")
"pengino_pequeo.stl"
>>> storage.sanitize_name("some/folder/still/left.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
>>> storage.sanitize_name("also\\no\\backslashes.gco")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: name must not contain / or \
"""
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def sanitize_path(self, path):
"""
Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all
relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the
absolute path including leading ``basefolder`` path.
Examples::
>>> storage = LocalFileStorage("/some/base/folder")
>>> storage.sanitize_path("folder/with/subfolder")
"/some/base/folder/folder/with/subfolder"
>>> storage.sanitize_path("folder/with/subfolder/../other/folder")
"/some/base/folder/folder/with/other/folder"
>>> storage.sanitize_path("/folder/with/leading/slash")
"/some/base/folder/folder/with/leading/slash"
>>> storage.sanitize_path(".folder/with/leading/dot")
"/some/base/folder/folder/with/leading/dot
>>> storage.sanitize_path("../../folder/out/of/the/basefolder")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: path not contained in base folder: /some/folder/out/of/the/basefolder
"""
if path[0] == "/" or path[0] == ".":
path = path[1:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def path_in_storage(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
def path_on_disk(self, path):
path, name = self.sanitize(path)
return os.path.join(path, name)
@@ -791,64 +974,6 @@ class LocalFileStorage(StorageInterface):
return hash.hexdigest()
def sanitize(self, path):
name = None
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
path = path.split("/")
if isinstance(path, (list, tuple)):
if len(path) == 1:
name = path[0]
path = "/"
else:
name = path[-1]
path = "/" + self.join_path(*path[:-1])
if not path:
path = "/"
name = self.sanitize_name(name)
path = self.sanitize_path(path)
return path, name
def sanitize_name(self, name):
if name is None:
return None
if "/" in name or "\\" in name:
raise ValueError("name must not contain / or \\")
import string
valid_chars = "-_.() {ascii}{digits}".format(ascii=string.ascii_letters, digits=string.digits)
sanitized_name = ''.join(c for c in name if c in valid_chars)
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name
def sanitize_path(self, path):
if path[0] == "/" or path[0] == ".":
path = path[1:]
path_elements = path.split("/")
joined_path = self.basefolder
for path_element in path_elements:
joined_path = os.path.join(joined_path, self.sanitize_name(path_element))
path = os.path.realpath(joined_path)
if not path.startswith(self.basefolder):
raise ValueError("path not contained in base folder: {path}".format(**locals()))
return path
def rel_path(self, path):
if isinstance(path, (tuple, list)):
path = self.join_path(*path)
if isinstance(path, (str, unicode, basestring)):
if path.startswith(self.basefolder):
path = path[len(self.basefolder):]
path = path.replace(os.path.sep, "/")
if path.startswith("/"):
path = path[1:]
return path
def _get_metadata(self, path):
if path in self._metadata_cache:
return self._metadata_cache[path]
+11 -5
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import logging
from octoprint.settings import settings
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
@@ -41,7 +42,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
if "enabled" in all_plugin_settings[key] and not all_plugin_settings[key]:
plugin_disabled_list.append(key)
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=plugin_disabled_list)
_instance = PluginManager(plugin_folders, plugin_types, plugin_entry_points, logging_prefix="octoprint.plugins.", plugin_disabled_list=plugin_disabled_list)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
@@ -51,7 +52,7 @@ def plugin_settings(plugin_key, defaults=None):
return PluginSettings(settings(), plugin_key, defaults=defaults)
def call_plugin(types, method, args=None, kwargs=None, callback=None):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
if not isinstance(types, (list, tuple)):
types = [types]
if args is None:
@@ -62,9 +63,14 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None):
plugins = plugin_manager().get_implementations(*types)
for name, plugin in plugins.items():
if hasattr(plugin, method):
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(name, plugin, result)
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(name, plugin, result)
except Exception as e:
logging.getLogger(__name__).exception("Error while calling plugin %s" % name)
if error_callback:
error_callback(name, plugin, e)
class PluginSettings(object):
+154 -64
View File
@@ -20,6 +20,12 @@ class PluginInfo(object):
attr_version = '__plugin_version__'
attr_author = '__plugin_author__'
attr_url = '__plugin_url__'
attr_license = '__plugin_license__'
attr_hooks = '__plugin_hooks__'
attr_implementations = '__plugin_implementations__'
@@ -30,15 +36,20 @@ class PluginInfo(object):
attr_init = '__plugin_init__'
def __init__(self, key, location, instance, version=None):
def __init__(self, key, location, instance, name=None, version=None, description=None, author=None, url=None, license=None):
self.key = key
self.location = location
self.instance = instance
self.origin = None
self.enabled = True
self.bundled = False
self._name = name
self._version = version
if self.name is None:
raise ValueError("Plugin {key} doesn't have a name".format(key=key))
self._description = description
self._author = author
self._url = url
self._license = license
def __str__(self):
return "{name} ({version})".format(name=self.name, version=self.version if self.version else "unknown")
@@ -61,15 +72,27 @@ class PluginInfo(object):
@property
def name(self):
return self._get_instance_attribute(self.__class__.attr_name, default=None)
return self._get_instance_attribute(self.__class__.attr_name, defaults=(self._name, self.key))
@property
def description(self):
return self._get_instance_attribute(self.__class__.attr_description, default=None)
return self._get_instance_attribute(self.__class__.attr_description, default=self._description)
@property
def version(self):
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=None)
return self._version if self._version is not None else self._get_instance_attribute(self.__class__.attr_version, default=self._version)
@property
def author(self):
return self._get_instance_attribute(self.__class__.attr_author, default=self._author)
@property
def url(self):
return self._get_instance_attribute(self.__class__.attr_url, default=self._url)
@property
def license(self):
return self._get_instance_attribute(self.__class__.attr_license, default=self._license)
@property
def hooks(self):
@@ -91,17 +114,23 @@ class PluginInfo(object):
def init(self):
return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True)
def _get_instance_attribute(self, attr, default=None):
def _get_instance_attribute(self, attr, default=None, defaults=None):
if not hasattr(self.instance, attr):
if defaults is not None:
for value in defaults:
if value is not None:
return value
return default
return getattr(self.instance, attr)
class PluginManager(object):
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=None):
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
logging_prefix = ""
if plugin_disabled_list is None:
plugin_disabled_list = []
@@ -109,26 +138,37 @@ class PluginManager(object):
self.plugin_types = plugin_types
self.plugin_entry_points = plugin_entry_points
self.plugin_disabled_list = plugin_disabled_list
self.logging_prefix = logging_prefix
self.plugins = dict()
self.plugin_hooks = defaultdict(list)
self.plugin_implementations = defaultdict(set)
self.plugin_implementations_by_type = defaultdict(list)
self.disabled_plugins = dict()
self.registered_clients = []
self.reload_plugins()
def _find_plugins(self):
plugins = dict()
disabled_plugins = dict()
if self.plugin_folders:
self._add_plugins_from_folders(self.plugin_folders, plugins)
self._add_plugins_from_folders(self.plugin_folders, plugins, disabled_plugins)
if self.plugin_entry_points:
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins)
return plugins
self._add_plugins_from_entry_points(self.plugin_entry_points, plugins, disabled_plugins)
return plugins, disabled_plugins
def _add_plugins_from_folders(self, folders, plugins):
def _add_plugins_from_folders(self, folders, plugins, disabled_plugins):
for folder in folders:
readonly = False
if isinstance(folder, (list, tuple)):
if len(folder) == 2:
folder, readonly = folder
else:
continue
if not os.path.exists(folder):
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
continue
@@ -143,22 +183,27 @@ class PluginManager(object):
else:
continue
if self._is_plugin_disabled(key):
# plugin is disabled, ignore it
continue
if key in plugins:
# plugin is already defined, ignore it
continue
plugin = self._load_plugin_from_module(key, folder=folder)
if plugin:
plugins[key] = plugin
plugin.origin = ("folder", folder)
if readonly:
plugin.bundled = True
return plugins
if self._is_plugin_disabled(key):
plugin.enabled = False
disabled_plugins[key] = plugin
else:
plugins[key] = plugin
def _add_plugins_from_entry_points(self, groups, plugins):
return plugins, disabled_plugins
def _add_plugins_from_entry_points(self, groups, plugins, disabled_plugins):
import pkg_resources
import pkginfo
if not isinstance(groups, (list, tuple)):
groups = [groups]
@@ -169,42 +214,62 @@ class PluginManager(object):
module_name = entry_point.module_name
version = entry_point.dist.version
if self._is_plugin_disabled(key):
# plugin is disabled, ignore it
continue
if key in plugins:
# plugin is already defined, ignore it
continue
plugin = self._load_plugin_from_module(key, module_name=module_name, version=version)
kwargs = dict(module_name=module_name, version=version)
try:
module_pkginfo = pkginfo.Installed(module_name)
except:
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
else:
kwargs.update(dict(
name=module_pkginfo.name,
summary=module_pkginfo.summary,
author=module_pkginfo.author,
url=module_pkginfo.home_page,
license=module_pkginfo.license
))
plugin = self._load_plugin_from_module(key, **kwargs)
if plugin:
plugins[key] = plugin
plugin.origin = ("entry_point", group, module_name)
return plugins
if self._is_plugin_disabled(key):
plugin.enabled = False
disabled_plugins[key] = plugin
else:
plugins[key] = plugin
def _load_plugin_from_module(self, key, folder=None, module_name=None, version=None):
return plugins, disabled_plugins
def _load_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
# TODO error handling
if folder:
module = imp.find_module(key, [folder])
elif module_name:
module = imp.find_module(module_name)
else:
try:
if folder:
module = imp.find_module(key, [folder])
elif module_name:
module = imp.find_module(module_name)
else:
return None
except:
self.logger.warn("Could not locate plugin {key}")
return None
plugin = self._load_plugin(key, *module, version=version)
plugin = self._load_plugin(key, *module, name=name, version=version, summary=summary, author=author, url=url, license=license)
if plugin:
if plugin.check():
return plugin
else:
self.logger.warn("Plugin \"{plugin}\" did not pass check, disabling it".format(plugin=str(plugin)))
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
return None
def _load_plugin(self, key, f, filename, description, version=None):
def _load_plugin(self, key, f, filename, description, name=None, version=None, summary=None, author=None, url=None, license=None):
try:
instance = imp.load_module(key, f, filename, description)
return PluginInfo(key, filename, instance, version=version)
return PluginInfo(key, filename, instance, name=name, version=version, description=summary, author=author, url=url, license=license)
except:
self.logger.exception("Error loading plugin {key}, disabling it".format(key=key))
return None
@@ -214,43 +279,70 @@ class PluginManager(object):
def reload_plugins(self):
self.logger.info("Loading plugins from {folders} and installed plugin packages...".format(folders=", ".join(self.plugin_folders)))
self.plugins = self._find_plugins()
self.plugins, self.disabled_plugins = self._find_plugins()
for name, plugin in self.plugins.items():
# initialize the plugin
plugin.init()
try:
# initialize the plugin
plugin.init()
# evaluate registered hooks
for hook, callback in plugin.hooks.items():
self.plugin_hooks[hook].append((name, callback))
# evaluate registered hooks
for hook, callback in plugin.hooks.items():
self.plugin_hooks[hook].append((name, callback))
# evaluate registered implementations
for plugin_type in self.plugin_types:
implementations = plugin.get_implementations(plugin_type)
self.plugin_implementations_by_type[plugin_type] += ( (name, implementation) for implementation in implementations )
self.plugin_implementations[name].update(plugin.get_implementations())
# evaluate registered implementations
for plugin_type in self.plugin_types:
implementations = plugin.get_implementations(plugin_type)
self.plugin_implementations_by_type[plugin_type] += ( (name, implementation) for implementation in implementations )
plugin_implementations = plugin.get_implementations()
if len(plugin_implementations):
self.plugin_implementations[name].update(plugin_implementations)
except:
self.logger.exception("There was an error loading plugin %s" % name)
self.log_registered_plugins()
def initialize_implementations(self, additional_injects=None):
def initialize_implementations(self, additional_injects=None, additional_inject_factories=None):
if additional_injects is None:
additional_injects = dict()
if additional_inject_factories is None:
additional_inject_factories = []
for name, implementations in self.plugin_implementations.items():
plugin = self.plugins[name]
for implementation in implementations:
kwargs = dict(additional_injects)
kwargs.update(dict(
identifier=name,
plugin_name=plugin.name,
plugin_version=plugin.version,
basefolder=os.path.realpath(plugin.location),
logger=logging.getLogger("octoprint.plugins." + name),
))
try:
implementation.pre_initialize(**kwargs)
kwargs = dict(additional_injects)
kwargs.update(dict(
identifier=name,
plugin_name=plugin.name,
plugin_version=plugin.version,
basefolder=os.path.realpath(plugin.location),
logger=logging.getLogger(self.logging_prefix + name),
))
# inject the additional_injects
for arg, value in kwargs.items():
setattr(implementation, "_" + arg, value)
# inject any injects produced in the additional_inject_factories
for factory in additional_inject_factories:
try:
return_value = factory(name, implementation)
except:
self.logger.exception("Exception while executing injection factory %r" % factory)
else:
if return_value is not None:
if isinstance(return_value, dict):
for arg, value in return_value.items():
setattr(implementation, "_" + arg, value)
implementation.initialize()
except:
self.logger.exception("Exception while initializing plugin")
# TODO disable plugin!
self.logger.info("Initialized {count} plugin(s)".format(count=len(self.plugin_implementations)))
@@ -260,6 +352,9 @@ class PluginManager(object):
else:
self.logger.info("Found {count} plugin(s): {plugins}".format(count=len(self.plugins), plugins=", ".join(map(lambda x: str(x), self.plugins.values()))))
if len(self.disabled_plugins) > 0:
self.logger.info("{count} plugin(s) currently disabled: {plugins}".format(count=len(self.disabled_plugins), plugins=", ".join(map(lambda x: str(x), self.disabled_plugins.values()))))
def get_plugin(self, name):
if not name in self.plugins:
return None
@@ -310,10 +405,5 @@ class PluginManager(object):
class Plugin(object):
def pre_initialize(self, **kwargs):
for arg, value in kwargs.items():
setattr(self, "_" + arg, value)
self.initialize()
def initialize(self):
pass
+432 -67
View File
@@ -21,10 +21,10 @@ class StartupPlugin(Plugin):
will listen on. Note that the ``host`` may be ``0.0.0.0`` if it will listen on all interfaces, so you can't just
blindly use this for constructing publicly reachable URLs. Also note that when this method is called, the server
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
externally reachable, use ``on_after_startup`` instead or additionally.
externally reachable, use :func:`on_after_startup` instead or additionally.
:param host: the host the server will listen on, may be ``0.0.0.0``
:param port: the port the server will listen on
:param string host: the host the server will listen on, may be ``0.0.0.0``
:param int port: the port the server will listen on
"""
pass
@@ -40,7 +40,7 @@ class StartupPlugin(Plugin):
class ShutdownPlugin(Plugin):
"""
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
``StartupPlugin`` mixin, to cleanly shut down additional services again that where started by the ``StartupPlugin``
:class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin`
part of the plugin.
"""
@@ -57,16 +57,16 @@ class AssetPlugin(Plugin):
be automatically embedded into the pages delivered by the server to be used within the client sided part of
the plugin.
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used on the settings page
of a ``SettingsPlugin``.
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected
through :class:`TemplatePlugin`s.
"""
def get_asset_folder(self):
"""
Defines the folder where the plugin stores its static assets as defined in ``get_assets``. Override this if
Defines the folder where the plugin stores its static assets as defined in :func:`get_assets`. Override this if
your plugin stores its assets at some other place than the ``static`` sub folder in the plugin base directory.
:return: the absolute path to the folder where the plugin stores its static assets
:return string: the absolute path to the folder where the plugin stores its static assets
"""
import os
return os.path.join(self._basefolder, "static")
@@ -84,7 +84,7 @@ class AssetPlugin(Plugin):
LESS files with additional styles, will be embedded into delivered pages when running in LESS mode.
The expected format to be returned is a dictionary mapping one or more of these keys to a list of files of that
type, the files being represented as relative paths from the asset folder as defined via ``get_asset_folder``.
type, the files being represented as relative paths from the asset folder as defined via :func:`get_asset_folder`.
Example:
.. code-block:: python
@@ -96,10 +96,10 @@ class AssetPlugin(Plugin):
less=['less/my_styles.less']
)
The assets will be made available by OctoPrint under the URL ``/plugin_assets/<plugin name>/<path>``, with
``plugin_name`` being the plugin's name and ``path`` being the path as defined in the asset dictionary.
The assets will be made available by OctoPrint under the URL ``/plugin_assets/<plugin identifier>/<path>``, with
``plugin identifier`` being the plugin's identifier and ``path`` being the path as defined in the asset dictionary.
:return: a dictionary describing the static assets to publish for the plugin
:return dict: a dictionary describing the static assets to publish for the plugin
"""
return dict()
@@ -115,22 +115,22 @@ class TemplatePlugin(Plugin):
with the current implementation, plugins will always be located *to the left* of the existing links.
The included template must be called ``<pluginname>_navbar.jinja2`` (e.g. ``myplugin_navbar.jinja2``) unless
overridden by the configuration supplied through ``get_template_config``.
overridden by the configuration supplied through :func:`get_template_configs`.
The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The
wrapper structure will have all additional classes and styles applied as specified via the configuration supplied
through ``get_template_config``.
through :func:`get_template_configs`.
Sidebar
The left side bar containing Connection, State and Files sections can be enriched with additional sections. Note
that with the current implementations, plugins will always be located *beneath* the existing sections.
The included template must be called ``<pluginname>_sidebar.jinja2`` (e.g. ``myplugin_sidebar.jinja2``) unless
overridden by the configuration supplied through ``get_template_config``.
overridden by the configuration supplied through :func:`get_template_configs`.
The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The
wrapper divs for both the whole box as well as the content pane will have all additional classes and styles applied
as specified via the configuration supplied through ``get_template_config``.
as specified via the configuration supplied through :func:`get_template_configs`.
Tabs
The available tabs of the main part of the interface may be extended with additional tabs originating from within
@@ -138,11 +138,11 @@ class TemplatePlugin(Plugin):
tabs.
The included template must be called ``<pluginname>_tab.jinja2`` (e.g. ``myplugin_tab.jinja2``) unless
overridden by the configuration supplied through ``get_template_config``.
overridden by the configuration supplied through :func:`get_template_configs`.
The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The
wrapper div and the link in the navigation will have the additional classes and styles applied as specified via the
configuration supplied through ``get_template_config``.
configuration supplied through :func:`get_template_configs`.
Settings
Plugins may inject a dialog into the existing settings view. Note that with the current implementations, plugins
@@ -150,11 +150,11 @@ class TemplatePlugin(Plugin):
their displayed name.
The included template must be called ``<pluginname>_settings.jinja2`` (e.g. ``myplugin_settings.jinja2``) unless
overridden by the configuration supplied through ``get_template_config``.
overridden by the configuration supplied through :func:`get_template_configs`.
The template will be already wrapped into the necessary structure, plugins just need to supply the pure content. The
wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the
supplied configuration supplied through ``get_template_config``.
supplied configuration supplied through :func:`get_template_configs`.
Generic
Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to
@@ -360,15 +360,16 @@ class TemplatePlugin(Plugin):
those, since the implicit default template will only be included automatically if no other templates of that
type are defined.
:return: a list containing the configuration options for the plugin's injected templates
:return list: a list containing the configuration options for the plugin's injected templates
"""
return []
def get_template_vars(self):
"""
Defines additional template variables to include into the template renderer.
Defines additional template variables to include into the template renderer. Variable names will be prefixed
with ``plugin_<plugin identifier>_``.
:return: a dictionary containing any additional template variables to include in the renderer
:return dict: a dictionary containing any additional template variables to include in the renderer
"""
return dict()
@@ -377,95 +378,410 @@ class TemplatePlugin(Plugin):
Defines the folder where the plugin stores its templates. Override this if your plugin stores its templates at
some other place than the ``templates`` sub folder in the plugin base directory.
:return: the absolute path to the folder where the plugin stores its jinja2 templates
:return string: the absolute path to the folder where the plugin stores its jinja2 templates
"""
import os
return os.path.join(self._basefolder, "templates")
class SimpleApiPlugin(Plugin):
"""
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
resource accepting JSON commands POSTed to it. This is the easy alternative for plugin's which don't need the
full power of a `Flask Blueprint <http://flask.pocoo.org/docs/0.10/blueprints/>`_ that the :class:`BlueprintPlugin`
mixin offers.
Use this mixin if all you need to do is return some kind of dynamic data to your plugin from the backend
and/or want to react to simple commands which boil down to a type of command and a couple of flat parameters
supplied with it.
The simple API constructed by OctoPrint for you will be made available under ``/api/plugin/<plugin identifier>/``.
OctoPrint will do some preliminary request validation for your defined commands, making sure the request body is in
the correct format (content type must be JSON) and contains all obligatory parameters for your command.
Let's take a look at a small example for such a simple API and how you would go about calling it.
Take this example of a plugin registered under plugin identifier ``mysimpleapiplugin``:
.. code-block:: python
:linenos:
import octoprint.plugin
import flask
class MySimpleApiPlugin(octoprint.plugin.SimpleApiPlugin):
def get_api_commands(self):
return dict(
command1=[],
command2=["some_parameter"]
)
def on_api_command(self, command, data):
import flask
if command == "command1":
parameter = "unset"
if "parameter" in data:
parameter = "set"
self._logger.info("command1 called, parameter is {parameter}".format(**locals()))
elif command == "command2":
self._logger.info("command2 called, some_parameter is {some_parameter}".format(**data))
def on_api_get(self, request):
return flask.jsonify(foo="bar")
__plugin_implementations__ = [MySimpleApiPlugin()]
Our plugin defines two commands, ``command1`` with no mandatory parameters and ``command2`` with one
mandatory parameter ``some_parameter``.
``command1`` can also accept an optional parameter ``parameter``, and will log whether
that parameter was set or unset. ``command2`` will log the content of the mandatory ``some_parameter`` parameter.
A valid POST request for ``command2`` sent to ``/api/plugin/mysimpleapiplugin`` would look like this:
.. sourcecode:: http
POST /api/plugin/mysimpleapiplugin HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "command2",
"some_parameter": "some_value",
"some_optional_parameter": 2342
}
which would produce a response like this:
.. sourcecode:: http
HTTP/1.1 204 No Content
and print something like this line to ``octoprint.log``::
2015-02-12 17:40:21,140 - octoprint.plugins.mysimpleapiplugin - INFO - command2 called, some_parameter is some_value
A GET request on our plugin's simple API resource will only return a JSON document like this:
.. sourcecode:: http
HTTP/1.1 200 Ok
Content-Type: application/json
{
"foo": "bar"
}
"""
def get_api_commands(self):
"""
Return a dictionary here with the keys representing the accepted commands and the values being lists of
mandatory parameter names.
"""
return None
def on_api_command(self, command, data):
"""
Called by OctoPrint upon a POST request to ``/api/plugin/<plugin identifier>``. ``command`` will contain one of
the commands as specified via :func:`get_api_commands`, ``data`` will contain the full request body parsed
from JSON into a Python dictionary. Note that this will also contain the ``command`` attribute itself. For the
example given above, for the ``command2`` request the ``data`` received by the plugin would be equal to
``dict(command="command2", some_parameter="some_value")``.
If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content``
for you. You may also return regular responses as you would return from any Flask view here though, e.g.
``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``.
:param string command: the command with which the resource was called
:param dict data: the full request body of the POST request parsed from JSON into a Python dictionary
:return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally
a proper Flask response.
"""
return None
def on_api_get(self, request):
"""
Called by OctoPrint upon a GET request to ``/api/plugin/<plugin identifier>``. ``request`` will contain the
received `Flask request object <http://flask.pocoo.org/docs/0.9/api/#flask.Request>`_ which you may evaluate
for additional arguments supplied with the request.
If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content``
for you. You may also return regular responses as you would return from any Flask view here though, e.g.
``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``.
:param request: the Flask request object
:return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally
a proper Flask response.
"""
return None
class BlueprintPlugin(Plugin):
"""
The ``BlueprintPlugin`` mixin allows plugins to define their own full fledged endpoints for whatever purpose,
be it a more sophisticated API than what is possible via the ``SimpleApiPlugin`` or a custom web frontend.
be it a more sophisticated API than what is possible via the :class:`SimpleApiPlugin` or a custom web frontend.
The mechanism at work here is `Flask's <http://flask.pocoo.org/>`_ own `Blueprint mechanism <http://flask.pocoo.org/docs/0.10/blueprints/>`_.
Your plugin should define a blueprint like this:
The mixin automatically creates a blueprint for you that will be registered under ``/plugin/<plugin identifier>/``.
All you need to do is decorate all of your view functions with the :func:`route` decorator,
which behaves exactly the same like Flask's regular ``route`` decorators. Example:
.. code-block:: python
:linenos:
import octoprint.plugin
import flask
class MyBlueprintPlugin(octoprint.plugin.BlueprintPlugin):
@octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"])
def myEcho(self):
if not "text" in flask.request.values:
return flask.make_response("Expected a text to echo back.", 400)
return flask.request.values["text"]
__plugin_implementations__ = [MyPlugin()]
Your blueprint will be published by OctoPrint under the base URL ``/plugin/<plugin identifier>/``, so the above
example of a plugin with the identifier "myblueprintplugin" would be reachable under
``/plugin/myblueprintplugin/echo``.
Just like with regular blueprints you'll be able to create URLs via ``url_for``, just use the prefix
``plugin.<plugin identifier>``, e.g.:
.. code-block:: python
template_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
blueprint = flask.Blueprint("plugin.myplugin", __name__, template_folder=template_folder)
flask.url_for("plugin.myblueprintplugin.echo") # will return "/plugin/myblueprintplugin/echo"
Use your blueprint just like any other Flask blueprint for defining your own endpoints, e.g.
.. code-block:: python
@blueprint.route("/echo", methods=["GET"])
def myEcho():
if not "text" in flask.request.values:
return flask.make_response("Expected a text to echo back.", 400)
return flask.request.values["text"]
Your blueprint will be published by OctoPrint under the URL ``/plugin/<pluginname>/``, so the above example
would be reachable under ``/plugin/myplugin/echo`` (given that you named your plugin "myplugin"). You'll be able
to create URLs via ``url_for`` under the prefix that you've chosen when constructing your blueprint, ``plugin.myplugin``
in the above example:
.. code-block:: python
flask.url_for("plugin.myplugin.echo") # will return "/plugin/myplugin/echo"
OctoPrint Blueprint plugins should always follow the naming scheme ``plugin.<plugin name>`` here
to avoid conflicts.
"""
@staticmethod
def route(rule, **options):
"""
A decorator to mark view methods in your BlueprintPlugin subclass. Works just the same as Flask's
own ``route`` decorator available on blueprints.
See `the documentation for flask.Blueprint.route <http://flask.pocoo.org/docs/0.10/api/#flask.Blueprint.route>`_
and `the documentation for flask.Flask.route <http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route>`_ for more
information.
"""
from collections import defaultdict
def decorator(f):
# We attach the decorator parameters directly to the function object, because that's the only place
# we can access right now.
# This neat little trick was adapter from the Flask-Classy project: https://pythonhosted.org/Flask-Classy/
if not hasattr(f, "_blueprint_rules") or f._blueprint_rules is None:
f._blueprint_rules = defaultdict(list)
f._blueprint_rules[f.__name__].append((rule, options))
return f
return decorator
def get_blueprint(self):
"""
Retrieves the blueprint as defined by your plugin.
Creates and returns the blueprint for your plugin. Override this if you want to define and handle your blueprint yourself.
This method will only be called once during server initialization.
:return: the blueprint ready to be registered with Flask
"""
return None
import flask
kwargs = self.get_blueprint_kwargs()
blueprint = flask.Blueprint("plugin." + self._identifier, self._identifier, **kwargs)
for member in [member for member in dir(self) if not member.startswith("_")]:
f = getattr(self, member)
if hasattr(f, "_blueprint_rules") and member in f._blueprint_rules:
for blueprint_rule in f._blueprint_rules[member]:
rule, options = blueprint_rule
blueprint.add_url_rule(rule, options.pop("endpoint", f.__name__), view_func=f, **options)
return blueprint
def get_blueprint_kwargs(self):
"""
Override this if you want your blueprint constructed with additional options such as ``static_folder``,
``template_folder``, etc.
Defaults to the blueprint's ``static_folder`` and ``template_folder`` to be set to the plugin's basefolder
plus ``/static`` or respectively ``/templates``.
"""
import os
return dict(
static_folder=os.path.join(self._basefolder, "static"),
template_folder=os.path.join(self._basefolder, "templates")
)
def is_blueprint_protected(self):
"""
Whether the blueprint is supposed to be protected by API key (the default) or not.
Whether a valid API key is needed to access the blueprint (the default) or not.
"""
return True
class SettingsPlugin(Plugin):
"""
Including the ``SettingsPlugin`` mixin allows plugins to store and retrieve their own settings within OctoPrint's
configuration.
Plugins including the mixing will get injected an additional property ``self._settings`` which is an instance of
:class:`PluginSettingsManager` already properly initialized for use by the plugin. In order for the manager to
know about the available settings structure and default values upon initialization, implementing plugins will need
to provide a dictionary with the plugin's default settings through overriding the method :func:`get_settings_defaults`.
The defined structure will then be available to access through the settings manager available as ``self._settings``.
If your plugin needs to react to the change of specific configuration values on the fly, e.g. to adjust the log level
of a logger when the user changes a corresponding flag via the settings dialog, you can override the
:func:`on_settings_save` method and wrap the call to the implementation from the parent class with retrieval of the
old and the new value and react accordingly.
Example:
.. code-block:: python
import octoprint.plugin
class MySettingsPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin):
def get_settings_defaults(self):
return dict(
some_setting="foo",
some_value=23,
sub=dict(
some_flag=True
)
)
def on_settings_save(self, data):
old_flag = self._settings.getBoolean(["sub", "some_flag"])
super(MySettingsPlugin, self).on_settings_save(data)
new_flag = self._settings.getBoolean(["sub", "some_flag"])
if old_flag != new_flag:
self._logger.info("sub.some_flag changed from {old_flag} to {new_flag}".format(**locals()))
def on_after_startup(self):
some_setting = self._settings.get(["some_setting"])
some_value = self._settings.getInt(["some_value"])
some_flag = self._settings.getBoolean(["sub", "some_flag"])
self._logger.info("some_setting = {some_setting}, some_value = {some_value}, sub.some_flag = {some_flag}".format(**locals())
__plugin_implementations__ = [MySettingsPlugin()]
Of course, you are always free to completely override both :func:`on_settings_load` and :func:`on_settings_save` if the
default implementations do not fit your requirements.
"""
def on_settings_load(self):
return None
"""
Loads the settings for the plugin, called by the Settings API view in order to retrieve all settings from
all plugins. Override this if you want to inject additional settings properties that are not stored within
OctoPrint's configuration.
.. note::
The default implementation will return your plugin's settings as is, so just in the structure and in the types
that are currently stored in OctoPrint's configuration.
If you need more granular control here, e.g. over the used data types, you'll need to override this method
and iterate yourself over all your settings, using the proper retriever methods on the settings manager
to retrieve the data in the correct format.
:return: the current settings of the plugin, as a dictionary
"""
return self._settings.get([], asdict=True, merged=True)
def on_settings_save(self, data):
pass
"""
Saves the settings for the plugin, called by the Settings API view in order to persist all settings
from all plugins. Override this if you need to directly react to settings changes or want to extract
additional settings properties that are not stored within OctoPrint's configuration.
.. note::
The default implementation will persist your plugin's settings as is, so just in the structure and in the
types that were received by the Settings API view.
If you need more granular control here, e.g. over the used data types, you'll need to override this method
and iterate yourself over all your settings, retrieving them (if set) from the supplied received ``data``
and using the proper setter methods on the settings manager to persist the data in the correct format.
:param dict data: the settings dictionary to be saved for the plugin
"""
import octoprint.util
current = self._settings.get([], asdict=True, merged=True)
data = octoprint.util.dict_merge(current, data)
self._settings.set([], data)
def get_settings_defaults(self):
"""
Retrieves the plugin's default settings with which the plugin's settings manager will be initialized.
Override this in your plugin's implementation and return a dictionary defining your settings data structure
with included default values.
"""
return dict()
class EventHandlerPlugin(Plugin):
"""
The ``EventHandlerPlugin`` mixin allows OctoPrint plugins to react to any of :ref:`OctoPrint's events <sec-events>`.
OctoPrint will call the :func:`on_event` method for any event fired on its internal event bus, supplying the
event type and the associated payload. Please note that until your plugin returns from that method, further event
processing within OctoPrint will block - the event queue itself is run asynchronously from the rest of OctoPrint,
but the processing of the events within the queue itself happens consecutively.
This mixin is especially interesting for plugins which want to react on things like print jobs finishing, timelapse
videos rendering etc.
"""
def on_event(self, event, payload):
"""
Called by OctoPrint upon processing of a fired event on the platform.
:param string event: the type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
for possible values
:param dict payload: the payload as provided with the event
"""
pass
class SlicerPlugin(Plugin):
"""
Via the ``SlicerPlugin`` mixin plugins can add support for slicing engines to be used by OctoPrint.
"""
def is_slicer_configured(self):
"""
Unless the return value of this method is ``True``, OctoPrint will not register the slicer within the slicing
sub system upon startup. Plugins may use this to do some start up checks to verify that e.g. the path to
a slicing binary as set and the binary is executable, or credentials of a cloud slicing platform are properly
entered etc.
"""
return False
def get_slicer_properties(self):
"""
Plugins should override this method to return a ``dict`` containing a bunch of meta data about the implemented slicer.
The expected keys in the returned ``dict`` have the following meaning:
type
The type identifier to use for the slicer. This should be a short unique lower case string which will be
used to store slicer profiles under or refer to the slicer programmatically or from the API.
name
The human readable name of the slicer. This will be displayed to the user during slicer selection.
same_device
``True`` if the slicer runs on the same device as OctoPrint, ``False`` otherwise. Slicers running on the same
device will TODO
progress_report
``True`` if the slicer can report back slicing progress to OctoPrint ``False`` otherwise.
"""
return dict(
type=None,
name=None,
@@ -473,22 +789,71 @@ class SlicerPlugin(Plugin):
progress_report=False
)
def get_slicer_profile_options(self):
def get_slicer_default_profile(self):
"""
Should return a :class:`SlicingProfile` containing the default slicing profile to use with this slicer if
no other profile has been selected.
"""
return None
def get_slicer_profile(self, path):
return None
"""
Should return a :class:`SlicingProfile` parsed from the slicing profile stored at the indicated ``path``.
def get_slicer_default_profile(self):
:param string path: the path from which to read the slicing profile
"""
return None
def save_slicer_profile(self, path, profile, allow_overwrite=True, overrides=None):
"""
Should save the provided :class:`SlicingProfile` to the indicated ``path``, after applying any supplied
``overrides``. If a profile is already saved under the indicated path and ``allow_overwrite`` is set to
``False`` (defaults to ``True``), an ``IOError`` should be raised.
:param string path: the path to which to save the profile
:param :class:`SlicingProfile` profile: the profile to save
:param bool allow_overwrite: whether to allow to overwrite an existing profile at the indicated path (``True``, default)
or not (``False``) - if a profile already exists on the path and this is ``False``
and :class:`IOError` should be raised
:param dict overrides: profile overrides to apply to the ``profile`` before saving it
"""
pass
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
def do_slice(self, model_path, printer_profile, machinecode_path=None, profile_path=None, position=None, on_progress=None, on_progress_args=None, on_progress_kwargs=None):
"""
Called by OctoPrint to slice ``model_path`` for the indicated ``printer_profile``. If the ``machinecode_path`` is ``None``,
slicer implementations should generate it from the provided model_path.
If provided, the ``profile_path`` is guaranteed by OctoPrint to be a serialized slicing profile created through the slicing
plugin's own :func:`save_slicer_profile` method.
If provided, ``position`` will be a ``dict`` containing and ``x`` and a ``y`` key, indicating the position
the center of the model on the print bed should have in the final sliced machine code. If not provided, slicer
implementations should place the model in the center of the print bed.
``on_progress`` will be a callback which expects an additional keyword argument ``_progress`` with the current
slicing progress which - if progress reporting is supported - the slicing plugin should call like the following:
.. code-block:: python
if on_progress is not None:
if on_progress_args is None:
on_progress_args = ()
if on_progress_kwargs is None:
on_progress_kwargs = dict()
on_progress_kwargs["_progress"] = your_plugins_slicing_progress
on_progress(*on_progress_args, **on_progress_kwargs)
Please note that both ``on_progress_args`` and ``on_progress_kwargs`` as supplied by OctoPrint might be ``None``,
so always make sure to initialize those values to sane defaults like depicted above before invoking the callback.
"""
pass
def cancel_slicing(self, machinecode_path):
"""
Cancels the slicing to the indicated file
"""
pass
@@ -502,9 +867,9 @@ class ProgressPlugin(Plugin):
"""
Called by OctoPrint on minimally 1% increments during a running print job.
:param location string: Location of the file
:param path string: Path of the file
:param progress int: Current progress as a value between 0 and 100
:param string location: Location of the file
:param string path: Path of the file
:param int progress: Current progress as a value between 0 and 100
"""
pass
@@ -512,12 +877,12 @@ class ProgressPlugin(Plugin):
"""
Called by OctoPrint on minimally 1% increments during a running slicing job.
:param slicer string: Key of the slicer reporting the progress
:param source_location string: Location of the source file
:param source_path string: Path of the source file
:param destination_location string: Location the destination file
:param destination_path string: Path of the destination file
:param progress int: Current progress as a value between 0 and 100
:param string slicer: Key of the slicer reporting the progress
:param string source_location: Location of the source file
:param string source_path: Path of the source file
:param string destination_location: Location the destination file
:param string destination_path: Path of the destination file
:param int progress: Current progress as a value between 0 and 100
"""
pass
+100 -112
View File
@@ -16,91 +16,8 @@ import octoprint.util
import octoprint.slicing
import octoprint.settings
default_settings = {
"cura_engine": None,
"default_profile": None,
"debug_logging": False
}
s = octoprint.plugin.plugin_settings("cura", defaults=default_settings)
from .profile import Profile
blueprint = flask.Blueprint("plugin.cura", __name__)
@blueprint.route("/import", methods=["POST"])
def importCuraProfile():
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + s.globalGet(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + s.globalGet(["server", "uploads", "pathSuffix"])
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
filename = flask.request.values[input_upload_name]
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
elif input_name in flask.request.files:
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
try:
temp_file.close()
upload = flask.request.files[input_name]
upload.save(temp_file.name)
profile_dict = Profile.from_cura_ini(temp_file.name)
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
finally:
os.remove(temp_file)
filename = upload.filename
else:
return flask.make_response("No file included", 400)
if profile_dict is None:
return flask.make_response("Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.getFormattedDateTime(datetime.datetime.now()))
profile_allow_overwrite = False
# overrides
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
profile_display_name = flask.request.values["displayName"]
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
from octoprint.server.api import valid_boolean_trues
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
slicingManager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
displayName=profile_display_name,
description=profile_description
)
r = flask.make_response(flask.jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
@@ -122,19 +39,88 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
def on_startup(self, host, port):
# setup our custom logger
cura_logging_handler = logging.handlers.RotatingFileHandler(s.getPluginLogfilePath(postfix="engine"), maxBytes=2*1024*1024)
cura_logging_handler = logging.handlers.RotatingFileHandler(self._settings.getPluginLogfilePath(postfix="engine"), maxBytes=2*1024*1024)
cura_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
cura_logging_handler.setLevel(logging.DEBUG)
self._cura_logger.addHandler(cura_logging_handler)
self._cura_logger.setLevel(logging.DEBUG if s.getBoolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.setLevel(logging.DEBUG if self._settings.getBoolean(["debug_logging"]) else logging.CRITICAL)
self._cura_logger.propagate = False
##~~ BlueprintPlugin API
def get_blueprint(self):
global blueprint
return blueprint
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
def importCuraProfile(self):
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + self._settings.globalGet(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + self._settings.globalGet(["server", "uploads", "pathSuffix"])
if input_upload_name in flask.request.values and input_upload_path in flask.request.values:
filename = flask.request.values[input_upload_name]
try:
profile_dict = Profile.from_cura_ini(flask.request.values[input_upload_path])
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
elif input_name in flask.request.files:
temp_file = tempfile.NamedTemporaryFile("wb", delete=False)
try:
temp_file.close()
upload = flask.request.files[input_name]
upload.save(temp_file.name)
profile_dict = Profile.from_cura_ini(temp_file.name)
except Exception as e:
return flask.make_response("Something went wrong while converting imported profile: {message}".format(e.message), 500)
finally:
os.remove(temp_file)
filename = upload.filename
else:
return flask.make_response("No file included", 400)
if profile_dict is None:
return flask.make_response("Could not convert Cura profile", 400)
name, _ = os.path.splitext(filename)
# default values for name, display name and description
profile_name = _sanitize_name(name)
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.getFormattedDateTime(datetime.datetime.now()))
profile_allow_overwrite = False
# overrides
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
profile_display_name = flask.request.values["displayName"]
if "description" in flask.request.values:
profile_description = flask.request.values["description"]
if "allowOverwrite" in flask.request.values:
from octoprint.server.api import valid_boolean_trues
profile_allow_overwrite = flask.request.values["allowOverwrite"] in valid_boolean_trues
slicingManager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
displayName=profile_display_name,
description=profile_description
)
r = flask.make_response(flask.jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
##~~ AssetPlugin API
@@ -147,32 +133,29 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
##~~ SettingsPlugin API
def on_settings_load(self):
return dict(
cura_engine=s.get(["cura_engine"]),
default_profile=s.get(["default_profile"]),
debug_logging=s.getBoolean(["debug_logging"])
)
def on_settings_save(self, data):
if "cura_engine" in data and data["cura_engine"]:
s.set(["cura_engine"], data["cura_engine"])
if "default_profile" in data and data["default_profile"]:
s.set(["default_profile"], data["default_profile"])
if "debug_logging" in data:
old_debug_logging = s.getBoolean(["debug_logging"])
new_debug_logging = data["debug_logging"] in octoprint.settings.valid_boolean_trues
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
else:
self._cura_logger.setLevel(logging.CRITICAL)
s.setBoolean(["debug_logging"], new_debug_logging)
old_debug_logging = self._settings.getBoolean(["debug_logging"])
super(CuraPlugin, self).on_settings_save(data)
new_debug_logging = self._settings.getBoolean(["debug_logging"])
if old_debug_logging != new_debug_logging:
if new_debug_logging:
self._cura_logger.setLevel(logging.DEBUG)
else:
self._cura_logger.setLevel(logging.CRITICAL)
def get_settings_defaults(self):
return dict(
cura_engine=None,
default_profile=None,
debug_logging=False
)
##~~ SlicerPlugin API
def is_slicer_configured(self):
cura_engine = s.get(["cura_engine"])
cura_engine = self._settings.get(["cura_engine"])
if cura_engine is not None and os.path.exists(cura_engine):
return True
else:
@@ -187,7 +170,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
)
def get_slicer_default_profile(self):
path = s.get(["default_profile"])
path = self._settings.get(["default_profile"])
if not path:
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "profiles", "default.profile.yaml")
return self.get_slicer_profile(path)
@@ -221,7 +204,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
try:
with self._job_mutex:
if not profile_path:
profile_path = s.get(["default_profile"])
profile_path = self._settings.get(["default_profile"])
if not machinecode_path:
path, _ = os.path.splitext(model_path)
machinecode_path = path + ".gco"
@@ -243,7 +226,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
executable = s.get(["cura_engine"])
executable = self._settings.get(["cura_engine"])
if not executable:
return False, "Path to CuraEngine is not configured "
@@ -258,6 +241,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._logger.info("Running %r in %s" % (command, working_dir))
p = sarge.run(command, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
self._slicing_commands[machinecode_path] = p.commands[0]
try:
@@ -430,4 +414,8 @@ def _sanitize_name(name):
__plugin_name__ = "CuraEngine"
__plugin_version__ = "0.1"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
__plugin_description__ = "Adds support for slicing via CuraEngine from within OctoPrint"
__plugin_license__ = "AGPLv3"
__plugin_implementations__ = [CuraPlugin()]
-2
View File
@@ -6,8 +6,6 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import s
import re
class SupportLocationTypes(object):
+1 -1
View File
@@ -100,7 +100,7 @@ $(function() {
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
$("#settings-plugin-cura-import").modal("hide");
$("#settings_plugin_cura_import").modal("hide");
self.requestData();
self.slicingViewModel.requestData();
}
+98 -107
View File
@@ -24,7 +24,10 @@ except:
__plugin_name__ = "Discovery"
__plugin_version__ = "0.1"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Discovery"
__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP"
__plugin_license__ = "AGPLv3"
def __plugin_init__():
if not pybonjour:
@@ -47,93 +50,16 @@ def __plugin_init__():
zeroconf_unregister=discovery_plugin.zeroconf_unregister
))
default_settings = {
"publicHost": None,
"publicPort": None,
"pathPrefix": None,
"httpUsername": None,
"httpPassword": None,
"upnpUuid": None,
"zeroConf": [],
"model": {
"name": None,
"description": None,
"number": None,
"url": None,
"serial": None,
"vendor": None,
"vendorUrl": None
}
}
s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings)
def get_uuid():
upnpUuid = s.get(["upnpUuid"])
if upnpUuid is None:
import uuid
upnpUuid = str(uuid.uuid4())
s.set(["upnpUuid"], upnpUuid)
s.save()
return upnpUuid
UUID = get_uuid()
del get_uuid
def get_instance_name():
name = s.globalGet(["appearance", "name"])
if name:
return u"OctoPrint instance \"{}\"".format(name)
else:
import socket
return u"OctoPrint instance on {}".format(socket.gethostname())
#~~ custom blueprint for providing discovery.xml
blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates"))
@blueprint.route("/discovery.xml")
def discovery():
logging.getLogger("octoprint.plugins." + __name__).debug("Rendering discovery.xml")
modelName = s.get(["model", "name"])
if not modelName:
import octoprint.server
modelName = octoprint.server.DISPLAY_VERSION
vendor = s.get(["model", "vendor"])
vendorUrl = s.get(["model", "vendorUrl"])
if not vendor:
vendor = "The OctoPrint Project"
vendorUrl = "http://www.octoprint.org/"
response = flask.make_response(flask.render_template("discovery.jinja2",
friendlyName=get_instance_name(),
manufacturer=vendor,
manufacturerUrl=vendorUrl,
modelName=modelName,
modelDescription=s.get(["model", "description"]),
modelNumber=s.get(["model", "number"]),
modelUrl=s.get(["model", "url"]),
serialNumber=s.get(["model", "serial"]),
uuid=UUID,
presentationUrl=flask.url_for("index", _external=True)))
response.headers['Content-Type'] = 'application/xml'
return response
class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.BlueprintPlugin):
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SettingsPlugin):
ssdp_multicast_addr = "239.255.255.250"
ssdp_multicast_port = 1900
def __init__(self):
self.logger = logging.getLogger("octoprint.plugins." + __name__)
self.host = None
self.port = None
@@ -147,10 +73,58 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
self._ssdp_notify_timeout = 10
self._ssdp_last_notify = 0
##~~ SettingsPlugin API
def get_settings_defaults(self):
return {
"publicHost": None,
"publicPort": None,
"pathPrefix": None,
"httpUsername": None,
"httpPassword": None,
"upnpUuid": None,
"zeroConf": [],
"model": {
"name": None,
"description": None,
"number": None,
"url": None,
"serial": None,
"vendor": None,
"vendorUrl": None
}
}
##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML
def get_blueprint(self):
return blueprint
@octoprint.plugin.BlueprintPlugin.route("/discovery.xml", methods=["GET"])
def discovery(self):
self._logger.debug("Rendering discovery.xml")
modelName = self._settings.get(["model", "name"])
if not modelName:
import octoprint.server
modelName = octoprint.server.DISPLAY_VERSION
vendor = self._settings.get(["model", "vendor"])
vendorUrl = self._settings.get(["model", "vendorUrl"])
if not vendor:
vendor = "The OctoPrint Project"
vendorUrl = "http://www.octoprint.org/"
response = flask.make_response(flask.render_template("discovery.xml.jinja2",
friendlyName=self.get_instance_name(),
manufacturer=vendor,
manufacturerUrl=vendorUrl,
modelName=modelName,
modelDescription=self._settings.get(["model", "description"]),
modelNumber=self._settings.get(["model", "number"]),
modelUrl=self._settings.get(["model", "url"]),
serialNumber=self._settings.get(["model", "serial"]),
uuid=self.get_uuid(),
presentationUrl=flask.url_for("index", _external=True)))
response.headers['Content-Type'] = 'application/xml'
return response
def is_blueprint_protected(self):
return False
@@ -158,10 +132,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup
def on_startup(self, host, port):
public_host = s.get(["publicHost"])
public_host = self._settings.get(["publicHost"])
if public_host:
host = public_host
public_port = s.get(["publicPort"])
public_port = self._settings.get(["publicPort"])
if public_port:
port = public_port
@@ -169,13 +143,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
self.port = port
# Zeroconf
self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict())
self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
for zeroconf in s.get(["zeroConf"]):
self.zeroconf_register("_http._tcp", self.get_instance_name(), txt_record=self._create_http_txt_record_dict())
self.zeroconf_register("_octoprint._tcp", self.get_instance_name(), txt_record=self._create_octoprint_txt_record_dict())
for zeroconf in self._settings.get(["zeroConf"]):
if "service" in zeroconf:
self.zeroconf_register(
zeroconf["service"],
zeroconf["name"] if "name" in zeroconf else get_instance_name(),
zeroconf["name"] if "name" in zeroconf else self.get_instance_name(),
port=zeroconf["port"] if "port" in zeroconf else None,
txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None
)
@@ -210,7 +184,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
return
if not name:
name = get_instance_name()
name = self.get_instance_name()
if not port:
port = self.port
@@ -224,7 +198,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
key = (reg_type, port)
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
self.logger.info(u"Registered {name} for {reg_type}".format(**locals()))
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
def zeroconf_unregister(self, reg_type, port=None):
"""
@@ -248,9 +222,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
sd_ref = self._sd_refs[key]
try:
sd_ref.close()
self.logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port))
except:
self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port))
def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5):
"""
@@ -314,7 +288,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ")
host = hosttarget[:-1]
self.logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
self._logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host))
result.append(dict(
name=name,
host=host,
@@ -330,7 +304,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
if not (flags & pybonjour.kDNSServiceFlagsAdd):
return
self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
self._logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type))
resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback)
try:
@@ -345,7 +319,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
finally:
resolve_ref.close()
self.logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type))
def browse():
sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback)
@@ -490,16 +464,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
# determine path entry
path = "/"
if s.get(["pathPrefix"]):
path = s.get(["pathPrefix"])
if self._settings.get(["pathPrefix"]):
path = self._settings.get(["pathPrefix"])
else:
prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"])
prefix = self._settings.globalGet(["server", "reverseProxy", "prefixFallback"])
if prefix:
path = prefix
# fetch username and password (if set)
username = s.get(["httpUsername"])
password = s.get(["httpPassword"])
username = self._settings.get(["httpUsername"])
password = self._settings.get(["httpPassword"])
entries = dict(
path=path
@@ -537,10 +511,10 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
api=octoprint.server.api.VERSION,
))
modelName = s.get(["model", "name"])
modelName = self._settings.get(["model", "name"])
if modelName:
entries.update(dict(model=modelName))
vendor = s.get(["model", "vendor"])
vendor = self._settings.get(["model", "vendor"])
if vendor:
entries.update(dict(vendor=vendor))
@@ -598,7 +572,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
location = "http://{addr}:{port}/plugin/discovery/discovery.xml".format(addr=addr, port=self.port)
self.logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
self._logger.debug("Sending NOTIFY {} via {}".format("alive" if alive else "byebye", addr))
notify_message = "".join([
"NOTIFY * HTTP/1.1\r\n",
"Server: Python/2.7\r\n",
@@ -609,7 +583,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
"USN: uuid:{uuid}::upnp:rootdevice\r\n",
"HOST: {mcast_addr}:{mcast_port}\r\n\r\n"
])
message = notify_message.format(uuid=UUID,
message = notify_message.format(uuid=self.get_uuid(),
location=location,
nts="ssdp:alive" if alive else "ssdp:byebye",
mcast_addr=self.__class__.ssdp_multicast_addr,
@@ -663,7 +637,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(self.__class__.ssdp_multicast_addr) + socket.inet_aton('0.0.0.0'))
self.logger.info(u"Registered {} for SSDP".format(get_instance_name()))
self._logger.info(u"Registered {} for SSDP".format(self.get_instance_name()))
self._ssdp_notify(alive=True)
@@ -675,11 +649,11 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
if not request.error_code and request.command == "M-SEARCH" and request.path == "*" and (request.headers["ST"] == "upnp:rootdevice" or request.headers["ST"] == "ssdp:all") and request.headers["MAN"] == '"ssdp:discover"':
interface_address = octoprint.util.address_for_client(*address)
if not interface_address:
self.logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
self._logger.warn("Can't determine address to user for client {}, not sending a M-SEARCH reply".format(address))
continue
message = location_message.format(uuid=UUID, location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
message = location_message.format(uuid=self.get_uuid(), location="http://{host}:{port}/plugin/discovery/discovery.xml".format(host=interface_address, port=self.port))
sock.sendto(message, address)
self.logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
self._logger.debug("Sent M-SEARCH reply for {path} and {st} to {address!r}".format(path=request.path, st=request.headers["ST"], address=address))
except socket.timeout:
pass
finally:
@@ -690,4 +664,21 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
except:
pass
##~~ helpers
def get_uuid(self):
upnpUuid = self._settings.get(["upnpUuid"])
if upnpUuid is None:
import uuid
upnpUuid = str(uuid.uuid4())
self._settings.set(["upnpUuid"], upnpUuid)
self._settings.save()
return upnpUuid
def get_instance_name(self):
name = self._settings.globalGet(["appearance", "name"])
if name:
return u"OctoPrint instance \"{}\"".format(name)
else:
import socket
return u"OctoPrint instance on {}".format(socket.gethostname())
+15
View File
@@ -213,6 +213,21 @@ class Printer():
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
def getTransport(self):
"""
Returns the communication layer's transport object, if a connection is currently established.
Note that this doesn't have to necessarily be a :class:`serial.Serial` instance, it might also be something
different, so take care to do instance checks before attempting to access any properties or methods.
:return: the communication layer's transport object
"""
if self._comm is None:
return None
return self._comm.getTransport()
def command(self, command):
"""
Sends a single gcode command to the printer.
+96 -1
View File
@@ -32,6 +32,101 @@ class BedTypes(object):
return [getattr(cls, name) for name in cls.__dict__ if not name.startswith("__")]
class PrinterProfileManager(object):
"""
Manager for printer profiles. Offers methods to select the globally used printer profile and to list, add, remove,
load and save printer profiles.
A printer profile is a ``dict`` of the following structure:
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Type
- Description
* - ``id``
- ``string``
- Internal id of the printer profile
* - ``name``
- ``string``
- Human readable name of the printer profile
* - ``model``
- ``string``
- Printer model
* - ``color``
- ``string``
- Color to associate with the printer profile
* - ``volume``
- ``dict``
- Information about the print volume
* - ``volume.width``
- ``float``
- Width of the print volume (X axis)
* - ``volume.depth``
- ``float``
- Depth of the print volume (Y axis)
* - ``volume.height``
- ``float``
- Height of the print volume (Z axis)
* - ``volume.formFactor``
- ``string``
- Form factor of the print bed, either ``rectangular`` or ``circular``
* - ``heatedBed``
- ``bool``
- Whether the printer has a heated bed (``True``) or not (``False``)
* - ``extruder``
- ``dict``
- Information about the printer's extruders
* - ``extruder.count``
- ``int``
- How many extruders the printer has (default 1)
* - ``extruder.offsets``
- ``list`` of ``tuple``s
- Extruder offsets relative to first extruder, list of (x, y) tuples, first is always (0,0)
* - ``extruder.nozzleDiameter``
- ``float``
- Diameter of the printer nozzle
* - ``axes``
- ``dict``
- Information about the printer axes
* - ``axes.x``
- ``dict``
- Information about the printer's X axis
* - ``axes.x.speed``
- ``float``
- Speed of the X axis in mm/s
* - ``axes.x.inverted``
- ``bool``
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
* - ``axes.y``
- ``dict``
- Information about the printer's Y axis
* - ``axes.y.speed``
- ``float``
- Speed of the Y axis in mm/s
* - ``axes.y.inverted``
- ``bool``
- Whether a positive value change moves the nozzle away from the print bed's origin (False, default) or towards it (True)
* - ``axes.z``
- ``dict``
- Information about the printer's Z axis
* - ``axes.z.speed``
- ``float``
- Speed of the Z axis in mm/s
* - ``axes.z.inverted``
- ``bool``
- Whether a positive value change moves the nozzle away from the print bed (False, default) or towards it (True)
* - ``axes.e``
- ``dict``
- Information about the printer's E axis
* - ``axes.e.speed``
- ``float``
- Speed of the E axis in mm/s
* - ``axes.e.inverted``
- ``bool``
- Whether a positive value change extrudes (False, default) or retracts (True) filament
"""
default = dict(
id = "_default",
@@ -229,7 +324,7 @@ class PrinterProfileManager(object):
profile = self._ensure_valid_profile(dict_merge(copy.deepcopy(self.__class__.default), default_overrides))
if not profile:
self._logger.warn("Invalid default profile after applying overrides")
raise InvalidProfileError()
return copy.deepcopy(self.__class__.default)
return profile
def _get_profile_path(self, identifier):
+137 -45
View File
@@ -89,6 +89,13 @@ LANGUAGES = get_available_locale_identifiers(LOCALES)
def before_request():
g.locale = get_locale()
@app.after_request
def after_request(response):
# send no-cache headers with all POST responses
if request.method == "POST":
response.cache_control.no_cache = True
return response
@babel.localeselector
def get_locale():
@@ -98,9 +105,15 @@ def get_locale():
@app.route("/")
@util.flask.cached(refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values)
def index():
#~~ a bunch of settings
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
enable_timelapse = (settings().get(["webcam", "snapshot"]) and settings().get(["webcam", "ffmpeg"]))
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0
enable_accesscontrol = userManager is not None
#~~ extract data from asset plugins
@@ -109,6 +122,71 @@ def index():
for name, implementation in asset_plugins.items():
asset_plugin_urls[name] = implementation.get_assets()
##~~ extract data from template plugins
templates = dict(
navbar=dict(order=[], entries=dict()),
sidebar=dict(order=[], entries=dict()),
tab=dict(order=[], entries=dict()),
settings=dict(order=[], entries=dict()),
generic=dict(order=[], entries=dict())
)
#~~ navbar
templates["navbar"]["entries"] = dict(
settings=dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin", custom_bindings=False)
)
if enable_accesscontrol:
templates["navbar"]["entries"]["login"] = dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False)
if enable_systemmenu:
templates["navbar"]["entries"]["systemmenu"] = dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False)
#~~ sidebar
templates["sidebar"]["entries"]= dict(
connection=(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")),
state=(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
files=(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], header_addon="sidebar/files_header.jinja2"))
)
#~~ tabs
templates["tab"]["entries"] = dict(
temperature=(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")),
control=(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")),
terminal=(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")),
)
if enable_gcodeviewer:
templates["tab"]["entries"]["gcodeviewer"] = (gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode"))
if enable_timelapse:
templates["tab"]["entries"]["timelapse"] = (gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
#~~ settings dialog
templates["settings"]["entries"] = dict(
section_printer=(gettext("Printer"), None),
serial=(gettext("Serial Connection"), dict(template="dialogs/settings/serialconnection.jinja2", _div="settings_serialConnection", custom_bindings=False)),
printerprofiles=(gettext("Printer Profiles"), dict(template="dialogs/settings/printerprofiles.jinja2", _div="settings_printerProfiles", custom_bindings=False)),
temperatures=(gettext("Temperatures"), dict(template="dialogs/settings/temperatures.jinja2", _div="settings_temperature", custom_bindings=False)),
terminalfilters=(gettext("Terminal Filters"), dict(template="dialogs/settings/terminalfilters.jinja2", _div="settings_terminalFilters", custom_bindings=False)),
section_features=(gettext("Features"), None),
features=(gettext("Features"), dict(template="dialogs/settings/features.jinja2", _div="settings_features", custom_bindings=False)),
webcam=(gettext("Webcam"), dict(template="dialogs/settings/webcam.jinja2", _div="settings_webcam", custom_bindings=False)),
api=(gettext("API"), dict(template="dialogs/settings/api.jinja2", _div="settings_api", custom_bindings=False)),
section_octoprint=(gettext("OctoPrint"), None),
folders=(gettext("Folders"), dict(template="dialogs/settings/folders.jinja2", _div="settings_folders", custom_bindings=False)),
appearance=(gettext("Appearance"), dict(template="dialogs/settings/appearance.jinja2", _div="settings_appearance", custom_bindings=False)),
logs=(gettext("Logs"), dict(template="dialogs/settings/logs.jinja2", _div="settings_logs")),
)
if enable_accesscontrol:
templates["settings"]["entries"]["accesscontrol"] = (gettext("Access Control"), dict(template="dialogs/settings/accesscontrol.jinja2", _div="settings_users", custom_bindings=False))
#~~ extract data from template plugins
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
@@ -123,11 +201,6 @@ def index():
)
plugin_vars = dict()
plugin_includes_navbar = []
plugin_includes_sidebar = []
plugin_includes_tabs = []
plugin_includes_settings = []
plugin_includes_generic = []
plugin_names = template_plugins.keys()
for name, implementation in template_plugins.items():
vars = implementation.get_template_vars()
@@ -143,37 +216,51 @@ def index():
includes = _process_template_configs(name, implementation, configs, rules)
plugin_includes_navbar += includes["navbar"]
plugin_includes_sidebar += includes["sidebar"]
plugin_includes_tabs += includes["tab"]
plugin_includes_settings += includes["settings"]
plugin_includes_generic += includes["generic"]
for t in ("navbar", "sidebar", "tab", "settings", "generic"):
for include in includes[t]:
if t == "navbar" or t == "generic":
data = include
else:
data = include[1]
#~~ navbar
key = "plugin_" + name + data["suffix"] if "suffix" in data else ""
if "replaces" in data:
key = data["replaces"]
templates[t]["entries"][key] = include
navbar_entries = plugin_includes_navbar + [
dict(template="navbar/settings.jinja2", _div="navbar_settings", styles=["display: none"], data_bind="visible: loginState.isAdmin", custom_bindings=False),
dict(template="navbar/systemmenu.jinja2", _div="navbar_systemmenu", styles=["display: none"], classes=["dropdown"], data_bind="visible: loginState.isAdmin", custom_bindings=False),
dict(template="navbar/login.jinja2", _div="navbar_login", classes=["dropdown"], custom_bindings=False)
#~~ order internal templates and plugins
templates["navbar"]["order"] = ["settings", "systemmenu", "login"]
templates["sidebar"]["order"] = ["connection", "state", "files"]
templates["tab"]["order"] = ["temperature", "control", "gcodeviewer", "terminal", "timelapse"]
templates["settings"]["order"] = [
"section_printer", "serial", "printerprofiles", "temperatures", "terminalfilters",
"section_features", "features", "webcam", "accesscontrol", "api",
"section_octoprint", "folders", "appearance", "logs"
]
#~~ sidebar
# make sure that
# 1) we only have keys in our ordered list that we have entries for and
# 2) we have all entries located somewhere within the order
sidebar_entries = [
(gettext("Connection"), dict(template="sidebar/connection.jinja2", _div="connection", icon="signal", styles_wrapper=["display: none"], data_bind="visible: loginState.isAdmin")),
(gettext("State"), dict(template="sidebar/state.jinja2", _div="state", icon="info-sign")),
(gettext("Files"), dict(template="sidebar/files.jinja2", _div="files", icon="list", classes_content=["overflow_visible"], header_addon="sidebar/files_header.jinja2"))
] + plugin_includes_sidebar
for t in ("navbar", "sidebar", "tab", "settings", "generic"):
templates[t]["order"] = [x for x in templates[t]["order"] if x in templates[t]["entries"]]
all_ordered = set(templates[t]["order"])
#~~ tabs
missing_in_order = set(templates[t]["entries"].keys()).difference(all_ordered)
if len(missing_in_order) == 0:
continue
tab_entries = [
(gettext("Temperature"), dict(template="tabs/temperature.jinja2", _div="temp")),
(gettext("Control"), dict(template="tabs/control.jinja2", _div="control")),
(gettext("GCode Viewer"), dict(template="tabs/gcodeviewer.jinja2", _div="gcode")),
(gettext("Terminal"), dict(template="tabs/terminal.jinja2", _div="term")),
(gettext("Timelapse"), dict(template="tabs/timelapse.jinja2", _div="timelapse"))
] + plugin_includes_tabs
sorted_missing = list(missing_in_order)
if not t == "navbar" and not t == "generic":
sorted_missing = sorted(missing_in_order, key=lambda x: templates[t]["entries"][x][0])
if t == "navbar":
templates[t]["order"] = sorted_missing + templates[t]["order"]
elif t == "sidebar" or t == "tab" or t == "generic":
templates[t]["order"] += sorted_missing
elif t == "settings":
templates[t]["entries"]["section_plugins"] = (gettext("Plugins"), None)
templates[t]["order"] += ["section_plugins"] + sorted_missing
#~~ settings dialog
@@ -202,10 +289,7 @@ def index():
render_kwargs = dict(
webcamStream=settings().get(["webcam", "stream"]),
enableTimelapse=(settings().get(["webcam", "snapshot"]) is not None and settings().get(["webcam", "ffmpeg"]) is not None),
enableGCodeVisualizer=settings().get(["gcodeViewer", "enabled"]),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
enableSystemMenu=settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None and len(settings().get(["system", "actions"])) > 0,
enableAccessControl=userManager is not None,
enableSdSupport=settings().get(["feature", "sdSupport"]),
firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()),
@@ -216,11 +300,7 @@ def index():
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
uiApiKey=UI_API_KEY,
navbarEntries=navbar_entries,
sidebarEntries=sidebar_entries,
tabEntries=tab_entries,
settingsEntries=settings_entries,
genericEntries=plugin_includes_generic,
templates=templates,
pluginNames=plugin_names,
assetPlugins=asset_plugin_urls,
)
@@ -241,7 +321,8 @@ def _process_template_configs(name, implementation, configs, rules):
navbar=1,
sidebar=1,
tab=1,
settings=1
settings=1,
generic=1
)
includes = defaultdict(list)
@@ -294,9 +375,11 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
data["_div"] = rule["div"](name)
if "suffix" in data:
data["_div"] += "_" + data["suffix"]
del data["suffix"]
elif counter > 1:
data["_div"] += "_%d" % counter
data["suffix"] = "_%d" % counter
else:
data["suffix"] = ""
if not "template" in data:
data["template"] = rule["template"](name)
if not "name" in data:
@@ -419,16 +502,24 @@ class Server():
printer = Printer(fileManager, analysisQueue, printerProfileManager)
appSessionManager = util.flask.AppSessionManager()
pluginManager.initialize_implementations(dict(
def plugin_settings_factory(name, implementation):
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return None
default_settings = implementation.get_settings_defaults()
plugin_settings = octoprint.plugin.plugin_settings(name, defaults=default_settings)
return dict(settings=plugin_settings)
pluginManager.initialize_implementations(additional_injects=dict(
plugin_manager=pluginManager,
printer_profile_manager=printerProfileManager,
event_manager=eventManager,
event_bus=eventManager,
analysis_queue=analysisQueue,
slicing_manager=slicingManager,
storage_managers=storage_managers,
file_manager=fileManager,
app_session_manager=appSessionManager,
plugin_manager=pluginManager
))
printer=printer,
app_session_manager=appSessionManager
), additional_inject_factories=[plugin_settings_factory])
slicingManager.initialize()
# configure additional template folders for jinja2
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
@@ -445,6 +536,7 @@ class Server():
])
app.jinja_loader = jinja_loader
del jinja2
app.jinja_env.add_extension("jinja2.ext.do")
# configure timelapse
octoprint.timelapse.configureTimelapse()
+3 -3
View File
@@ -210,7 +210,7 @@ def uploadGcodeFile(target):
filename = added_file
done = True
else:
filename = fileProcessingFinished(added_file, fileManager.get_absolute_path(FileDestinations.LOCAL, added_file), target)
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
done = True
sdFilename = None
@@ -293,7 +293,7 @@ def gcodeFileCommand(filename, target):
filenameToSelect = filename
sd = True
else:
filenameToSelect = fileManager.get_absolute_path(target, filename)
filenameToSelect = fileManager.path_on_disk(target, filename)
printer.selectFile(filenameToSelect, sd, printAfterLoading)
elif command == "slice":
@@ -371,7 +371,7 @@ def gcodeFileCommand(filename, target):
filenameToSelect = gcode_name
sd = True
else:
filenameToSelect = fileManager.get_absolute_path(target, gcode_name)
filenameToSelect = fileManager.path_on_disk(target, gcode_name)
printer.selectFile(filenameToSelect, sd, print_after_slicing)
ok, result = fileManager.slice(slicer, target, filename, target, gcode_name,
+5 -1
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, make_response, Response
from flask.exceptions import JSONBadRequest
import re
from octoprint.settings import settings, valid_boolean_trues
@@ -306,7 +307,10 @@ def printerCommand():
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content type JSON", 400)
data = request.json
try:
data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
parameters = dict()
if "parameters" in data.keys(): parameters = data["parameters"]
+25 -8
View File
@@ -9,6 +9,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import copy
from flask import jsonify, make_response, request, url_for
from flask.exceptions import JSONBadRequest
from octoprint.server.api import api, NO_CONTENT
from octoprint.server.util.flask import restricted_access
@@ -27,11 +28,15 @@ def printerProfilesList():
@restricted_access
def printerProfilesAdd():
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
return make_response("Expected content-type JSON", 400)
try:
json_data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
json_data = request.json
if not "profile" in json_data:
return None, None, make_response("No profile included in request", 400)
return make_response("No profile included in request", 400)
base_profile = printerProfileManager.get_default()
if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring):
@@ -43,10 +48,18 @@ def printerProfilesAdd():
del base_profile["id"]
if "name" in base_profile:
del base_profile["name"]
if "default" in base_profile:
del base_profile["default"]
profile = dict_merge(base_profile, json_data["profile"])
new_profile = json_data["profile"]
make_default = False
if "default" in new_profile:
make_default = True
del new_profile["default"]
profile = dict_merge(base_profile, new_profile)
try:
saved_profile = printerProfileManager.save(profile, allow_overwrite=False)
saved_profile = printerProfileManager.save(profile, allow_overwrite=False, make_default=make_default)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except CouldNotOverwriteError:
@@ -74,11 +87,15 @@ def printerProfilesDelete(identifier):
@restricted_access
def printerProfilesUpdate(identifier):
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
return make_response("Expected content-type JSON", 400)
try:
json_data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
json_data = request.json
if not "profile" in json_data:
make_response("No profile included in request", 400)
return make_response("No profile included in request", 400)
profile = printerProfileManager.get(identifier)
if profile is None:
+74 -68
View File
@@ -7,7 +7,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
from flask import request, jsonify
from flask import request, jsonify, make_response
from flask.exceptions import JSONBadRequest
from octoprint.events import eventManager, Events
from octoprint.settings import settings
@@ -112,91 +113,96 @@ def getSettings():
@restricted_access
@admin_permission.require(403)
def setSettings():
if "application/json" in request.headers["Content-Type"]:
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.json
s = settings()
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
s = settings()
if "api" in data.keys():
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
if "api" in data.keys():
if "enabled" in data["api"].keys(): s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "key" in data["api"].keys(): s.set(["api", "key"], data["api"]["key"], True)
if "allowCrossOrigin" in data["api"].keys(): s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
if "appearance" in data.keys():
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
if "appearance" in data.keys():
if "name" in data["appearance"].keys(): s.set(["appearance", "name"], data["appearance"]["name"])
if "color" in data["appearance"].keys(): s.set(["appearance", "color"], data["appearance"]["color"])
if "printer" in data.keys():
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
if "printer" in data.keys():
if "defaultExtrusionLength" in data["printer"]: s.setInt(["printerParameters", "defaultExtrusionLength"], data["printer"]["defaultExtrusionLength"])
if "webcam" in data.keys():
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "webcam" in data.keys():
if "streamUrl" in data["webcam"].keys(): s.set(["webcam", "stream"], data["webcam"]["streamUrl"])
if "snapshotUrl" in data["webcam"].keys(): s.set(["webcam", "snapshot"], data["webcam"]["snapshotUrl"])
if "ffmpegPath" in data["webcam"].keys(): s.set(["webcam", "ffmpeg"], data["webcam"]["ffmpegPath"])
if "bitrate" in data["webcam"].keys(): s.set(["webcam", "bitrate"], data["webcam"]["bitrate"])
if "watermark" in data["webcam"].keys(): s.setBoolean(["webcam", "watermark"], data["webcam"]["watermark"])
if "flipH" in data["webcam"].keys(): s.setBoolean(["webcam", "flipH"], data["webcam"]["flipH"])
if "flipV" in data["webcam"].keys(): s.setBoolean(["webcam", "flipV"], data["webcam"]["flipV"])
if "feature" in data.keys():
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "feature" in data.keys():
if "gcodeViewer" in data["feature"].keys(): s.setBoolean(["gcodeViewer", "enabled"], data["feature"]["gcodeViewer"])
if "temperatureGraph" in data["feature"].keys(): s.setBoolean(["feature", "temperatureGraph"], data["feature"]["temperatureGraph"])
if "waitForStart" in data["feature"].keys(): s.setBoolean(["feature", "waitForStartOnConnect"], data["feature"]["waitForStart"])
if "alwaysSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "alwaysSendChecksum"], data["feature"]["alwaysSendChecksum"])
if "sdSupport" in data["feature"].keys(): s.setBoolean(["feature", "sdSupport"], data["feature"]["sdSupport"])
if "sdAlwaysAvailable" in data["feature"].keys(): s.setBoolean(["feature", "sdAlwaysAvailable"], data["feature"]["sdAlwaysAvailable"])
if "swallowOkAfterResend" in data["feature"].keys(): s.setBoolean(["feature", "swallowOkAfterResend"], data["feature"]["swallowOkAfterResend"])
if "repetierTargetTemp" in data["feature"].keys(): s.setBoolean(["feature", "repetierTargetTemp"], data["feature"]["repetierTargetTemp"])
if "keyboardControl" in data["feature"].keys(): s.setBoolean(["feature", "keyboardControl"], data["feature"]["keyboardControl"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "serial" in data.keys():
if "autoconnect" in data["serial"].keys(): s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"].keys(): s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"].keys(): s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"].keys(): s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"].keys(): s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutTemperature" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
if oldLog and not s.getBoolean(["serial", "log"]):
# disable debug logging to serial.log
logging.getLogger("SERIAL").debug("Disabling serial logging")
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
elif not oldLog and s.getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
if oldLog and not s.getBoolean(["serial", "log"]):
# disable debug logging to serial.log
logging.getLogger("SERIAL").debug("Disabling serial logging")
logging.getLogger("SERIAL").setLevel(logging.CRITICAL)
elif not oldLog and s.getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
if "folder" in data.keys():
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
if "folder" in data.keys():
if "uploads" in data["folder"].keys(): s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"].keys(): s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"].keys(): s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"].keys(): s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"].keys(): s.setBaseFolder("watched", data["folder"]["watched"])
if "temperature" in data.keys():
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "temperature" in data.keys():
if "profiles" in data["temperature"].keys(): s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "terminalFilters" in data.keys():
s.set(["terminalFilters"], data["terminalFilters"])
if "terminalFilters" in data.keys():
s.set(["terminalFilters"], data["terminalFilters"])
if "system" in data.keys():
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
if "system" in data.keys():
if "actions" in data["system"].keys(): s.set(["system", "actions"], data["system"]["actions"])
if "events" in data["system"].keys(): s.set(["system", "events"], data["system"]["events"])
if "scripts" in data:
if "gcode" in data["scripts"]: s.set(["scripts", "gcode"], data["scripts"]["gcode"])
if "plugins" in data:
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
if name in data["plugins"]:
plugin.on_settings_save(data["plugins"][name])
if "plugins" in data:
for name, plugin in octoprint.plugin.plugin_manager().get_implementations(octoprint.plugin.SettingsPlugin).items():
if name in data["plugins"]:
plugin.on_settings_save(data["plugins"][name])
if s.save():
eventManager().fire(Events.SETTINGS_UPDATED)
if s.save():
eventManager().fire(Events.SETTINGS_UPDATED)
return getSettings()
+9 -2
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, make_response, url_for
from flask.exceptions import JSONBadRequest
from octoprint.server import slicingManager
from octoprint.server.util.flask import restricted_access
@@ -58,7 +59,10 @@ def slicingAddSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
return None, None, make_response("Expected content-type JSON", 400)
json_data = request.json
try:
json_data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
data = dict()
display_name = None
@@ -90,7 +94,10 @@ def slicingPatchSlicerProfile(slicer, name):
if not profile:
return make_response("Profile not found", 404)
json_data = request.json
try:
json_data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
data = dict()
display_name = None
+46 -26
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, abort, make_response
from flask.exceptions import JSONBadRequest
from flask.ext.login import current_user
import octoprint.users as users
@@ -35,21 +36,26 @@ def addUser():
if userManager is None:
return jsonify(SUCCESS)
if "application/json" in request.headers["Content-Type"]:
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
name = data["name"]
password = data["password"]
active = data["active"]
name = data["name"]
password = data["password"]
active = data["active"]
roles = ["user"]
if "admin" in data.keys() and data["admin"]:
roles.append("admin")
roles = ["user"]
if "admin" in data.keys() and data["admin"]:
roles.append("admin")
try:
userManager.addUser(name, password, active, roles)
except users.UserAlreadyExists:
abort(409)
try:
userManager.addUser(name, password, active, roles)
except users.UserAlreadyExists:
abort(409)
return getUsers()
@@ -78,18 +84,23 @@ def updateUser(username):
user = userManager.findUser(username)
if user is not None:
if "application/json" in request.headers["Content-Type"]:
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.json
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
# change roles
roles = ["user"]
if "admin" in data.keys() and data["admin"]:
roles.append("admin")
userManager.changeUserRoles(username, roles)
# change roles
roles = ["user"]
if "admin" in data.keys() and data["admin"]:
roles.append("admin")
userManager.changeUserRoles(username, roles)
# change activation
if "active" in data.keys():
userManager.changeUserActivation(username, data["active"])
# change activation
if "active" in data.keys():
userManager.changeUserActivation(username, data["active"])
return getUsers()
else:
abort(404)
@@ -116,13 +127,22 @@ def changePasswordForUser(username):
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
if "application/json" in request.headers["Content-Type"]:
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.json
if "password" in data.keys() and data["password"]:
try:
userManager.changeUserPassword(username, data["password"])
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
except JSONBadRequest:
return make_response("Malformed JSON body in request", 400)
if not "password" in data.keys() or not data["password"]:
return make_response("password is missing from request", 400)
try:
userManager.changeUserPassword(username, data["password"])
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify(SUCCESS)
else:
return make_response(("Forbidden", 403, []))
+42
View File
@@ -19,6 +19,48 @@ from octoprint.settings import settings
import octoprint.server
import octoprint.users
from werkzeug.contrib.cache import SimpleCache
#~~ cache decorator for cacheable views
_cache = SimpleCache()
def cached(timeout=5 * 60, key="view/%s", unless=None, refreshif=None):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
logger = logging.getLogger(__name__)
# bypass the cache if "unless" condition is true
if callable(unless) and unless():
logger.debug("Cache bypassed, calling wrapped function")
return f(*args, **kwargs)
cache_key = key % flask.request.path
# only take the value from the cache if we are not required to refresh it from the wrapped function
if not callable(refreshif) or not refreshif():
rv = _cache.get(cache_key)
if rv is not None:
logger.debug("Serving entry from cache")
return rv
# get value from wrapped function
logger.debug("No cache entry or refreshing cache, calling wrapped function")
rv = f(*args, **kwargs)
# store it in the cache
_cache.set(cache_key, rv, timeout=timeout)
return rv
return decorated_function
return decorator
def cache_check_headers():
return "no-cache" in flask.request.cache_control or "no-cache" in flask.request.pragma
#~~ access validators for use with tornado
-5
View File
@@ -131,11 +131,6 @@ default_settings = {
"localNetworks": ["127.0.0.0/8"],
"autologinAs": None
},
"cura": {
"enabled": False,
"path": "/default/path/to/cura",
"config": "/default/path/to/your/cura/config.ini"
},
"slicing": {
"enabled": True,
"defaultSlicer": "cura",
+3 -1
View File
@@ -55,11 +55,13 @@ class SlicingManager(object):
self._slicers = dict()
self._slicer_names = dict()
self._load_slicers()
self._progress_callbacks = []
self._last_progress_report = None
def initialize(self):
self._load_slicers()
def register_progress_callback(self, callback):
self._progress_callbacks.append(callback)
+1 -1
View File
@@ -1 +1 @@
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:aLine truncated
.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 12px;margin-bottom:0;font-size:14px;line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333;text-shadow:0 1px 1px rgba(255,255,255,.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);border:1px solid #ccc;*border:0;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 1px 0 rgba(255,255,255,.2),0 1px 2px rgba(0,0,0,.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05);box-shadow:inset 0 2px 4px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^=icon-],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^=icon-],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^=icon-],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#006dcc;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#04c;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25);background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.activeLine truncated
+7 -1
View File
@@ -168,11 +168,17 @@ function DataUpdater(allViewModels) {
console.log("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type == "UpdatedFiles") {
_.each(self.allViewModels, function(viewModel) {
_.each(self.allViewModels, function (viewModel) {
if (viewModel.hasOwnProperty("onUpdatedFiles")) {
viewModel.onUpdatedFiles(payload);
}
});
} else if (type == "MetadataStatisticsUpdated") {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onMetadataStatisticsUpdated")) {
viewModel.onMetadataStatisticsUpdated(payload);
}
})
} else if (type == "MetadataAnalysisFinished") {
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onMetadataAnalysisFinished")) {
+145 -74
View File
@@ -83,6 +83,7 @@ $(function() {
var navigationViewModel = new NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsViewModel, usersViewModel);
var logViewModel = new LogViewModel(loginStateViewModel);
// the view model map is our basic look up table for dependencies that may be injected into other view models
var viewModelMap = {
loginStateViewModel: loginStateViewModel,
printerProfilesViewModel: printerProfilesViewModel,
@@ -102,28 +103,87 @@ $(function() {
slicingViewModel: slicingViewModel
};
var allViewModels = _.values(viewModelMap);
var additionalViewModels = [];
_.each(ADDITIONAL_VIEWMODELS, function(viewModel) {
// helper to create a view model instance with injected constructor parameters from the view model map
var _createViewModelInstance = function(viewModel, viewModelMap){
var viewModelClass = viewModel[0];
var viewModelParameters = viewModel[1];
var viewModelBindTarget = viewModel[2];
var constructorParameters = [];
_.each(viewModelParameters, function(parameter) {
if (_.has(viewModelMap, parameter)) {
constructorParameters.push(viewModelMap[parameter]);
} else {
constructorParameters.push(undefined);
}
// now we'll try to resolve all of the view model's constructor parameters via our view model map
var constructorParameters = _.map(viewModelParameters, function(parameter){
return viewModelMap[parameter]
});
var viewModelInstance = new viewModelClass(constructorParameters);
additionalViewModels.push([viewModelInstance, viewModelBindTarget]);
allViewModels.push(viewModelInstance);
});
if (_.some(constructorParameters, function(parameter) { return parameter === undefined; })) {
var _extractName = function(entry) { return entry[0]; };
var _onlyUnresolved = function(entry) { return entry[1] === undefined; };
var missingParameters = _.map(_.filter(_.zip(viewModelParameters, constructorParameters), _onlyUnresolved), _extractName);
console.log("postponing", viewModel[0].name, "due to missing parameters:", missingParameters.join(", "));
return;
}
// if we came this far then we could resolve all constructor parameters, so let's construct that view model
return new viewModelClass(constructorParameters);
};
// helper for translating the name of a view model class into an identifier for the view model map
var _getViewModelId = function(viewModel){
var name = viewModel[0].name;
return name.substr(0, 1).toLowerCase() + name.substr(1); // FooBarViewModel => fooBarViewModel
};
// instantiation loop, will make multiple passes over the list of unprocessed view models until all
// view models have been successfully instantiated with all of their dependencies or no changes can be made
// any more which means not all view models can be instantiated due to missing dependencies
var unprocessedViewModels = ADDITIONAL_VIEWMODELS.slice();
var additionalViewModels = [];
var pass = 1;
while (unprocessedViewModels.length > 0) {
console.log("View model dependency resolution, pass #" + pass++);
var startLength = unprocessedViewModels.length;
var postponed = [];
// now try to instantiate every one of our as of yet unprocessed view model descriptors
while (unprocessedViewModels.length > 0){
var viewModel = unprocessedViewModels.shift();
var viewModelId = _getViewModelId(viewModel);
// make sure that we don't have to view models going by the same name
if (_.has(viewModelMap, viewModelId)) {
console.error("Duplicate class name while instantiating viewModel ", viewModelId);
continue;
}
var viewModelInstance = _createViewModelInstance(viewModel, viewModelMap);
// our view model couldn't yet be instantiated, so postpone it for a bit
if (viewModelInstance === undefined) {
postponed.push(viewModel);
continue;
}
// we could resolve the depdendencies and the view model is not defined yet => add it, it's now fully processed
var viewModelBindTarget = viewModel[2];
additionalViewModels.push([viewModelInstance, viewModelBindTarget]);
viewModelMap[viewModelId] = viewModelInstance;
}
// anything that's now in the postponed list has to be readded to the unprocessedViewModels
unprocessedViewModels = unprocessedViewModels.concat(postponed);
// if we still have the same amount of items in our list of unprocessed view models it means that we
// couldn't instantiate any more view models over a whole iteration, which in turn mean we can't resolve the
// dependencies of remaining ones, so log that as an error and then quit the loop
if (unprocessedViewModels.length == startLength) {
console.error("Could not instantiate the following view models due to unresolvable dependencies:");
_.each(unprocessedViewModels, function(entry) {
console.error(entry[0].name, "(missing:", _.filter(entry[1], function(id) { return !_.has(viewModelMap, id); }).join(", "), ")");
});
break;
}
}
console.log("View model dependency resolution done");
var allViewModels = _.values(viewModelMap);
var dataUpdater = new DataUpdater(allViewModels);
//~~ Temperature
@@ -415,64 +475,6 @@ $(function() {
}
};
settingsViewModel.requestData(function() {
ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
ko.applyBindings(connectionViewModel, document.getElementById("connection_wrapper"));
ko.applyBindings(printerStateViewModel, document.getElementById("state_wrapper"));
ko.applyBindings(gcodeFilesViewModel, document.getElementById("files_wrapper"));
ko.applyBindings(temperatureViewModel, document.getElementById("temp"));
ko.applyBindings(controlViewModel, document.getElementById("control"));
ko.applyBindings(terminalViewModel, document.getElementById("term"));
var gcode = document.getElementById("gcode");
if (gcode) {
gcodeViewModel.initialize();
ko.applyBindings(gcodeViewModel, gcode);
}
//ko.applyBindings(settingsViewModel, document.getElementById("settings_dialog"));
ko.applyBindings(navigationViewModel, document.getElementById("navbar"));
ko.applyBindings(appearanceViewModel, document.getElementsByTagName("head")[0]);
ko.applyBindings(printerStateViewModel, document.getElementById("drop_overlay"));
ko.applyBindings(logViewModel, document.getElementById("logs"));
var timelapseElement = document.getElementById("timelapse");
if (timelapseElement) {
ko.applyBindings(timelapseViewModel, timelapseElement);
}
ko.applyBindings(slicingViewModel, document.getElementById("slicing_configuration_dialog"));
// apply bindings and signal startup
_.each(additionalViewModels, function(additionalViewModel) {
var viewModel = additionalViewModel[0];
var targets = additionalViewModel[1];
if (targets === undefined) {
return;
}
if (!Array.isArray(targets)) {
targets = [targets];
}
if (viewModel.hasOwnProperty("onBeforeBinding")) {
viewModel.onBeforeBinding();
}
_.each(targets, function(target) {
try {
ko.applyBindings(viewModel, target);
} catch (exc) {
console.log("Could not apply bindings for additional view model " + viewModel + ": " + exc.message);
}
});
if (viewModel.hasOwnProperty("onAfterBinding")) {
viewModel.onAfterBinding();
}
});
});
//~~ startup commands
_.each(allViewModels, function(viewModel) {
@@ -493,6 +495,75 @@ $(function() {
}
});
//~~ view model binding
settingsViewModel.requestData(function() {
var viewModelsToInit = additionalViewModels.concat([
[settingsViewModel, document.getElementById("settings_dialog")],
[connectionViewModel, document.getElementById("connection_wrapper")],
[printerStateViewModel, document.getElementById("state_wrapper")],
[gcodeFilesViewModel, document.getElementById("files_wrapper")],
[temperatureViewModel, document.getElementById("temp")],
[controlViewModel, document.getElementById("control")],
[gcodeViewModel, document.getElementById("gcode")],
[terminalViewModel, document.getElementById("term")],
[navigationViewModel, document.getElementById("navbar")],
[appearanceViewModel, document.getElementsByTagName("head")[0]],
[printerStateViewModel, document.getElementById("drop_overlay")],
[logViewModel, document.getElementById("logs")],
[timelapseViewModel, document.getElementById("timelapse")],
[slicingViewModel, document.getElementById("slicing_configuration_dialog")]
]);
// apply bindings
var rerenderControls = false;
_.each(viewModelsToInit, function(viewModelData) {
if (!Array.isArray(viewModelData) || viewModelData.length != 2) {
return;
}
var viewModel = viewModelData[0];
var targets = viewModelData[1];
if (targets === undefined) {
return;
}
if (!Array.isArray(targets)) {
targets = [targets];
}
if (viewModel.hasOwnProperty("onBeforeBinding")) {
viewModel.onBeforeBinding();
}
_.each(targets, function(target) {
if (target) {
try {
ko.applyBindings(viewModel, target);
} catch (exc) {
console.log("Could not apply bindings for additional view model " + viewModel + ": " + exc.message);
}
} else {
console.log("Could not apply binding for view model " + viewModel + ", target does not exist");
}
});
if (viewModel.hasOwnProperty("onAfterBinding")) {
viewModel.onAfterBinding();
}
if (viewModel.hasOwnProperty("getAdditionalControls")) {
controlViewModel.additionalControls = controlViewModel.additionalControls.concat(viewModel.getAdditionalControls());
rerenderControls = true
}
});
if (rerenderControls) {
controlViewModel.rerenderControls();
}
});
//~~ UI stuff
var webcamDisableTimeout;
@@ -26,6 +26,9 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.feedbackControlLookup = {};
self.controlsFromServer = [];
self.additionalControls = [];
self.keycontrolActive = ko.observable(false);
self.keycontrolHelpActive = ko.observable(false);
self.keycontrolPossible = ko.computed(function() {
@@ -84,6 +87,11 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
}
};
self.rerenderControls = function() {
var allControls = self.controlsFromServer.concat(self.additionalControls);
self.controls(self._processControls(allControls))
};
self.requestData = function() {
$.ajax({
url: API_BASEURL + "printer/command/custom",
@@ -96,7 +104,8 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
};
self._fromResponse = function(response) {
self.controls(self._processControls(response.controls));
self.controlsFromServer = response.controls;
self.rerenderControls();
};
self._processControls = function(controls) {
@@ -117,9 +126,49 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
} else if (control.type == "section") {
control.children = self._processControls(control.children);
}
var js;
if (control.hasOwnProperty("javascript")) {
js = control.javascript;
// if js is a function everything's fine already, but if it's a string we need to eval that first
if (!_.isFunction(js)) {
control.javascript = function(data) {
eval(js);
};
}
}
if (control.hasOwnProperty("enabled")) {
js = control.enabled;
// if js is a function everything's fine already, but if it's a string we need to eval that first
if (!_.isFunction(js)) {
control.enabled = function(data) {
return eval(js);
}
}
}
return control;
};
self.isCustomEnabled = function(data) {
if (data.hasOwnProperty("enabled")) {
return data.enabled(data);
} else {
return self.isOperational() && self.loginState.isUser();
}
};
self.clickCustom = function(data) {
if (data.hasOwnProperty("javascript")) {
data.javascript(data);
} else {
self.sendCustomCommand(data);
}
};
self.sendJogCommand = function(axis, multiplier, distance) {
if (typeof distance === "undefined")
distance = $('#jog_distance button.active').data('distance');
@@ -185,17 +234,17 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
self.sendSelectToolCommand = function(data) {
if (!data || !data.key()) return;
var data = {
var payload = {
command: "select",
tool: data.key()
}
};
$.ajax({
url: API_BASEURL + "printer/tool",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
data: JSON.stringify(payload)
});
};
@@ -211,7 +260,7 @@ function ControlViewModel(loginStateViewModel, settingsViewModel) {
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(data)
})
}
};
var data = undefined;
if (command.type == "command" || command.type == "parametric_command" || command.type == "feedback_command") {
// single command
@@ -67,7 +67,7 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicing
}
},
"name",
["machinecode"],
[],
[["sd", "local"], ["machinecode", "model"]],
0
);
@@ -337,5 +337,9 @@ function GcodeFilesViewModel(printerStateViewModel, loginStateViewModel, slicing
self.onMetadataAnalysisFinished = function(payload) {
self.requestData();
};
self.onMetadataStatisticsUpdated = function(payload) {
self.requestData();
};
}
+32 -22
View File
@@ -244,31 +244,37 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
};
self._configureLayerSlider = function() {
self.layerSlider = $("#gcode_slider_layers").slider({
id: "gcode_layer_slider",
reversed: true,
selection: "after",
orientation: "vertical",
min: 0,
max: 1,
step: 1,
value: 0,
enabled: false,
formatter: function(value) { return "Layer #" + (value + 1); }
}).on("slide", self.changeLayer);
var layerSliderElement = $("#gcode_slider_layers");
if (layerSliderElement) {
self.layerSlider = layerSliderElement.slider({
id: "gcode_layer_slider",
reversed: true,
selection: "after",
orientation: "vertical",
min: 0,
max: 1,
step: 1,
value: 0,
enabled: false,
formatter: function(value) { return "Layer #" + (value + 1); }
}).on("slide", self.changeLayer);
}
};
self._configureLayerCommandSlider = function() {
self.layerCommandSlider = $("#gcode_slider_commands").slider({
id: "gcode_command_slider",
orientation: "horizontal",
min: 0,
max: 1,
step: 1,
value: [0, 1],
enabled: false,
tooltip: "hide"
}).on("slide", self.changeCommandRange);
var commandSliderElement = $("#gcode_slider_commands");
if (commandSliderElement) {
self.layerCommandSlider = commandSliderElement.slider({
id: "gcode_command_slider",
orientation: "horizontal",
min: 0,
max: 1,
step: 1,
value: [0, 1],
enabled: false,
tooltip: "hide"
}).on("slide", self.changeCommandRange);
}
};
self.loadFile = function(filename, date){
@@ -469,6 +475,10 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) {
self.onDataUpdaterReconnect = function() {
self.reset();
};
self.onBeforeBinding = function() {
self.initialize();
}
}
@@ -3,6 +3,7 @@ function NavigationViewModel(loginStateViewModel, appearanceViewModel, settingsV
self.loginState = loginStateViewModel;
self.appearance = appearanceViewModel;
self.settings = settingsViewModel;
self.systemActions = settingsViewModel.system_actions;
self.users = usersViewModel;
@@ -44,7 +44,7 @@ function PrinterProfilesViewModel() {
"name",
[],
[],
5
10
);
self.defaultProfile = ko.observable();
self.currentProfile = ko.observable();
+25 -56
View File
@@ -46,6 +46,25 @@ body {
}
}
.nowrap {
white-space: nowrap;
}
.actioncol {
text-align: center;
.nowrap;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
.navbar-inner-color (@base) {
@top: lighten(@base, 25%);
@bottom: darken(@base, 15%);
@@ -203,23 +222,13 @@ table {
// gcode files
&.gcode_files_name {
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
.nowrap;
}
&.gcode_files_action {
text-align: center;
width: 90px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
.actioncol;
}
// timelapse files
@@ -234,18 +243,8 @@ table {
}
&.timelapse_files_action {
text-align: center;
width: 45px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
.actioncol;
}
// user settings
@@ -260,18 +259,8 @@ table {
}
&.settings_users_actions {
text-align: center;
width: 60px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
.actioncol;
}
// log files
@@ -291,18 +280,8 @@ table {
}
&.settings_logs_action {
text-align: center;
width: 70px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
.actioncol;
}
// Printer profiles
@@ -317,18 +296,8 @@ table {
}
&.settings_printerProfiles_profiles_action {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
.actioncol;
}
}
@@ -6,15 +6,16 @@
<div class="modal-body">
<div class="tabbable">
<ul class="nav nav-list span4" id="settingsTabs">
{% set active_set = false %}
{% for entry, data in settingsEntries %}
{% set mark_active = True %}
{% for key in templates.settings.order %}
{% set entry, data = templates.settings.entries[key] %}
{% if data is none %}
<li class="nav-header">{{ entry }}</li>
{% else %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<li id="{{ data._div }}_link"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
class="{% if not active_set %}active{% set active_set = true %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
class="{% if mark_active %}active{% set mark_active = False %}{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_link" in data %} style="{{ data.styles_link|join(', ') }}" {% elif "styles" in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
<a href="#{{ data._div }}" data-toggle="tab">{{ entry }}</a>
@@ -25,13 +26,14 @@
</ul>
<div class="tab-content span8">
{% set active_set = false %}
{% for entry, data in settingsEntries %}
{% set mark_active = True %}
{% for key in templates.settings.order %}
{% set entry, data = templates.settings.entries[key] %}
{% if data is not none %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<div id="{{ data._div }}"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
class="tab-pane {% if not active_set %}active{% set active_set = true %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
class="tab-pane {% if mark_active %}active{% set mark_active = False %}{% endif %} {% if classes_content in data %}{{ data.classes_content|join(' ') }}{% elif classes in data %}{{ data.classes|join(' ') }}{% endif %}"
{% if "styles_content" in data %} style="{{ data.styles_content|join(', ') }}" {% elif styles in data %} style="{{ data.styles|join(', ') }}" {% endif %}
>
{% include data.template ignore missing %}
@@ -1,4 +1,3 @@
{% if enableAccessControl %}
<table class="table table-condensed table-hover" id="system_users">
<thead>
<tr>
@@ -161,4 +160,3 @@
<button class="btn btn-primary" data-bind="click: function() { $root.users.confirmChangePassword(); }, enable: !$root.users.editorPasswordMismatch()">{{ _('Confirm') }}</button>
</div>
</div>
{% endif %}
@@ -18,6 +18,19 @@
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: printerProfiles.profiles.currentPage() === 0}"><a href="#" data-bind="click: printerProfiles.profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: printerProfiles.profiles.pages">
<li data-bind="css: { active: $data.number === $root.printerProfiles.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.printerProfiles.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: printerProfiles.profiles.currentPage() === printerProfiles.profiles.lastPage()}"><a href="#" data-bind="click: printerProfiles.profiles.nextPage">»</a></li>
</ul>
</div>
<button class="btn pull-right" data-bind="click: function() { $root.printerProfiles.showEditProfileDialog(); }">{{ _('Add Profile...') }}</button>
<div id="settings_printerProfiles_editDialog" class="modal hide fade">
@@ -1,24 +1,24 @@
<form class="form-horizontal">
<div class="control-group">
<div class="control-group" title="{{ _('Serial port to connect to, setting this to AUTO will make OctoPrint try to automatically find the right setting') }}">
<label class="control-label" for="settings-serialPort">{{ _('Serial Port') }}</label>
<div class="controls">
<select id="settings-serialPort" data-bind="options: serial_portOptions, optionsCaption: 'AUTO', value: serial_port"></select>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Serial baud rate to connect with, setting this to AUTO will make OctoPrint try to automatically find the right setting') }}">
<label class="control-label" for="settings-baudrate">{{ _('Baudrate') }}</label>
<div class="controls">
<select id="settings-baudrate" data-bind="options: serial_baudrateOptions, optionsCaption: 'AUTO', value: serial_baudrate"></select>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Makes OctoPrint try to connect to the printer automatically during start up') }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: serial_autoconnect" id="settings-serialAutoconnect"> {{ _('Auto-connect to printer on server start') }}
</label>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Time after which the communication with your printer will be considered timed out if nothing was sent by your printer (and an attempt to get it talking again will be done). Increase this if your printer takes longer than this for some moves. This is also the interval in which the temperature will be polled from the printer while not printing.') }}">
<label class="control-label" for="settings-serialTimeoutCommunication">{{ _('Communication timeout') }}</label>
<div class="controls">
<div class="input-append">
@@ -27,8 +27,8 @@
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-movementSpeedE">{{ _('Temperature timeout') }}</label>
<div class="control-group" title="{{ _('Interval in which to poll for the temperature information from the printer while printing') }}">
<label class="control-label" for="settings-serialTimeoutTemperature">{{ _('Temperature timeout') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" step="any" min="0" class="input-mini text-right" data-bind="value: serial_timeoutTemperature" id="settings-serialTimeoutTemperature">
@@ -36,7 +36,7 @@
</div>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Interval in which to poll for the SD printing status information from the printer while printing') }}">
<label class="control-label" for="settings-serialTimeoutSdStatus">{{ _('SD status timeout') }}</label>
<div class="controls">
<div class="input-append">
@@ -45,7 +45,7 @@
</div>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Time after which a connection attempt to the printer will be considered as having failed') }}">
<label class="control-label" for="settings-serialTimeoutConnection">{{ _('Connection timeout') }}</label>
<div class="controls">
<div class="input-append">
@@ -54,7 +54,7 @@
</div>
</div>
</div>
<div class="control-group">
<div class="control-group" title="{{ _('Time after which to consider an auto detection attempt to have failed if no successful connection is detected') }}">
<label class="control-label" for="settings-serialTimeoutDetection">{{ _('Autodetection timeout') }}</label>
<div class="controls">
<div class="input-append">
+10 -5
View File
@@ -18,7 +18,8 @@
<div class="nav-collapse">
<!-- Navbar -->
<ul class="nav pull-right">
{% for data in navbarEntries %}
{% for key in templates.navbar.order %}
{% set data = templates.navbar.entries[key] %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<li id="{{ data._div }}"
{% if "data_bind" in data %}data-bind="{{ data.data_bind }}"{% endif %}
@@ -38,7 +39,8 @@
<div class="row">
<!-- Sidebar -->
<div class="accordion span4">
{% for entry, data in sidebarEntries %}
{% for key in templates.sidebar.order %}
{% set entry, data = templates.sidebar.entries[key] %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<div id="{{ data._div }}_wrapper"
class="accordion-group {% if "classes_wrapper" in data %}{{ data.classes_wrapper|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
@@ -69,7 +71,8 @@
<!-- Tabs -->
<div class="span8 tabbable">
<ul class="nav nav-tabs" id="tabs">
{% for entry, data in tabEntries %}
{% for key in templates.tab.order %}
{% set entry, data = templates.tab.entries[key] %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<li id="{{ data._div }}_link"
class="{% if loop.first %}active{% endif %} {% if "classes_link" in data %}{{ data.classes_link|join(' ') }}{% elif "classes" in data %}{{ data.classes|join(' ') }}{% endif %}"
@@ -83,7 +86,8 @@
</ul>
<div class="tab-content">
{% for entry, data in tabEntries %}
{% for key in templates.tab.order %}
{% set entry, data = templates.tab.entries[key] %}
{% if "custom_bindings" not in data or data["custom_bindings"] %}<!-- ko allowBindings: false -->{% endif %}
<div id="{{ data._div }}"
class="tab-pane{% if loop.first %} active{% endif %}{% if "additional_classes" in data %} {{ data.additional_classes|join(' ') }}{% endif %}"
@@ -123,7 +127,8 @@
<!-- End of overlays -->
<!-- Generic plugin template files -->
{% for data in genericEntries %}
{% for key in templates.generic.order %}
{% set data = templates.generic.entries[key] %}
{% include data.template ignore missing %}
{% endfor %}
<!-- End of generic plugin template files -->
@@ -1,4 +1,3 @@
{% if enableAccessControl %}
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-user"></i> <span data-bind="text: loginState.userMenuText">{{ _('Login') }}</span>
<b class="caret"></b>
@@ -17,4 +16,3 @@
<li><a href="#" id="change_password_button" data-bind="click: function() { users.showChangePasswordDialog(loginState.currentUser()); }">{{ _('Change Password') }}</a></li>
<li><a href="#" id="logout_button" data-bind="click: loginState.logout">{{ _('Logout') }}</a></li>
</ul>
{% endif %}
@@ -1,4 +1,3 @@
{% if enableSystemMenu %}
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-off"></i> {{ _('System') }}
<b class="caret"></b>
@@ -6,4 +5,3 @@
<ul class="dropdown-menu" data-bind="foreach: systemActions">
<li><a href="#" data-bind="click: $root.triggerAction, text: name"></a></li>
</ul>
{% endif %}
@@ -14,6 +14,10 @@
{% for asset in assets["less"] %}
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet/less" type="text/css" media="screen">
{% endfor %}
{% elif "css" in assets %}
{% for asset in assets["css"] %}
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet" type="text/css" media="screen">
{% endfor %}
{% endif %}
{% endfor %}
<!-- /Plugin files -->
@@ -22,13 +26,22 @@
{% else %}
<link href="{{ url_for('static', filename='css/octoprint.css') }}" rel="stylesheet" type="text/css" media="screen">
<!-- Plugin files -->
{% set lessneeded=[] %}
{% for name, assets in assetPlugins.items() %}
{% if "css" in assets %}
{% for asset in assets["css"] %}
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet" type="text/css" media="screen">
{% endfor %}
{% elif "less" in assets %}
{% do lessneeded.append(1) %}
{% for asset in assets["less"] %}
<link href="{{ url_for('plugin_assets', name=name, filename=asset) }}" rel="stylesheet/less" type="text/css" media="screen">
{% endfor %}
{% endif %}
{% endfor %}
{% if lessneeded %}
<script src="{{ url_for('static', filename='js/lib/less.min.js') }}" type="text/javascript"></script>
{% endif %}
<!-- /Plugin files -->
{% endif %}
+3 -3
View File
@@ -105,12 +105,12 @@
</script>
<script type="text/html" id="customControls_commandTemplate">
<form class="form-inline">
<button class="btn" data-bind="text: name, enable: $root.isOperational() && $root.loginState.isUser(), click: function() { $root.sendCustomCommand($data) }"></button>
<button class="btn" data-bind="text: name, enable: $root.isCustomEnabled($data), click: function() { $root.clickCustom($data) }"></button>
</form>
</script>
<script type="text/html" id="customControls_feedbackCommandTemplate">
<form class="form-inline">
<button class="btn" data-bind="text: name, enable: $root.isOperational() && $root.loginState.isUser(), click: function() { $root.sendCustomCommand($data) }"></button> <span data-bind="text: output"></span>
<button class="btn" data-bind="text: name, enable: $root.isCustomEnabled($data), click: function() { $root.clickCustom($data) }"></button> <span data-bind="text: output"></span>
</form>
</script>
<script type="text/html" id="customControls_feedbackTemplate">
@@ -124,7 +124,7 @@
<label data-bind="text: name"></label>
<input type="text" class="input-small" data-bind="attr: {placeholder: name}, value: value">
<!-- /ko -->
<button class="btn" data-bind="text: name, enable: $root.isOperational() && $root.loginState.isUser(), click: function() { $root.sendCustomCommand($data) }"></button>
<button class="btn" data-bind="text: name, enable: $root.isCustomEnabled($data), click: function() { $root.clickCustom($data) }"></button>
</form>
</script>
<script type="text/html" id="customControls_emptyTemplate"><div></div></script>
@@ -1,4 +1,3 @@
{% if enableGCodeVisualizer %}
<div data-bind="visible: !waitForApproval()">
<input id="gcode_slider_layers" type="text">
<canvas id="gcode_canvas" width="568" height="568"></canvas>
@@ -74,4 +73,3 @@
Yes, please visualize <span data-bind="text: selectedFile.name"></span> regardless of its size
</button>
</div>
{% endif %}
+58 -60
View File
@@ -1,69 +1,67 @@
{% if enableTimelapse %}
<div style="display: none;" data-bind="visible: loginState.isUser">
<h1>{{ _('Timelapse Configuration') }}</h1>
<div style="display: none;" data-bind="visible: loginState.isUser">
<h1>{{ _('Timelapse Configuration') }}</h1>
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
<option value="off">{{ _('Off') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
<option value="timed">{{ _('Timed') }}</option>
</select>
<label for="webcam_timelapse_mode">{{ _('Timelapse Mode') }}</label>
<select id="webcam_timelapse_mode" data-bind="value: timelapseType, enable: isOperational() && !isPrinting() && loginState.isUser()">
<option value="off">{{ _('Off') }}</option>
<option value="zchange">{{ _('On Z Change') }}</option>
<option value="timed">{{ _('Timed') }}</option>
</select>
<label for="webcam_timelapse_postRoll">{{ _('Timelapse post roll (in rendered seconds)') }}</label>
<label for="webcam_timelapse_postRoll">{{ _('Timelapse post roll (in rendered seconds)') }}</label>
<div class="input-append">
<input type="text" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
<label for="webcam_timelapse_interval">{{ _('Interval') }}</label>
<div class="input-append">
<input type="text" class="input-mini" id="webcam_timelapse_postRoll" data-bind="value: timelapsePostRoll, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser() && timelapseTypeSelected()">
<input type="text" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()">
<span class="add-on">{{ _('sec') }}</span>
</div>
<div id="webcam_timelapse_timedsettings" data-bind="visible: intervalInputEnabled">
<label for="webcam_timelapse_interval">{{ _('Interval') }}</label>
<div class="input-append">
<input type="text" class="input-mini" id="webcam_timelapse_interval" data-bind="value: timelapseTimedInterval, valueUpdate: 'afterkeydown', enable: isOperational() && !isPrinting() && loginState.isUser()">
<span class="add-on">{{ _('sec') }}</span>
</div>
</div>
<div data-bind="visible: loginState.isAdmin">
<label class="checkbox">
<input type="checkbox" data-bind="checked: persist"> {{ _('Save as default') }}
</label>
</div>
<div>
<button class="btn" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save config') }}</button>
</div>
</div>
<h1>{{ _('Finished Timelapses') }}</h1>
<div data-bind="visible: loginState.isAdmin">
<label class="checkbox">
<input type="checkbox" data-bind="checked: persist"> {{ _('Save as default') }}
</label>
</div>
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('creation'); }">{{ _('Creation date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a></small>
<div>
<button class="btn" data-bind="click: save, enable: saveButtonEnabled">{{ _('Save config') }}</button>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_files">
<thead>
<tr>
<th class="timelapse_files_name">{{ _('Name') }}</th>
<th class="timelapse_files_size">{{ _('Size') }}</th>
<th class="timelapse_files_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="timelapse_files_name" data-bind="text: name"></td>
<td class="timelapse_files_size" data-bind="text: size"></td>
<td class="timelapse_files_action"><a href="#" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="#" class="icon-download" data-bind="attr: {href: url}"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === 0}"><a href="#" data-bind="click: listHelper.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: listHelper.pages">
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}"><a href="#" data-bind="click: listHelper.nextPage">»</a></li>
</ul>
</div>
{% endif %}
</div>
<h1>{{ _('Finished Timelapses') }}</h1>
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { listHelper.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('creation'); }">{{ _('Creation date') }} ({{ _('descending') }})</a> | <a href="#" data-bind="click: function() { listHelper.changeSorting('size'); }">{{ _('Size') }} ({{ _('descending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_files">
<thead>
<tr>
<th class="timelapse_files_name">{{ _('Name') }}</th>
<th class="timelapse_files_size">{{ _('Size') }}</th>
<th class="timelapse_files_action">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: listHelper.paginatedItems">
<tr data-bind="attr: {title: name}">
<td class="timelapse_files_name" data-bind="text: name"></td>
<td class="timelapse_files_size" data-bind="text: size"></td>
<td class="timelapse_files_action"><a href="#" class="icon-trash" data-bind="click: function() { if ($root.loginState.isUser()) { $parent.removeFile($data.name); } else { return; } }, css: {disabled: !$root.loginState.isUser()}"></a>&nbsp;|&nbsp;<a href="#" class="icon-download" data-bind="attr: {href: url}"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === 0}"><a href="#" data-bind="click: listHelper.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: listHelper.pages">
<li data-bind="css: { active: $data.number === $root.listHelper.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.listHelper.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}"><a href="#" data-bind="click: listHelper.nextPage">»</a></li>
</ul>
</div>
+10 -9
View File
@@ -262,18 +262,13 @@ class MachineCom(object):
if self._state == self.STATE_CLOSED:
return "Closed"
if self._state == self.STATE_ERROR:
return "Error: %s" % (self.getShortErrorString())
return "Error: %s" % (self.getErrorString())
if self._state == self.STATE_CLOSED_WITH_ERROR:
return "Error: %s" % (self.getShortErrorString())
return "Error: %s" % (self.getErrorString())
if self._state == self.STATE_TRANSFERING_FILE:
return "Transfering file to SD"
return "?%d?" % (self._state)
def getShortErrorString(self):
if len(self._errorValue) < 20:
return self._errorValue
return self._errorValue[:20] + "..."
def getErrorString(self):
return self._errorValue
@@ -345,6 +340,9 @@ class MachineCom(object):
def getConnection(self):
return self._port, self._baudrate
def getTransport(self):
return self._serial
##~~ external interface
def close(self, isError = False):
@@ -1042,9 +1040,12 @@ class MachineCom(object):
try:
self._log("Connecting to: %s" % self._port)
if self._baudrate == 0:
self._serial = serial.Serial(str(self._port), 115200, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000)
self._serial = serial.Serial(str(self._port), 115200, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000, parity=serial.PARITY_ODD)
else:
self._serial = serial.Serial(str(self._port), self._baudrate, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000)
self._serial = serial.Serial(str(self._port), self._baudrate, timeout=settings().getFloat(["serial", "timeout", "connection"]), writeTimeout=10000, parity=serial.PARITY_ODD)
self._serial.close()
self._serial.parity = serial.PARITY_NONE
self._serial.open()
except:
self._log("Unexpected error while connecting to serial port: %s %s" % (self._port, getExceptionString()))
self._errorValue = "Failed to open serial port, permissions correct?"
+5 -2
View File
@@ -262,13 +262,16 @@ def getCodeInt(line, code):
def getCodeFloat(line, code):
import math
n = line.find(code) + 1
if n < 1:
return None
m = line.find(' ', n)
try:
if m < 0:
return float(line[n:])
return float(line[n:m])
val = float(line[n:])
else:
val = float(line[n:m])
return val if not (math.isnan(val) or math.isinf(val)) else None
except:
return None
+74
View File
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import unittest
import os
from ddt import ddt, unpack, data
import octoprint.filemanager.storage
@@ -33,6 +35,7 @@ FILE_BP_CASE_STL = FileWrapper("bp_case.stl")
FILE_BP_CASE_GCODE = FileWrapper("bp_case.gcode")
FILE_CRAZYRADIO_STL = FileWrapper("crazyradio.stl")
@ddt
class LocalStorageTest(unittest.TestCase):
def setUp(self):
@@ -286,6 +289,77 @@ class LocalStorageTest(unittest.TestCase):
self.assertEquals(0, len(gcode_metadata["links"]))
self.assertEquals(1, len(stl_metadata["links"]))
@data(
("some_file.gco", "some_file.gco"),
("some_file with (parentheses) and ümläuts and digits 123.gco", "some_file_with_(parentheses)_and_mluts_and_digits_123.gco"),
("pengüino pequeño.stl", "pengino_pequeo.stl")
)
@unpack
def test_sanitize_name(self, input, expected):
actual = self.storage.sanitize_name(input)
self.assertEquals(expected, actual)
@data(
"some/folder/still/left.gco",
"also\\no\\backslashes.gco"
)
def test_sanitize_name_invalid(self, input):
try:
self.storage.sanitize_name(input)
self.fail("expected a ValueError")
except ValueError as e:
self.assertEquals("name must not contain / or \\", e.message)
@data(
("folder/with/subfolder", "/folder/with/subfolder"),
("folder/with/subfolder/../other/folder", "/folder/with/other/folder"),
("/folder/with/leading/slash", "/folder/with/leading/slash"),
("folder/with/leading/dot", "/folder/with/leading/dot")
)
@unpack
def test_sanitize_path(self, input, expected):
actual = self.storage.sanitize_path(input)
self.assertTrue(actual.startswith(self.basefolder))
self.assertEquals(expected, actual[len(self.basefolder):].replace(os.path.sep, "/"))
@data(
"../../folder/out/of/the/basefolder",
"some/folder/../../../and/then/back"
)
def test_sanitize_path_invalid(self, input):
try:
self.storage.sanitize_path(input)
self.fail("expected a ValueError")
except ValueError as e:
self.assertTrue(e.message.startswith("path not contained in base folder: "))
@data(
("some/folder/and/some file.gco", "/some/folder/and", "some_file.gco"),
(("some", "folder", "and", "some file.gco"), "/some/folder/and", "some_file.gco"),
("some file.gco", "/", "some_file.gco"),
(("some file.gco",), "/", "some_file.gco"),
("", "/", ""),
("some/folder/with/trailing/slash/", "/some/folder/with/trailing/slash", ""),
(("some", "folder", ""), "/some/folder", "")
)
@unpack
def test_sanitize(self, input, expected_path, expected_name):
actual = self.storage.sanitize(input)
self.assertTrue(isinstance(actual, tuple))
self.assertEquals(2, len(actual))
actual_path, actual_name = actual
self.assertTrue(actual_path.startswith(self.basefolder))
actual_path = actual_path[len(self.basefolder):].replace(os.path.sep, "/")
if not actual_path.startswith("/"):
# if the actual path originally was just the base folder, we just stripped
# away everything, so let's add a / again so the behaviour matches the
# other preprocessing of our test data here
actual_path = "/" + actual_path
self.assertEquals(expected_path, actual_path)
self.assertEquals(expected_name, actual_name)
def _add_file(self, path, expected_path, file_object, links=None, overwrite=False):
sanitized_path = self.storage.add_file(path, file_object, links=links, allow_overwrite=overwrite)
split_path = sanitized_path.split("/")
+84 -2
View File
@@ -1,4 +1,5 @@
import unittest
import mock
import octoprint.plugin
import octoprint.plugin.core
@@ -13,14 +14,17 @@ class PluginTestCase(unittest.TestCase):
# TODO mock pkg_resources to return some defined entry_points
import os
plugin_folders = [os.path.join(os.path.dirname(os.path.realpath(__file__)), "_plugins")]
self.plugin_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "_plugins")
plugin_folders = [self.plugin_folder]
plugin_types = [octoprint.plugin.SettingsPlugin, octoprint.plugin.StartupPlugin]
plugin_entry_points = None
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=[])
self.plugin_manager = octoprint.plugin.core.PluginManager(plugin_folders, plugin_types, plugin_entry_points, plugin_disabled_list=[], logging_prefix="logging_prefix.")
def test_plugin_loading(self):
self.assertEquals(4, len(self.plugin_manager.plugins))
self.assertEquals(1, len(self.plugin_manager.plugin_hooks))
self.assertEquals(3, len(self.plugin_manager.plugin_implementations))
self.assertEquals(2, len(self.plugin_manager.plugin_implementations_by_type))
self.assertTrue("octoprint.core.startup" in self.plugin_manager.plugin_hooks)
@@ -32,6 +36,55 @@ class PluginTestCase(unittest.TestCase):
self.assertTrue(octoprint.plugin.SettingsPlugin in self.plugin_manager.plugin_implementations_by_type)
self.assertEquals(2, len(self.plugin_manager.plugin_implementations_by_type[octoprint.plugin.SettingsPlugin]))
def test_plugin_initializing(self):
def test_factory(name, implementation):
return dict(test_factory="test_factory_%s" % name)
def verify_injection_order(name, implementation):
self.assertTrue(hasattr(implementation, "_basefolder"))
return dict()
additional_injects = dict(
additional_inject="additional_inject"
)
additional_inject_factories = [test_factory, verify_injection_order]
self.plugin_manager.initialize_implementations(
additional_injects=additional_injects,
additional_inject_factories=additional_inject_factories
)
all_implementations = self.plugin_manager.plugin_implementations
self.assertEquals(3, len(all_implementations))
for name, implementations in all_implementations.items():
self.assertEquals(1, len(implementations))
impl = implementations.pop()
self.assertTrue(name in self.plugin_manager.plugins)
plugin = self.plugin_manager.plugins[name]
# test that the standard fields were properly initialized
self.assertTrue(hasattr(impl, "_identifier"))
self.assertEquals(name, impl._identifier)
self.assertTrue(hasattr(impl, "_plugin_name"))
self.assertEquals(plugin.name, impl._plugin_name)
self.assertTrue(hasattr(impl, "_plugin_version"))
self.assertEquals(plugin.version, impl._plugin_version)
self.assertTrue(hasattr(impl, "_logger"))
self.assertIsNotNone(impl._logger)
self.assertEquals("logging_prefix.%s" % name, impl._logger.name)
self.assertTrue(hasattr(impl, "_basefolder"))
self.assertTrue(impl._basefolder.startswith(self.plugin_folder))
# test that the additional injects were properly injected
self.assertTrue(hasattr(impl, "_additional_inject"))
self.assertEquals("additional_inject", impl._additional_inject)
# test that the injection factory was properly executed and the result injected
self.assertTrue(hasattr(impl, "_test_factory"))
self.assertEquals("test_factory_%s" % name, impl._test_factory)
def test_get_plugin(self):
plugin = self.plugin_manager.get_plugin("hook_plugin")
self.assertIsNotNone(plugin)
@@ -67,3 +120,32 @@ class PluginTestCase(unittest.TestCase):
implementations = self.plugin_manager.get_implementations(octoprint.plugin.StartupPlugin, octoprint.plugin.SettingsPlugin)
self.assertEquals(1, len(implementations))
self.assertTrue('mixed_plugin' in implementations)
def test_client_registration(self):
client = mock.Mock()
self.assertEquals(0, len(self.plugin_manager.registered_clients))
self.plugin_manager.register_client(client)
self.assertEquals(1, len(self.plugin_manager.registered_clients))
self.assertIn(client, self.plugin_manager.registered_clients)
self.plugin_manager.unregister_client(client)
self.assertEquals(0, len(self.plugin_manager.registered_clients))
self.assertNotIn(client, self.plugin_manager.registered_clients)
def test_send_plugin_message(self):
client1 = mock.Mock()
client2 = mock.Mock()
self.plugin_manager.register_client(client1)
self.plugin_manager.register_client(client2)
plugin = "some plugin"
data = "some data"
self.plugin_manager.send_plugin_message(plugin, data)
client1.sendPluginMessage.assert_called_once_with(plugin, data)
client2.sendPluginMessage.assert_called_once_with(plugin, data)