Added functionality to warn in case object exceeds printing area

This commit is contained in:
Javierma87 committed 2016-02-17 10:03:56 +00:00
commit 9e07a3b7c0
216 files changed
+30317 -4336

No files matched your search

+4
View File
@@ -1,3 +1,7 @@
src/octoprint/templates/_data/AUTHORS.md
src/octoprint/templates/_data/CHANGELOG.md
src/octoprint/templates/_data/THIRDPARTYLICENSES.md
*.tar.bz2
*.tar.gz
*.7z
+3 -3
View File
@@ -14,10 +14,10 @@ master
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.2.8
# maintenance is currently the branch for preparation of maintenance release 1.2.9
# so are any fix/... branches
maintenance 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
fix/.* 1.2.8 6c622f7c4332b71c6ece59552ffc87c146155c84 pep440-dev
maintenance 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
fix/.* 1.2.9 dedadbc9ac0305799e94ae279d3bca131629c4c5 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.3.0-dev for now
.* 1.3.0 198d3450d94be1a2 pep440-dev
+2
View File
@@ -54,7 +54,9 @@ date of first contribution):
* [Nicanor Romero Venier](https://github.com/nicanor-romero)
* [Thomas Hou](https://github.com/masterhou)
* [Mark Bastiaans](https://github.com/markbastiaans)
* [Marcel Hellwig](https://github.com/punkkeks)
* [Kevin Murphy](https://github.com/kevingelion)
* [Richard Joyce](https://github.com/richjoyce)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
+69
View File
@@ -1,5 +1,74 @@
# OctoPrint Changelog
## 1.3.0 (unreleased)
### New Features
* A new wizard dialog for system setups that can also be extended by plugins. Replaces the first run dialog
for setting up access control and can also be triggered in other cases than only the first run, e.g.
if Plugins necessitate user input to function properly.
* An About dialog including licenses, authors, the changelog and more, extendable by plugins if necessary.
* New features within the plugin system (TODO):
* New plugin mixin `UiPlugin` for plugins that want to provide an alternative web interface delivered by the
server.
* Extracted a Javascript client library for utilizing the server's API, can be reused by `UiPlugin`s. (TODO)
(TODO) = needs to be further described and documented
### Improvements
* Upgraded versioneer, generated version numbers are now PEP440 compatible (relevant
for setup)
* More verbose output for Software Update plugin for logged in administrators.
Will now log the update commands and their output similar to the Plugin
Manager install and uninstall dialog.
* Allow hiding plugins from Plugin Manager via ``config.yaml``.
* Cura Plugin: "Test" button to check if path to cura engine is valid.
* Cura Plugin: Now also supports 15.06 version of CuraEngine.
* New central configuration option for commands to restart OctoPrint and to
restart and shut down the system OctoPrint is running on. This allows plugins
(like the Software Update Plugin or the Plugin Manager) and core functionality
to perform these common administrative tasks without the user needing to define
everything redundantly.
* `pip` helper now adjusts `pip install` parameters corresponding to detected
`pip` version:
* Removes `--process-dependency-links` when it's not needed
* Adds `--no-use-wheel` when it's needed
* Detects and reports on completely broken versions
* Better tracking of printer connection state for plugins and scripts:
* Introduced three new Events `Connecting`, `Disconnecting` and
`PrinterStateChanged`.
* Introduced new GCODE script `beforePrinterDisconnected` which will get sent
before a (controlled) disconnect from the printer. This can be used to send
some final commands to the printer before the connection goes down, e.g.
`M117 Bye from OctoPrint`.
* The communication layer will now wait for the send queue to be fully processed
before disconnecting from the printer for good. This way it is ensured that
the `beforePrinterDisconnected` script or any further GCODE injected into it
will actually get sent.
* Additional baud rates to allow for connecting can now be specified along side
additional serial ports via the settings dialog and the configuration file.
* Option to never send checksums (e.g. if the printer firmware doesn't support it),
see [#949](https://github.com/foosel/OctoPrint/issues/949).
* Added secondary temperature polling interval to use when printer is not printing
but a target temperature is set - this way the graph should be more responsive
while monitoring a manual heatup.
* Documentation improvements
* Test buttons for webcam snapshot & stream URL, ffmpeg path and some other settings
(see also [#183](https://github.com/foosel/OctoPrint/issues/183)).
* Temperature graph automatically adjusts its Y axis range if necessary to
accomodate the plotted data (see also [#632](https://github.com/foosel/OctoPrint/issues/632)).
* "Fan on" command now always sends `S255` parameter for better compatibility
across firmwares.
### Bug Fixes
* It's not possible anymore to select files that are not machinecode files (e.g.
GCODE) for printing on the file API.
* Changes to a user's personal settings via the UI now propagate across sessions.
* [#1047](https://github.com/foosel/OctoPrint/issues/1047) - Fixed 90 degree
webcam rotation for iOS Safari.
## 1.2.8 (2015-12-07)
### Notes for Upgraders
+6 -2
View File
@@ -30,8 +30,12 @@ nothing but ticket management.
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
and *[use the provided template](#what-should-i-include-in-a-ticket)*.
You do not need to do anything else with your ticket.
- If you want to post a **request** of any kind (feature request, documentation
request, ...), add `[Request]` to your issue's title (e.g. `[Request] Awesome new feature`).
- If you want to post a **feature request** or a **documentation request**, add `[Request]`
to your issue's title (e.g. `[Request] Awesome new feature`). A question on how to run/change/setup
something is **not** what qualifies as a request here, use the
[Mailinglist](https://groups.google.com/group/octoprint) or the
[Google+ Community](https://plus.google.com/communities/102771308349328485741) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
`[Brainstorming] New plugin hook for doing some cool stuff`).
+4
View File
@@ -2,7 +2,11 @@ recursive-include src/octoprint/static *
recursive-include src/octoprint/templates *
recursive-include src/octoprint/plugins *
recursive-include src/octoprint/translations *
include src/octoprint/util/piptestballoon/setup.py
include versioneer.py
include src/octoprint/_version.py
include AUTHORS.md
include CHANGELOG.md
include LICENSE
include README.md
include requirements.txt
+2 -2
View File
@@ -47,11 +47,11 @@ which is a custom SD card image that includes OctoPrint plus dependencies.
The generic steps that should basically be done regardless of operating system
and runtime environment are the following (as *regular
user*, please keep your hands *off* of the `sudo` command here!) - this assumes
you already have Python 2.7, pip and virtualenv set up:
you already have Python 2.7, pip and virtualenv set up on your system:
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv --system-site-packages venv`
3. Create a user-owned virtual environment therein: `virtualenv venv`
4. Install OctoPrint *into that virtual environment*: `./venv/bin/python setup.py install`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
+56
View File
@@ -0,0 +1,56 @@
# Third Party Licenses
## Web Interface
* [AVLTree](https://gist.github.com/viking/2424106) (modified): GPL, LGPL (dual licensed)
* [Babel JavaScript Support](https://github.com/mitsuhiko/babel/blob/master/contrib/babel.js): BSD
* [Bootstrap](http://getbootstrap.com/): Apache License 2.0
* [Bootstrap Modal](http://jschr.github.io/bootstrap-modal/): Apache License 2.0
* [Bootstrap Slider Knockout Bindings](https://github.com/cosminstefanxp/bootstrap-slider-knockout-binding): MIT
* [Bootstrap Slider](http://seiyria.com/bootstrap-slider/): Apache License 2.0
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
* [Flot](http://www.flotcharts.org/): MIT
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
* [JQuery](http://jquery.com/): MIT
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
* [JQuery File Upload](https://github.com/blueimp/jQuery-File-Upload): MIT
* [JQuery iframe transport](https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.iframe-transport.js): MIT
* [JQuery QRCode](http://larsjung.de/jquery-qrcode/): MIT
* [JQuery Slimscroll](http://rocha.la/jQuery-slimScroll): MIT, GPL (dual licensed)
* [JQuery UI Core, Mouse, Slider and Widget](http://jqueryui.com): MIT
* [Knockout](http://knockoutjs.com/): MIT
* [LESS](http://lesscss.org): Apache License 2.0
* [lodash](https://lodash.com): MIT
* [Loglevel](https://github.com/pimterry/loglevel): MIT
* [Modernizr](http://modernizr.com): MIT
* [Moment.js](http://momentjs.com/): MIT
* [PNotify](http://sciactive.com/pnotify/): GPL, LGPL, MPL (triple licensed)
* [pusher.color.js](http://cache.preserve.io/5g18q0pw/index.html) (original link dead): MIT
* [SockJS](https://github.com/sockjs/sockjs-client): MIT
* [sprintf-js](http://alexei.ro/): BSD
## Server
* [Awesome-Slugify](https://pypi.python.org/pypi/awesome-slugify): GPLv3
* [Click](http://click.pocoo.org/): BSD
* [Flask](http://flask.pocoo.org/): BSD
* [Flask-Assets](http://github.com/miracle2k/flask-assets): BSD
* [Flask-Babel](http://github.com/mitsuhiko/flask-babel): BSD
* [Flask-Login](https://flask-login.readthedocs.org/en/latest/https://github.com/maxcountryman/flask-login): MIT
* [Flask-Markdown](http://github.com/dcolish/flask-markdown): BSD
* [Flask-Principal](http://packages.python.org/Flask-Principal/): MIT
* [netaddr](https://github.com/drkjam/netaddr/): BSD
* [netifaces](https://bitbucket.org/al45tair/netifaces): MIT
* [pkginfo](http://pypi.python.org/pypi/pkginfo/): Python
* [psutil](https://github.com/giampaolo/psutil): BSD
* [pylru](https://github.com/jlhutch/pylru): GPLv2
* [pyserial](http://pyserial.sourceforge.net/): Python
* [PyYAML](http://pyyaml.org/wiki/PyYAML): MIT
* [requests](http://python-requests.org/): Apache License 2.0
* [rsa](http://stuvel.eu/rsa): Apache License 2.0
* [sarge](http://sarge.readthedocs.org/): BSD
* [semantic_version](https://github.com/rbarrois/python-semanticversion): BSD
* [SockJS-Tornado](http://github.com/mrjoes/sockjs-tornado/): MIT
* [Tornado](http://www.tornadoweb.org/): Apache License 2.0
* [watchdog](http://github.com/gorakhargosh/watchdog): Apache License 2.0
+26
View File
@@ -611,6 +611,32 @@ Use the following settings to configure the serial connection to the printer:
additionalPorts:
- /dev/myPrinterSymlink
# Use this to define additional baud rates to offer for connecting to serial ports. Must be a
# valid integer. Defaults to not set
additionalBaudrates:
- 123456
# Commands which are known to take a long time to be acknowledged by the firmware. E.g.
# homing, dwelling, auto leveling etc. Defaults to the below commands.
longRunningCommands:
- G4
- G28
- G29
- G30
- G32
- M400
- M226
# Commands which need to always be send with a checksum. Defaults to only M110
checksumRequiringCommands:
- M110
# Command to send in order to initiate a handshake with the printer.
# Defaults to "M110 N0" which simply resets the line numbers in the firmware and which
# should be acknowledged with a simple "ok".
helloCommand:
- M110 N0
.. _sec-configuration-config_yaml-server:
Server
+17
View File
@@ -106,6 +106,9 @@ ClientClosed
Printer communication
---------------------
Connecting
The server is attempting to connect to the printer.
Connected
The server has connected to the printer.
@@ -114,6 +117,11 @@ Connected
* ``port``: the connected serial port
* ``baudrate``: the baud rate
Disconnecting
The server is going to disconnect from the printer. Note that this
event might not always be sent when the server and printer get disconnected
from each other. Do not depend on this for critical life cycle management.
Disconnected
The server has disconnected from the printer
@@ -124,6 +132,15 @@ Error
* ``error``: the error string
PrinterStateChanged
The state of the printer changed.
Payload:
* ``state_id``: Id of the new state. See
:func:`~octoprint.printer.PrinterInterface.get_state_id` for possible values.
* ``state_string``: Text representation of the new state.
File handling
-------------
+1 -1
View File
@@ -65,7 +65,7 @@ a GCODE script including user input.
children:
- name: Get Position
command: M114
regex: "X:([0-9.]+) Y:([0-9.]+) Z:([0-9.]+) E:([0-9.]+)"
regex: "X:([-+]?[0-9.]+) Y:([-+]?[0-9.]+) Z:([-+]?[0-9.]+) E:([-+]?[0-9.]+)"
template: "Position: X={0}, Y={1}, Z={2}, E={3}"
- name: Fun stuff
children:
+4
View File
@@ -26,6 +26,10 @@ Predefined Scripts
The following GCODE scripts are sent by OctoPrint automatically:
* ``afterPrinterConnected``: Sent after OctoPrint successfully connected to a printer. Defaults to an empty script.
* ``beforePrinterDisconnected``: Sent just before OctoPrint (actively) closes the connection to the printer. Defaults
to an empty script. Note that this will *not* be sent for unexpected connection cut offs, e.g. in case of errors
on the serial line, only when the user clicks the "Disconnect" button or the printer requests a disconnect via an
:ref:`action command <sec-features-action_commands>` .
* ``beforePrintStarted``: Sent just before a print job is started. Defaults to an empty script.
* ``afterPrintCancelled``: Sent just after a print job was cancelled. Defaults to the
:ref:`bundled script listed below <sec-features-gcode_scripts-bundled>`.
+31
View File
@@ -0,0 +1,31 @@
.. _sec-modules-cli:
octoprint.cli
-------------
.. automodule:: octoprint.cli
:members:
.. _sec-modules-cli-dev:
octoprint.cli.dev
-----------------
.. automodule:: octoprint.cli.dev
:members:
.. _sec-modules-cli-plugins:
octoprint.cli.plugins
---------------------
.. automodule:: octoprint.cli.plugins
:members:
.. _sec-modules-cli-server:
octoprint.cli.server
--------------------
.. automodule:: octoprint.cli.server
:members:
+1
View File
@@ -7,6 +7,7 @@ Internal Modules
.. toctree::
:maxdepth: 3
cli.rst
filemanager.rst
plugin.rst
printer.rst
+2
View File
@@ -328,6 +328,8 @@ An overview of these properties follows.
OctoPrint's printer management object, an instance of :class:`octoprint.printer.PrinterInterface`.
``self._app_session_manager``
OctoPrint's application session manager, an instance of :class:`octoprint.server.util.flask.AppSessionManager`.
``self._user_manager``
OctoPrint's user manager, an instance of :class:`octoprint.users.UserManager`.
.. seealso::
+80 -37
View File
@@ -10,6 +10,37 @@ Over the course of this little tutorial we'll build a full fledged, installable
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.
First of all let use make sure that you have OctoPrint checked out and set up for development on your local
development environment::
$ cd ~/devel
$ git clone https://github.com/foosel/OctoPrint
[...]
$ cd OctoPrint
$ virtualenv venv
[...]
$ source venv/bin/activate
(venv) $ pip install -e[develop]
[...]
(venv) $ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
[...]
.. note::
You can also develop your plugin directly on your Raspberry Pi running OctoPi of course. In that
case please ignore the above instructions, you'll only need to activate the ``oprint``
virtual environment:
.. code-block:: none
$ source ~/oprint/bin/activate
(oprint) $ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
[...]
We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code:
.. code-block:: python
@@ -24,14 +55,15 @@ We'll start at the most basic form a plugin can take - just a couple of simple l
Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup::
(venv) $ octoprint serve
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 - 3 plugin(s) registered with the system:
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
[...]
| Hello World (1.0.0) = /home/pi/.octoprint/plugins/helloworld.py
[...]
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
@@ -101,31 +133,35 @@ or alternatively manually utilizing Python's standard package manager ``pip`` di
So let's begin. We'll use the `cookiecutter <https://github.com/audreyr/cookiecutter>`_ template for OctoPrint plugins here,
so we'll first need to install that::
$ pip install cookiecutter
(venv) $ pip install cookiecutter
Then we can use the ``cookiecutter`` command to generate a new OctoPrint plugin skeleton for us::
Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a new OctoPrint plugin skeleton for us::
$ cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin
(venv) $ cd ~/devel
(venv) $ octoprint dev plugin:new helloworld
Cloning into 'cookiecutter-octoprint-plugin'...
remote: Counting objects: 70, done.
remote: Compressing objects: 100% (17/17), done.
emote: Total 70 (delta 0), reused 0 (delta 0), pack-reused 51
Unpacking objects: 100% (70/70), done.
Checking connectivity... done.
plugin_identifier (default is "skeleton")? helloworld
plugin_package (default is "octoprint_helloworld")?
plugin_name (default is "OctoPrint-Helloworld")?
repo_name (default is "OctoPrint-Helloworld")?
full_name (default is "You")? Your Name
email (default is "you@example.com")? you@somewhere.net
github_username (default is "you")? yourGithubName
plugin_version (default is "0.1.0")? 1.0.0
plugin_description (default is "TODO")? A quick "Hello World" example plugin for OctoPrint
plugin_license (default is "AGPLv3")?
plugin_homepage (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")?
plugin_source (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")?
plugin_installurl (default is "https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip")?
$ cd OctoPrint-HelloWorld
remote: Counting objects: 101, done.
remote: Total 101 (delta 0), reused 0 (delta 0), pack-reused 101
Receiving objects: 100% (101/101), 53.69 KiB, done.
Resolving deltas: 100% (35/35), done.
plugin_package [octoprint_helloworld]:
plugin_name [OctoPrint-Helloworld]:
repo_name [OctoPrint-Helloworld]:
full_name [You]: Your Name
email [you@example.com]: you@somewhere.net
github_username [you]: yourGithubName
plugin_version [0.1.0]: 1.0.0
plugin_description [TODO]: A quick "Hello World" example plugin for OCtoPrint
plugin_license [AGPLv3]:
plugin_homepage [https://github.com/yourGithubName/OctoPrint-Helloworld]:
plugin_source [https://github.com/yourGithubName/OctoPrint-Helloworld]:
plugin_installurl [https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip]:
(venv) $ cd OctoPrint-HelloWorld
.. note::
If ``octoprint dev plugin:new`` isn't recognized as a command (and also doesn't show up in the output of
``octoprint --help``, make sure you installed cookiecutter into the same python environment as OctoPrint.
This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this::
@@ -193,9 +229,11 @@ Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_
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::
discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do. We can have the
``octoprint dev plugin:install`` command do everything for us here, it will ensure to use the python binary belonging
to your OctoPrint installation::
$ python setup.py develop
(venv) $ octoprint dev plugin:install
running develop
running egg_info
creating OctoPrint_HelloWorld.egg-info
@@ -209,9 +247,8 @@ Restart OctoPrint. Your plugin should still be properly discovered and the log l
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 - 3 plugin(s) registered with the system:
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
| Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
[...]
| Hello World (1.0.0) = /home/pi/devel/OctoPrint-HelloWorld/octoprint_helloworld
[...]
2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World!
@@ -257,9 +294,9 @@ and ``__plugin_description__`` from ``__init__.py``:
and restart OctoPrint::
2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system:
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
| OctoPrint-HelloWorld (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
[...]
| OctoPrint-HelloWorld (1.0.0) = /home/pi/devel/OctoPrint-HelloWorld/octoprint_helloworld
[...]
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:
@@ -284,9 +321,9 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the
Restart OctoPrint again::
2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system:
| CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura
| Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery
[...]
| Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld
[...]
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-plugin-concepts-controlproperties>` for all available
@@ -295,7 +332,7 @@ 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/yourGithubName/OctoPrint-HelloWorld/archive/master.zip
(venv) $ pip install https://github.com/yourGithubName/OctoPrint-HelloWorld/archive/master.zip
But let's add some more features instead.
@@ -857,7 +894,7 @@ generated CSS files (and compiles them on the fly in your browser using `lessjs
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``
into that the same content as into our CSS file. Compile that LESS file to CSS [#f2]_, overwriting our old ``helloworld.css``
in the process. The folder structure of our plugin should now look like this::
octoprint_helloworld/
@@ -1038,6 +1075,12 @@ 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
.. [#f1] Instead of the ``octoprint dev plugin:new`` you could also have manually called cookiecutter with the
template's repository URL shortcut: ``cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin``. The
``devel:newplugin`` command already does this for you, makes sure cookiecutter always uses a fresh
checkout without prompting you for it and also allows to pre-specify a bunch of settings (like the
plugin's identifier) directly from the command line. Take a look at ``octoprint dev plugin:new --help``
for the usage details.
.. [#f2] 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.
+163
View File
@@ -37,6 +37,143 @@ octoprint.accesscontrol.appkey
:return: A list of 3-tuples as described above
:rtype: list
.. _sec-plugins-hook-cli-commands:
octoprint.cli.commands
----------------------
.. py:function:: hook(cli_group, pass_octoprint_ctx, *args, **kwargs)
By providing a handler for this hook plugins may register commands on OctoPrint's command line interface (CLI).
Handlers are expected to return a list of callables annotated as `Click commands <http://click.pocoo.org/5/>`_ to register with the
CLI.
The custom ``MultiCommand`` instance :class:`~octoprint.cli.plugins.OctoPrintPluginCommands` is provided
as parameter. Via that object handlers may access the *global* :class:`~octoprint.settings.Settings`
and the :class:`~octoprint.plugin.core.PluginManager` instance as ``cli_group.settings`` and ``cli_group.plugin_manager``.
**Example:**
Registers two new commands, ``custom_cli_command:greet`` and ``custom_cli_command:random`` with
OctoPrint:
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_cli_command.py
:linenos:
:tab-width: 4
:caption: `custom_cli_command.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/custom_cli_command.py>`_
Calling ``octoprint --help`` shows the two new commands:
.. code-block:: none
$ octoprint --help
Usage: octoprint [OPTIONS] COMMAND [ARGS]...
Options:
-b, --basedir PATH Specify the basedir to use for uploads, timelapses etc.
-c, --config PATH Specify the config file to use.
-v, --verbose Increase logging verbosity
--version Show the version and exit.
--help Show this message and exit.
Commands:
daemon Starts, stops or restarts in daemon mode.
dev:plugin Helpers for plugin developers
plugin:custom_cli_command custom_cli_command commands
serve Starts the OctoPrint server.
$ octoprint plugin:custom_cli_command --help
Usage: octoprint plugin:custom_cli_command [OPTIONS] COMMAND [ARGS]...
custom_cli_command commands
Options:
--help Show this message and exit.
Commands:
greet Greet someone by name, the greeting can be...
random Greet someone by name with a random greeting.
Each also has an individual help output:
.. code-block:: none
$ octoprint plugin:custom_cli_command greet --help
Usage: octoprint plugin:custom_cli_command greet [OPTIONS] [NAME]
Greet someone by name, the greeting can be customized.
Options:
-g, --greeting TEXT The greeting to use
--help Show this message and exit.
$ octoprint plugin:custom_cli_command random --help
Usage: octoprint plugin:custom_cli_command random [OPTIONS] [NAME]
Greet someone by name with a random greeting.
Options:
--help Show this message and exit.
And of course they work too:
.. code-block:: none
$ octoprint plugin:custom_cli_command greet
Hello World!
$ octoprint plugin:custom_cli_command greet --greeting "Good morning"
Good morning World!
$ octoprint plugin:custom_cli_command random stranger
Hola stranger!
.. note::
If your hook handler is an instance method of a plugin mixin implementation, be aware that the hook will be
called without OctoPrint initializing your implementation instance. That means that **none** of the
:ref:`injected properties <sec-plugins-concepts-injectedproperties>` will be available and also the
:method:`~octoprint.plugin.Plugin.initialize` method will not be called.
Your hook handler will have access to the plugin manager as ``cli_group.plugin_manager`` and to the
*global* settings as ``cli_group.settings``. You can have your handler turn the latter into a
:class:`~octoprint.plugin.PluginSettings` instance by using :func:`octoprint.plugin.plugin_settings_from_settings_plugin`
if your plugin's implementation implements the :class:`~octoprint.plugin.SettingsPlugin` mixin and inject
that and the plugin manager instance yourself:
.. code-block:: python
import octoprint.plugin
class MyPlugin(octoprint.plugin.SettingsPlugin):
def get_cli_commands(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
import logging
settings = cli_group._settings
plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin("myplugin", self)
if plugin_settings is None:
# this can happen if anything goes wrong with preparing the PluginSettings instance
return dict()
self._settings = plugin_settings
self._plugin_manager = cli_group._plugin_manager
self._logger = logging.getLogger(__name__)
### command definition starts here
# ...
No other platform components will be available - the CLI runs outside of a running, fully initialized
OctoPrint server context, so there is absolutely no way to access a printer connection, the event bus or
anything else like that. The only things available are the settings and the plugin manager.
:return: A list of `Click commands or groups <http://click.pocoo.org/5/commands/>`_ to provide on
OctoPrint's CLI.
:rtype: list
.. _sec-plugins-hook-comm-protocol-action:
octoprint.comm.protocol.action
@@ -159,6 +296,32 @@ This describes actually four hooks:
:param str gcode: Parsed GCODE command, e.g. ``G0`` or ``M110``, may also be None if no known command could be parsed
:return: None, 1-tuple, 2-tuple or string, see the description above for details.
.. _sec-plugins-hook-comm-protocol-gcode-received:
octoprint.comm.protocol.gcode.received
--------------------------------------
.. py:function:: hook(comm_instance, line, *args, **kwargs)
Get the returned lines sent by the printer. Handlers should return the received line or in any case, the modified
version of it. If the the handler returns None, processing will be aborted and the communication layer will get an
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
``return`` statement is used or just nothing is returned explicitely from the handler.
**Example:**
Looks for the response of a M115, which contains information about the MACHINE_TYPE, among other things.
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/read_m115_response.py
:linenos:
:tab-width: 4
:caption: `read_m115_response.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/read_m115_response.py>`_
:param MachineCom comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str line: The line received from the printer.
:return: The received line or in any case, a modified version of it.
:rtype: str
.. _sec-plugins-hook-comm-protocol-scripts:
octoprint.comm.protocol.scripts
+28
View File
@@ -18,6 +18,7 @@ StartupPlugin
.. autoclass:: octoprint.plugin.StartupPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-shutdownplugin:
@@ -26,6 +27,7 @@ ShutdownPlugin
.. autoclass:: octoprint.plugin.ShutdownPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-settingsplugin:
@@ -34,6 +36,7 @@ SettingsPlugin
.. autoclass:: octoprint.plugin.SettingsPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-assetplugin:
@@ -42,6 +45,7 @@ AssetPlugin
.. autoclass:: octoprint.plugin.AssetPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-templateplugin:
@@ -50,6 +54,25 @@ TemplatePlugin
.. autoclass:: octoprint.plugin.TemplatePlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-wizardplugin:
WizardPlugin
------------
.. autoclass:: octoprint.plugin.WizardPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-uiplugin:
UiPlugin
--------
.. autoclass:: octoprint.plugin.UiPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-simpleapiplugin:
@@ -58,6 +81,7 @@ SimpleApiPlugin
.. autoclass:: octoprint.plugin.SimpleApiPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-blueprintplugin:
@@ -66,6 +90,7 @@ BlueprintPlugin
.. autoclass:: octoprint.plugin.BlueprintPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-eventhandlerplugin:
@@ -74,6 +99,7 @@ EventHandlerPlugin
.. autoclass:: octoprint.plugin.EventHandlerPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-progressplugin:
@@ -82,6 +108,7 @@ ProgressPlugin
.. autoclass:: octoprint.plugin.ProgressPlugin
:members:
:show-inheritance:
.. _sec-plugins-mixins-slicerplugin:
@@ -90,4 +117,5 @@ SlicerPlugin
.. autoclass:: octoprint.plugin.SlicerPlugin
:members:
:show-inheritance:
+22 -1
View File
@@ -171,7 +171,7 @@ onAfterTabChange
getAdditionalControls
Your viewmodel may return additional custom control definitions for inclusion on the "Control" tab of OctoPrint's
interface. See :ref:`the custom control feature<sec-features-custom_controls>`.
interface. See :ref:`the custom control feature<sec-features-custom_controls>`.
onSettingsShown
Called when the settings dialog is shown.
@@ -189,6 +189,27 @@ onUserSettingsShown
onUserSettingsHidden
Called when the user settings dialog is hidden.
onWizardDetails
Called with the response from the wizard detail API call initiated before opening the wizard dialog. Will contain
the data from all :class:`~octoprint.plugin.WizardPlugin` implementations returned by their :meth:`~octoprint.plugin.WizardPlugin.get_wizard_details`
method, mapped by the plugin identifier.
onWizardTabChange
Called before the wizard tab/step is changed, with the ids of the current and the next tab as parameters. Return false
in order to prevent the tab change, e.g. if the wizard step is mandatory and not yet completed by the user. Take a look at
the "Core Wizard" plugin bundled with OctoPrint and the ACL wizard step in particular for an example on how to use this.
onAfterWizardTabChange
Called after the wizard tab/step is changed, with the id of the current tab as parameter.
onBeforeWizardFinish
Called before executing the finishing of the wizard. Return false here to stop the actual finish, e.g. if some step is
still incomplete.
onWizardFinish
Called after executing the finishing of the wizard and before closing the dialog. Return ``reload`` here in order to
instruct OctoPrint to reload the UI after the wizard closes.
In order to hook into any of those callbacks, just have your viewmodel define a function named accordingly, e.g.
to get called after all viewmodels have been bound during application startup, implement a function ``onAllBound``
on your viewmodel, taking a list of all bound viewmodels:
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2
import os
import sys
+8 -2
View File
@@ -3,11 +3,17 @@
# The init.d script will only run if this variable non-empty.
OCTOPRINT_USER=pi
# base directory to use
#BASEDIR=/home/pi/.octoprint
# configuration file to use
#CONFIGFILE=/home/pi/.octoprint/config.yaml
# On what port to run daemon, default is 5000
PORT=5000
# Path to the OctoPrint executable, use this to override the default setting "/usr/bin/octoprint"
#DAEMON=/path/to/octoprint/executable
# Path to the OctoPrint executable, you need to set this to match your installation!
#DAEMON=/home/pi/OctoPrint/venv/bin/octoprint
# What arguments to pass to octoprint, usually no need to touch this
DAEMON_ARGS="--port=$PORT"
+27 -8
View File
@@ -16,17 +16,23 @@
# Author: Sami Olmari
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Octoprint Daemon"
NAME="Octoprint"
DAEMON=/usr/local/bin/octoprint
PIDFILE=/var/run/$NAME.pid
DESC="OctoPrint Daemon"
NAME="OctoPrint"
PKGNAME=octoprint
PIDFILE=/var/run/$PKGNAME.pid
SCRIPTNAME=/etc/init.d/$PKGNAME
# Read configuration variable file if it is present
[ -r /etc/default/$PKGNAME ] && . /etc/default/$PKGNAME
# Exit if the octoprint is not installed
# Exit if the DAEMON is not set
if [ -z "$DAEMON" ]
then
log_warning_msg "Not starting $PKGNAME, DAEMON not set in /etc/default/$PKGNAME."
exit 0
fi
# Exit if the DAEMON is not installed
[ -x "$DAEMON" ] || exit 0
# Load the VERBOSE setting and other rcS variables
@@ -48,6 +54,17 @@ then
exit 0
fi
COMMAND_ARGS=
if [ -z "$BASEDIR" ]
then
COMMAND_ARGS="--basedir $BASEDIR $COMMAND_ARGS"
fi
if [ -z "$CONFIGFILE" ]
then
COMMAND_ARGS="--config $CONFIGFILE $COMMAND_ARGS"
fi
#
# Function to verify if a pid is alive
#
@@ -74,7 +91,7 @@ do_start()
if [ $RETVAL != 0 ]; then
start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \
--exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK --nicelevel=$NICELEVEL \
-- $DAEMON_ARGS
-- $COMMAND_ARGS serve $DAEMON_ARGS
RETVAL="$?"
fi
}
@@ -116,6 +133,9 @@ case "$1" in
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
status)
status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
;;
restart)
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
@@ -135,8 +155,7 @@ case "$1" in
esac
;;
*)
echo "Usage: $SCRIPTNAME {start|stop|restart}" >&2
echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
exit 3
;;
esac
+65 -25
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# coding=utf-8
from setuptools import setup, find_packages
from distutils.command.build_py import build_py as _build_py
import os
import versioneer
@@ -14,25 +15,28 @@ import octoprint_setuptools
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"werkzeug==0.8.3",
"tornado==4.0.1",
"sockjs-tornado==1.0.1",
"PyYAML==3.10",
"Flask-Login==0.2.2",
"Flask-Principal==0.3.5",
"Flask-Babel==0.9",
"Flask-Assets==0.10",
"pyserial==2.7",
"netaddr==0.7.17",
"watchdog==0.8.3",
"sarge==0.1.4",
"netifaces==0.10",
"pylru==1.0.9",
"rsa==3.2",
"pkginfo==1.2.1",
"requests==2.7.0",
"semantic_version==2.4.2",
"psutil==3.2.1"
"werkzeug>=0.8.3,<0.9",
"tornado>=4.0.2,<4.1",
"sockjs-tornado>=1.0.2,<1.1",
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3",
"Flask-Principal>=0.3.5,<0.4",
"Flask-Babel>=0.9,<0.10",
"Flask-Assets>=0.10,<0.11",
"Flask-Markdown>=0.3,<0.4",
"pyserial>=2.7,<2.8",
"netaddr>=0.7.17,<0.8",
"watchdog>=0.8.3,<0.9",
"sarge>=0.1.4,<0.2",
"netifaces>=0.10,<0.11",
"pylru>=1.0.9,<1.1",
"rsa>=3.2,<3.3",
"pkginfo>=1.2.1,<1.3",
"requests>=2.7,<2.8",
"semantic_version>=2.4.2,<2.5",
"psutil>=3.2.1,<3.3",
"Click>=5.1,<5.2",
"awesome-slugify>=1.6.5,<1.7"
]
# Additional requirements for optional install options
@@ -40,12 +44,12 @@ EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=1.0.1",
"nose>=1.3.0",
"mock>=1.0.1,<1.1",
"nose>=1.3.0,<1.4",
"ddt",
# Documentation dependencies
"sphinx>=1.3",
"sphinx>=1.3,<1.4",
"sphinxcontrib-httpdomain",
"sphinx_rtd_theme",
@@ -68,6 +72,32 @@ DEPENDENCY_LINKS = []
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
files = dict()
def run(self):
import shutil
if not self.dry_run:
for directory, files in self.__class__.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry
else:
source = dest = entry
shutil.copy(source, os.path.join(target_dir, dest))
baseclass.run(self)
return type(data_copy_build_py)(data_copy_build_py.__name__,
(data_copy_build_py,),
dict(files=files))
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
@@ -80,6 +110,14 @@ def get_cmdclass():
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
cmdclass["build_py"] = data_copy_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"CHANGELOG.md",
"THIRDPARTYLICENSES.md",
]
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
return cmdclass
@@ -130,10 +168,12 @@ def params():
packages = find_packages(where="src")
package_dir = {
"": "src"
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint', ['static', 'templates', 'plugins', 'translations'])
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint',
['static', 'templates', 'plugins', 'translations'])
+ ['util/piptestballoon/setup.py']
}
include_package_data = True
+199 -68
View File
@@ -1,84 +1,215 @@
#!/usr/bin/env python
#!/usr/bin/env python2
# coding=utf-8
from __future__ import absolute_import, print_function
import sys
from octoprint.daemon import Daemon
from octoprint.server import Server
import logging
#~~ version
from ._version import get_versions
__version__ = get_versions()['version']
versions = get_versions()
__version__ = versions['version']
__branch__ = versions.get('branch', None)
__display_version__ = "{} ({} branch)".format(__version__, __branch__) if __branch__ else __version__
__revision__ = versions.get('full-revisionid', versions.get('full', None))
del versions
del get_versions
#~~ main class
#~~ sane logging defaults
class Main(Daemon):
def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot, logConf):
Daemon.__init__(self, pidfile)
logging.basicConfig()
self._configfile = configfile
self._basedir = basedir
self._host = host
self._port = port
self._debug = debug
self._allowRoot = allowRoot
self._logConf = logConf
#~~ try to ensure a sound SSL environment
def run(self):
octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot)
octoprint.run()
urllib3_ssl = True
"""Whether requests/urllib3 and urllib3 (if installed) should be able to establish
a sound SSL environment or not."""
version_info = sys.version_info
if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < 9:
try:
# make sure our requests version of urllib3 is properly patched (if possible)
import requests.packages.urllib3.contrib.pyopenssl
requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
urllib3_ssl = False
try:
import urllib3
# only proceed if urllib3 is even installed on its own
try:
# urllib3 is there, let's patch that too
import urllib3.contrib.pyopenssl
urllib3.contrib.pyopenssl.inject_into_urllib3()
except ImportError:
urllib3_ssl = False
except ImportError:
pass
del version_info
#~~ init methods to bring up platform
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
uncaught_handler=None, after_settings=None, after_logging=None):
settings = init_settings(basedir, configfile)
if callable(after_settings):
after_settings(settings)
logger = init_logging(settings,
use_logging_file=use_logging_file,
logging_file=logging_file,
default_config=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=uncaught_logger,
uncaught_handler=uncaught_handler)
if callable(after_logging):
after_logging(logger)
plugin_manager = init_pluginsystem(settings)
return settings, logger, plugin_manager
def init_settings(basedir, configfile):
"""Inits the settings instance based on basedir and configfile to use."""
from octoprint.settings import settings
return settings(init=True, basedir=basedir, configfile=configfile)
def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None):
"""Sets up logging."""
import os
from octoprint.util import dict_merge
# default logging configuration
if default_config is None:
default_config = {
"version": 1,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"file": {
"class": "logging.handlers.TimedRotatingFileHandler",
"level": "DEBUG",
"formatter": "simple",
"when": "D",
"backupCount": "1",
"filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log")
},
"serialFile": {
"class": "logging.handlers.RotatingFileHandler",
"level": "DEBUG",
"formatter": "simple",
"maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log")
}
},
"loggers": {
"SERIAL": {
"level": "CRITICAL",
"handlers": ["serialFile"],
"propagate": False
},
"octoprint": {
"level": "INFO"
},
"octoprint.util": {
"level": "INFO"
},
"octoprint.plugins": {
"level": "INFO"
}
},
"root": {
"level": "WARN",
"handlers": ["console", "file"]
}
}
if debug or verbosity > 0:
default_config["loggers"]["octoprint"]["level"] = "DEBUG"
default_config["root"]["level"] = "INFO"
if verbosity > 1:
default_config["loggers"]["octoprint.plugins"]["level"] = "DEBUG"
if verbosity > 2:
default_config["root"]["level"] = "DEBUG"
if use_logging_file:
# further logging configuration from file...
if logging_file is None:
logging_file = os.path.join(settings.getBaseFolder("base"), "logging.yaml")
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
with open(logging_file, "r") as f:
config_from_file = yaml.safe_load(f)
# we merge that with the default config
config = dict_merge(default_config, config_from_file)
else:
config = default_config
# configure logging globally
import logging.config
logging.config.dictConfig(config)
# make sure we log any warnings
logging.captureWarnings(True)
import warnings
categories = (DeprecationWarning, PendingDeprecationWarning)
if verbosity > 2:
warnings.simplefilter("always")
elif debug or verbosity > 0:
for category in categories:
warnings.simplefilter("always", category=category)
# make sure we also log any uncaught exceptions
if uncaught_logger is None:
logger = logging.getLogger(__name__)
else:
logger = logging.getLogger(uncaught_logger)
if uncaught_handler is None:
def exception_logger(exc_type, exc_value, exc_tb):
logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
uncaught_handler = exception_logger
sys.excepthook = uncaught_handler
return logger
def init_pluginsystem(settings):
"""Initializes the plugin manager based on the settings."""
from octoprint.plugin import plugin_manager
return plugin_manager(init=True, settings=settings)
#~~ server main method
def main():
import argparse
from octoprint.cli import octo
octo(prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
parser = argparse.ArgumentParser(prog="run")
parser.add_argument("-v", "--version", action="store_true", dest="version",
help="Output OctoPrint's version and exit")
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
help="Enable debug mode")
parser.add_argument("--host", action="store", type=str, dest="host",
help="Specify the host on which to bind the server")
parser.add_argument("--port", action="store", type=int, dest="port",
help="Specify the port on which to bind the server")
parser.add_argument("-c", "--config", action="store", dest="config",
help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml")
parser.add_argument("-b", "--basedir", action="store", dest="basedir",
help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint")
parser.add_argument("--logging", action="store", dest="logConf",
help="Specify the config file to use for configuring logging. Defaults to ~/.octoprint/logging.yaml")
parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"],
help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)")
parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid",
help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid")
parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot",
help="Allow OctoPrint to run as user root")
args = parser.parse_args()
if args.version:
print "OctoPrint version %s" % __version__
sys.exit(0)
if args.daemon:
if sys.platform == "darwin" or sys.platform == "win32":
print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now"
sys.exit(2)
daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf)
if "start" == args.daemon:
daemon.start()
elif "stop" == args.daemon:
daemon.stop()
elif "restart" == args.daemon:
daemon.restart()
else:
octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf)
octoprint.run()
if __name__ == "__main__":
main()
+2 -2
View File
@@ -40,11 +40,11 @@ def get_config():
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440"
cfg.style = "pep440-post"
cfg.tag_prefix = ""
cfg.parentdir_prefix = ""
cfg.versionfile_source = "src/octoprint/_version.py"
cfg.lookupfile = None
cfg.lookupfile = ".versioneer-lookup"
cfg.verbose = False
return cfg
+151
View File
@@ -0,0 +1,151 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import octoprint
#~~ click context
class OctoPrintContext(object):
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True)
"""Decorator to pass in the :class:`OctoPrintContext` instance."""
#~~ Custom click option to hide from help
class HiddenOption(click.Option):
"""Custom option sub class with empty help."""
def get_help_record(self, ctx):
pass
def hidden_option(*param_decls, **attrs):
"""Attaches a hidden option to the command. All positional arguments are
passed as parameter declarations to :class:`Option`; all keyword
arguments are forwarded unchanged. This is equivalent to creating an
:class:`Option` instance manually and attaching it to the
:attr:`Command.params` list.
"""
import inspect
from click.decorators import _param_memo
def decorator(f):
if 'help' in attrs:
attrs['help'] = inspect.cleandoc(attrs['help'])
_param_memo(f, HiddenOption(param_decls, **attrs))
return f
return decorator
#~~ helper for settings context options
def set_ctx_obj_option(ctx, param, value):
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if hasattr(ctx.obj, param.name):
setattr(ctx.obj, param.name, value)
#~~ helper for setting a lot of bulk options
def bulk_options(options):
"""
Utility decorator to decorate a function with a list of click decorators.
The provided list of ``options`` will be reversed to ensure correct
processing order (inverse from what would be intuitive).
"""
def decorator(f):
options.reverse()
for option in options:
option(f)
return f
return decorator
#~~ helper for setting --basedir, --config and --verbose options
def standard_options(hidden=False):
"""
Decorator to add the standard options shared among all "octoprint" commands.
Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden``
is set to ``True``, the options will be available on the command but not
listed in its help page.
"""
factory = click.option
if hidden:
factory = hidden_option
options = [
factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the basedir to use for uploads, timelapses etc."),
factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Specify the config file to use."),
factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Increase logging verbosity"),
]
return bulk_options(options)
#~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options([
hidden_option("--host", type=click.STRING),
hidden_option("--port", type=click.INT),
hidden_option("--logging", type=click.Path()),
hidden_option("--debug", "-d", is_flag=True),
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"])),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid"),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True),
])
"""Legacy options available directly on the "octoprint" command in earlier versions.
Kept available for reasons of backwards compatibility, but hidden from the
generated help pages."""
#~~ "octoprint" command, merges server_commands and plugin_commands groups
from .server import server_commands
from .plugins import plugin_commands
from .dev import dev_commands
from .client import client_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__)
@click.pass_context
def octo(ctx, debug, host, port, logging, daemon, pid, allow_root):
if ctx.invoked_subcommand is None:
# We have to support calling the octoprint command without any
# sub commands to remain backwards compatible.
#
# But better print a message to inform people that they should
# use the sub commands instead.
if daemon:
click.echo("Daemon operation via \"octoprint --daemon "
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, debug=debug, pid=pid, daemon=daemon, allow_root=allow_root)
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
from octoprint.cli.server import serve_command
ctx.invoke(serve_command, debug=debug, host=host, port=port, logging=logging, allow_root=allow_root)
+176
View File
@@ -0,0 +1,176 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import json
import octoprint_client
from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options
from octoprint import init_settings
class JsonStringParamType(click.ParamType):
name = "json"
def convert(self, value, param, ctx):
try:
return json.loads(value)
except:
self.fail("%s is not a valid json string" % value, param, ctx)
@click.group()
def client_commands():
pass
@client_commands.group("client", context_settings=dict(ignore_unknown_options=True))
@click.option("--host", "-h", type=click.STRING)
@click.option("--port", "-p", type=click.INT)
@click.option("--httpuser", type=click.STRING)
@click.option("--httppass", type=click.STRING)
@click.option("--https", is_flag=True)
@click.option("--prefix", type=click.STRING)
@pass_octoprint_ctx
def client(obj, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
obj.settings = init_settings(obj.basedir, obj.configfile)
octoprint_client.init_client(obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix)
def log_response(response, status_code=True, body=True, headers=False):
if status_code:
click.echo("Status Code: {}".format(response.status_code))
if headers:
for header, value in response.headers.items():
click.echo("{}: {}".format(header, value))
click.echo()
if body:
click.echo(response.text)
@client.command("get")
@click.argument("path")
def get(path):
"""Performs a GET request against the specified server path."""
r = octoprint_client.get(path)
log_response(r)
@client.command("post_json")
@click.argument("path")
@click.argument("data", type=JsonStringParamType())
def post_json(path, data):
"""POSTs JSON data to the specified server path."""
r = octoprint_client.post_json(path, data)
log_response(r)
@client.command("patch_json")
@click.argument("path")
@click.argument("data", type=JsonStringParamType())
def patch_json(path, data):
"""PATCHes JSON data to the specified server path."""
r = octoprint_client.patch(path, data, encoding="json")
log_response(r)
@client.command("post_from_file")
@click.argument("path")
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option("--json", is_flag=True)
@click.option("--yaml", is_flag=True)
def post_from_file(path, file_path, json_flag, yaml_flag):
"""POSTs JSON data to the specified server path."""
if json_flag or yaml_flag:
if json_flag:
with open(file_path, "rb") as fp:
data = json.load(fp)
else:
import yaml
with open(file_path, "rb") as fp:
data = yaml.safe_load(fp)
r = octoprint_client.post_json(path, data)
else:
with open(file_path, "rb") as fp:
data = fp.read()
r = octoprint_client.post(path, data)
log_response(r)
@client.command("command")
@click.argument("path")
@click.argument("command")
@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int]))
@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float]))
@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool]))
def command(path, command, str_params, int_params, float_params, bool_params):
"""Sends a JSON command to the specified server path."""
data = dict()
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = octoprint_client.post_command(path, command, additional=data)
log_response(r, body=False)
@client.command("upload")
@click.argument("path")
@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True))
@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode]))
@click.option("--file-name", type=click.STRING)
@click.option("--content-type", type=click.STRING)
def upload(path, file_path, params, file_name, content_type):
"""Uploads the specified file to the specified server path."""
data = dict()
for param in params:
data[param[0]] = param[1]
r = octoprint_client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type)
log_response(r)
@client.command("delete")
@click.argument("path")
def delete(path):
"""Sends a DELETE request to the specified server path."""
r = octoprint_client.delete(path)
log_response(r)
@client.command("listen")
def listen():
def on_connect(ws):
click.echo(">>> Connected!")
def on_close(ws):
click.echo(">>> Connection closed!")
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_heartbeat(ws):
click.echo("<3")
def on_message(ws, message_type, message_payload):
click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload)))
socket = octoprint_client.connect_socket(on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_heartbeat=on_heartbeat,
on_message=on_message)
click.echo(">>> Waiting for client to exit")
try:
socket.wait()
finally:
click.echo(">>> Goodbye...")
+235
View File
@@ -0,0 +1,235 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
class OctoPrintDevelCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
sep = ":"
groups = ("plugin",)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
from octoprint.util.commandline import CommandlineCaller
from functools import partial
def log_util(f):
def log(*lines):
for line in lines:
f(line)
return log
self.command_caller = CommandlineCaller()
self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x)))
self.command_caller.on_log_stdout = log_util(click.echo)
self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True))
def _get_prefix_methods(self, method_prefix):
for name in [x for x in dir(self) if x.startswith(method_prefix)]:
method = getattr(self, name)
yield method
def _get_commands_from_prefix_methods(self, method_prefix):
for method in self._get_prefix_methods(method_prefix):
result = method()
if result is not None and isinstance(result, click.Command):
yield result
def _get_commands(self):
result = dict()
for group in self.groups:
for command in self._get_commands_from_prefix_methods("{}_".format(group)):
result[group + self.sep + command.name] = command
return result
def list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
def get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
import contextlib
@contextlib.contextmanager
def custom_cookiecutter_config(config):
"""
Allows overriding cookiecutter's user config with a custom dict
with fallback to the original data.
"""
from octoprint.util import fallback_dict
original_get_user_config = cookiecutter.main.get_user_config
try:
def f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
If a setting is available in the provided options (read from the CLI)
that will be used, otherwise the user will be prompted for a value
via click.
"""
original_prompt_for_config = cookiecutter.main.prompt_for_config
def custom_prompt_for_config(context, no_input=False):
import cookiecutter.prompt
cookiecutter_dict = {}
env = cookiecutter.prompt.Environment()
for key, raw in context['cookiecutter'].items():
if key in options:
val = options[key]
else:
raw = raw if isinstance(raw, basestring) else str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
if not no_input:
val = click.prompt(key, default=val)
cookiecutter_dict[key] = val
return cookiecutter_dict
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
@click.command("new")
@click.option("--name", "-n", help="The name of the plugin")
@click.option("--package", "-p", help="The plugin package")
@click.option("--author", "-a", help="The plugin author's name")
@click.option("--email", "-e", help="The plugin author's mail address")
@click.option("--license", "-l", help="The plugin's license")
@click.option("--description", "-d", help="The plugin's description")
@click.option("--homepage", help="The plugin's homepage URL")
@click.option("--source", "-s", help="The URL to the plugin's source")
@click.option("--installurl", "-i", help="The plugin's install URL")
@click.argument("identifier", required=False)
def command(name, package, author, email, description, license, homepage, source, installurl, identifier):
"""Creates a new plugin based on the OctoPrint Plugin cookiecutter template."""
from octoprint.util import tempdir
# deleting a git checkout folder might run into access errors due
# to write-protected sub folders, so we use a custom onerror handler
# that tries to fix such permissions
def onerror(func, path, exc_info):
"""Originally from http://stackoverflow.com/a/2656405/2028598"""
import stat
import os
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
with tempdir(onerror=onerror) as path:
custom = dict(cookiecutters_dir=path)
with custom_cookiecutter_config(custom):
raw_options = dict(
plugin_identifier=identifier,
plugin_package=package,
plugin_name=name,
full_name=author,
email=email,
plugin_description=description,
plugin_license=license,
plugin_homepage=homepage,
plugin_source=source,
plugin_installurl=installurl
)
options = dict((k, v) for k, v in raw_options.items() if v is not None)
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin")
return command
def plugin_install(self):
@click.command("install")
@click.option("--path", help="Path of the local plugin development folder to install")
def command(path):
"""
Installs the local plugin in development mode.
Note: This can NOT be used to install plugins from remote locations
such as the plugin repository! It is strictly for local development
of plugins, to ensure the plugin is installed (editable) into the
same python environment that OctoPrint is installed under.
"""
import os
import sys
if not path:
path = os.getcwd()
# check if this really looks like a plugin
if not os.path.isfile(os.path.join(path, "setup.py")):
click.echo("This doesn't look like an OctoPrint plugin folder")
sys.exit(1)
self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path)
return command
def plugin_uninstall(self):
from octoprint.util.pip import PipCaller
pip_command = PipCaller.autodetect_pip()
if pip_command is None:
return
@click.command("uninstall")
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
lower_name = name.lower()
if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"):
click.echo("This doesn't look like an OctoPrint plugin name")
sys.exit(1)
call = [pip_command, "uninstall", "--yes", name]
self.command_caller.call(call)
return command
@click.group()
def dev_commands():
pass
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
def dev():
"""Additional commands for development tasks."""
pass
+99
View File
@@ -0,0 +1,99 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
from octoprint.cli import pass_octoprint_ctx, OctoPrintContext
#~~ "octoprint plugin:command" commands
class OctoPrintPluginCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
.. attribute:: settings
The global :class:`~octoprint.settings.Settings` instance.
.. attribute:: plugin_manager
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
sep = ":"
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
self.settings = None
self.plugin_manager = None
self.hooks = dict()
self._logger = logging.getLogger(__name__)
self._initialized = False
def _initialize(self, ctx):
if self._initialized:
return
if ctx.obj is None:
ctx.obj = OctoPrintContext()
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import init_settings, init_pluginsystem
self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile)
self.plugin_manager = init_pluginsystem(self.settings)
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
self._initialized = True
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
import collections
result = collections.OrderedDict()
for name, hook in self.hooks.items():
try:
commands = hook(self, pass_octoprint_ctx)
for command in commands:
if not isinstance(command, click.Command):
self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
continue
result[name + self.sep + command.name] = command
except:
self._logger.exception("Error while retrieving cli commants for plugin {}".format(name))
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN)
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
"""Additional commands provided by plugins."""
pass
+131
View File
@@ -0,0 +1,131 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
import sys
from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options
def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity):
"""Initializes the environment and starts up the server."""
from octoprint import init_platform, __display_version__
def log_startup(_):
logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__))
from octoprint import urllib3_ssl
if not urllib3_ssl:
logging.getLogger("octoprint.server")\
.warn("requests/urllib3 will run in an insecure SSL environment. "
"You might see corresponding warnings logged later "
"(\"InsecurePlatformWarning\"). It is recommended to either "
"update to a Python version >= 2.7.9 or alternatively "
"install PyOpenSSL plus its dependencies. For details see "
"https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl")
settings, _, plugin_manager = init_platform(basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
after_logging=log_startup)
from octoprint.server import Server
octoprint_server = Server(settings=settings, plugin_manager=plugin_manager, host=host, port=port, debug=debug, allow_root=allow_root)
octoprint_server.run()
#~~ server options
server_options = bulk_options([
click.option("--host", type=click.STRING,
help="Specify the host on which to bind the server."),
click.option("--port", type=click.INT,
help="Specify the port on which to bind the server."),
click.option("--logging", type=click.Path(),
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, help="Enable debug mode"),
])
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``,
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
#~~ "octoprint serve" and "octoprint daemon" commands
@click.group()
@pass_octoprint_ctx
def server_commands(obj):
pass
@server_commands.command(name="serve")
@server_options
@standard_options(hidden=True)
@pass_octoprint_ctx
def serve_command(obj, host, port, logging, allow_root, debug):
"""Starts the OctoPrint server."""
run_server(obj.basedir, obj.configfile, host, port, debug,
allow_root, logging, obj.verbosity)
@server_commands.command(name="daemon")
@click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid",
help="Pidfile to use for daemonizing.")
@server_options
@standard_options(hidden=True)
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@pass_octoprint_ctx
def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, command):
"""
Starts, stops or restarts in daemon mode.
Please note that daemon mode is only supported under Linux right now.
"""
if sys.platform == "darwin" or sys.platform == "win32":
click.echo("Sorry, daemon mode is only supported under Linux right now",
file=sys.stderr)
sys.exit(2)
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
sys.exit(1)
from octoprint.daemon import Daemon
class OctoPrintDaemon(Daemon):
def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity):
Daemon.__init__(self, pidfile)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity)
octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile,
host, port, debug, allow_root, logging, octoprint_ctx.verbosity)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
+121 -69
View File
@@ -1,46 +1,65 @@
# coding=utf-8
"""
Generic linux daemon base class for python 3.x
Generic linux daemon base class
Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35
"""
from __future__ import (print_function, absolute_import)
import sys, os, time, signal
class Daemon:
"""A generic daemon class.
"""
A generic daemon class.
Usage: subclass the daemon class and override the run() method."""
Usage: subclass the daemon class and override the run() method.
def __init__(self, pidfile): self.pidfile = pidfile
def daemonize(self):
"""Deamonize class. UNIX double fork mechanism."""
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
try:
pid = os.fork()
def __init__(self, pidfile):
self.pidfile = pidfile
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
self._double_fork()
self._redirect_io()
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
# register listener for SIGTERM
signal.signal(signal.SIGTERM, self._on_sigterm)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: {0}\n'.format(err))
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
sys.exit(1)
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(002)
# do second fork
try:
pid = os.fork()
if pid > 0:
# decouple from parent environment
os.chdir('/')
os.setsid()
os.umask(002)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed: {0}\n'.format(err))
sys.exit(1)
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
sys.exit(1)
def _redirect_io(self):
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
@@ -51,57 +70,39 @@ class Daemon:
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
# write pidfile
pid = str(os.getpid())
with open(self.pidfile,'w+') as f:
f.write(pid + '\n')
# register listener for SIGTERM
signal.signal(signal.SIGTERM, self.term)
def term(self, _signo, _stack_frame):
os.remove(self.pidfile)
def _on_sigterm(self, _signo, _stack_frame):
"""Signal handler for SIGTERM, deletes the pidfile."""
self.remove_pidfile()
sys.exit(0)
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
pid = self.get_pid()
if pid:
message = "pidfile {0} already exist. " + \
"Daemon already running?\n"
sys.stderr.write(message.format(self.pidfile))
self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile))
sys.exit(1)
self.echo("Starting daemon...")
# Start the daemon
self.daemonize()
self._daemonize()
self.run()
def stop(self):
def stop(self, check_running=True):
"""Stop the daemon."""
# Get the pid from the pidfile
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
pid = self.get_pid()
if not pid:
message = "pidfile {0} does not exist. " + \
"Daemon not running?\n"
sys.stderr.write(message.format(self.pidfile))
return # not an error in a restart
if not check_running:
return
self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile))
sys.exit(1)
# Try killing the daemon process
self.echo("Stopping daemon...")
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
@@ -109,20 +110,71 @@ class Daemon:
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
self.remove_pidfile()
else:
print (str(err.args))
self.error(e)
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop()
self.stop(check_running=False)
self.start()
def status(self):
"""Prints the daemon status."""
if self.is_running():
self.echo("Daemon is running")
else:
self.echo("Daemon is not running")
def is_running(self):
"""Check if a process is running under the specified pid."""
pid = self.get_pid()
if pid is None:
return False
try:
os.kill(pid, 0)
except OSError:
try:
self.remove_pidfile()
except:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
return True
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
return pid
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with open(self.pidfile,'w+') as f:
f.write(str(pid) + '\n')
def remove_pidfile(self):
"""Removes the pidfile."""
if os.path.isfile(self.pidfile):
os.remove(self.pidfile)
def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
It will be called after the process has been daemonized by
start() or restart()."""
raise NotImplementedError()
@classmethod
def echo(cls, line):
print(line)
@classmethod
def error(cls, line):
print(line, stream=sys.stderr)
+5
View File
@@ -28,9 +28,14 @@ class Events(object):
STARTUP = "Startup"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
+22
View File
@@ -340,9 +340,15 @@ class FileManager(object):
def get_busy_files(self):
return self._slicing_jobs.keys()
def file_in_path(self, destination, path, file):
return self._storage(destination).file_in_path(path, file)
def file_exists(self, destination, path):
return self._storage(destination).file_exists(path)
def folder_exists(self, destination, path):
return self._storage(destination).folder_exists(path)
def list_files(self, destinations=None, path=None, filter=None, recursive=None):
if not destinations:
destinations = self._storage_managers.keys()
@@ -385,6 +391,14 @@ class FileManager(object):
self._storage(destination).remove_file(path)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_file(self, destination, source, dst):
self._storage(destination).copy_file(source, dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_file(self, destination, source, dst):
self._storage(destination).move_file(source, dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def add_folder(self, destination, path, ignore_existing=True):
folder_path = self._storage(destination).add_folder(path, ignore_existing=ignore_existing)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
@@ -394,6 +408,14 @@ class FileManager(object):
self._storage(destination).remove_folder(path, recursive=recursive)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def copy_folder(self, destination, source, dst):
self._storage(destination).copy_folder(source, dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def move_folder(self, destination, source, dst):
self._storage(destination).move_folder(source, dst)
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def get_metadata(self, destination, path):
return self._storage(destination).get_metadata(path)
+285 -76
View File
@@ -9,7 +9,11 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import pylru
import tempfile
import shutil
from octoprint.util import atomic_write
from contextlib import contextmanager
from copy import deepcopy
import octoprint.filemanager
@@ -35,6 +39,15 @@ class StorageInterface(object):
return
yield
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
@@ -43,6 +56,14 @@ class StorageInterface(object):
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder 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
@@ -114,6 +135,24 @@ class StorageInterface(object):
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copys the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
"""
Adds the file ``file_object`` as ``path``
@@ -138,6 +177,24 @@ class StorageInterface(object):
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copys the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
@@ -279,6 +336,25 @@ class StorageInterface(object):
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
class LocalFileStorage(StorageInterface):
"""
@@ -304,13 +380,18 @@ class LocalFileStorage(StorageInterface):
if not os.path.exists(self.basefolder) and create:
os.makedirs(self.basefolder)
if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder):
raise RuntimeError("{basefolder} is not a valid directory".format(**locals()))
raise StorageError("{basefolder} is not a valid directory".format(**locals()), code=StorageError.INVALID_DIRECTORY)
import threading
self._metadata_lock = threading.Lock()
self._metadata_lock_mutex = threading.RLock()
self._metadata_locks = dict()
self._metadata_cache = pylru.lrucache(10)
from slugify import Slugify
self._slugify = Slugify()
self._slugify.safe_chars = "-_.() "
self._old_metadata = None
self._initialize_metadata()
@@ -376,11 +457,22 @@ class LocalFileStorage(StorageInterface):
for sub_entry in self._analysis_backlog_generator(absolute_path):
yield self.join_path(entry, sub_entry[0]), sub_entry[1], sub_entry[2]
def file_in_path(self, path, filepath):
filepath = self.sanitize_path(filepath)
path = self.sanitize_path(path)
return filepath.startswith(path)
def file_exists(self, path):
path, name = self.sanitize(path)
file_path = os.path.join(path, name)
return os.path.exists(file_path) and os.path.isfile(file_path)
def folder_exists(self, path):
path, name = self.sanitize(path)
folder_path = os.path.join(path, name)
return os.path.exists(folder_path) and os.path.isdir(folder_path)
def list_files(self, path=None, filter=None, recursive=True):
if path:
path = self.sanitize_path(path)
@@ -394,7 +486,7 @@ class LocalFileStorage(StorageInterface):
folder_path = os.path.join(path, name)
if os.path.exists(folder_path):
if not ignore_existing:
raise RuntimeError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()))
raise StorageError("{sanitized_foldername} does already exist in {virtual_path}".format(**locals()), code=StorageError.ALREADY_EXISTS)
else:
os.mkdir(folder_path)
@@ -411,25 +503,69 @@ class LocalFileStorage(StorageInterface):
if ".metadata.yaml" in contents:
contents.remove(".metadata.yaml")
if contents and not recursive:
raise RuntimeError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()))
raise StorageError("{sanitized_foldername} in {virtual_path} is not empty".format(**locals()), code=StorageError.NOT_EMPTY)
import shutil
shutil.rmtree(folder_path)
self._delete_metadata(folder_path)
def _get_source_destination_data(self, source, destination):
"""Prepares data dicts about source and destination for copy/move."""
source_path, source_name = self.sanitize(source)
destination_path, destination_name = self.sanitize(destination)
source_fullpath = os.path.join(source_path, source_name)
destination_fullpath = os.path.join(destination_path, destination_name)
if not os.path.exists(source_fullpath):
raise StorageError("{} in {} does not exist".format(source_name, source_path), code=StorageError.INVALID_SOURCE)
if not os.path.isdir(destination_path):
raise StorageError("Destination path {} does not exist or is not a folder".format(destination_path), code=StorageError.INVALID_DESTINATION)
if os.path.exists(destination_fullpath):
raise StorageError("{} does already exist in {}".format(destination_name, destination_path), code=StorageError.INVALID_DESTINATION)
source_data = dict(
path=source_path,
name=source_name,
fullpath=source_fullpath,
)
destination_data = dict(
path=destination_path,
name=destination_name,
fullpath=destination_fullpath,
)
return source_data, destination_data
def copy_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
try:
shutil.copytree(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
def move_folder(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
try:
shutil.move(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
self._delete_metadata(source_data["fullpath"])
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False):
path, name = self.sanitize(path)
if not octoprint.filemanager.valid_file_type(name):
raise RuntimeError("{name} is an unrecognized file type".format(**locals()))
metadata = self._get_metadata(path)
if not metadata:
metadata = dict()
raise StorageError("{name} is an unrecognized file type".format(**locals()), code=StorageError.INVALID_FILE)
file_path = os.path.join(path, name)
if os.path.exists(file_path) and not os.path.isfile(file_path):
raise RuntimeError("{name} does already exist in {path} and is not a file".format(**locals()))
raise StorageError("{name} does already exist in {path} and is not a file".format(**locals()), code=StorageError.ALREADY_EXISTS)
if os.path.exists(file_path) and not allow_overwrite:
raise RuntimeError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()))
raise StorageError("{name} does already exist in {path} and overwriting is prohibited".format(**locals()), code=StorageError.ALREADY_EXISTS)
# make sure folders exist
if not os.path.exists(path):
@@ -440,13 +576,10 @@ class LocalFileStorage(StorageInterface):
# save the file's hash to the metadata of the folder
file_hash = self._create_hash(file_path)
if not name in metadata or not "hash" in metadata[name] or metadata[name]["hash"] != file_hash:
# make sure to create a new metadata entry if we've never seen that file with that content before
file_metadata = dict(
hash=file_hash
)
metadata[name] = file_metadata
self._save_metadata(path, metadata)
metadata = self._get_metadata_entry(path, name, default=dict())
if not "hash" in metadata or metadata["hash"] != file_hash:
metadata["hash"] = file_hash
self._update_metadata_entry(path, name, metadata)
# process any links that were also provided for adding to the file
if not links:
@@ -465,45 +598,50 @@ class LocalFileStorage(StorageInterface):
def remove_file(self, path):
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
file_path = os.path.join(path, name)
if not os.path.exists(file_path):
return
if not os.path.isfile(file_path):
raise RuntimeError("{name} in {path} is not a file".format(**locals()))
raise StorageError("{name} in {path} is not a file".format(**locals()), code=StorageError.INVALID_FILE)
try:
os.remove(file_path)
except Exception as e:
raise RuntimeError("Could not delete {name} in {path}".format(**locals()), e)
raise StorageError("Could not delete {name} in {path}".format(**locals()), cause=e)
if name in metadata:
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
if not "links" in m:
continue
for link in m["links"]:
if "rel" in link and "hash" in link and (link["rel"] == "model" or link["rel"] == "machinecode") and link["hash"] == hash:
m["links"].remove(link)
del metadata[name]
self._save_metadata(path, metadata)
self._remove_metadata_entry(path, name)
def copy_file(self, source, destination):
source_data, destination_data = self._get_source_destination_data(source, destination)
try:
shutil.copy2(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not copy %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"])
def move_file(self, source, destination, allow_overwrite=False):
source_data, destination_data = self._get_source_destination_data(source, destination)
try:
shutil.move(source_data["fullpath"], destination_data["fullpath"])
except Exception as e:
raise StorageError("Could not move %s in %s to %s in %s" % (source_data["name"], source_data["path"], destination_data["name"], destination_data["path"]), cause=e)
self._copy_metadata_entry(source_data["path"], source_data["name"],
destination_data["path"], destination_data["name"],
delete_source=True)
def get_metadata(self, path):
path, name = self.sanitize(path)
metadata = self._get_metadata(path)
if name in metadata:
return metadata[name]
else:
return None
return self._get_metadata_entry(path, name)
def get_link(self, path, rel):
path, name = self.sanitize(path)
return self._get_links(name, path, rel)
def add_link(self, path, rel, data):
path, name = self.sanitize(path)
self._add_links(name, path, [(rel, data)])
@@ -609,9 +747,9 @@ class LocalFileStorage(StorageInterface):
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 ``_``.
Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\``. Otherwise
slugifies the given ``name`` by converting it to ASCII, leaving ``-``, ``_``, ``.``,
``(``, and ``)`` as is.
"""
if name is None:
return None
@@ -619,11 +757,7 @@ class LocalFileStorage(StorageInterface):
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
return self._slugify(name).replace(" ", "_")
def sanitize_path(self, path):
"""
@@ -927,13 +1061,29 @@ class LocalFileStorage(StorageInterface):
# folder recursion
elif os.path.isdir(entry_path) and recursive:
sub_result = self._list_folder(entry_path, filter=filter)
result[entry] = dict(
sub_result = self._list_folder(entry_path, filter=filter, recursive=recursive)
entry_data = dict(
name=entry,
type="folder",
children=sub_result
)
if not filter or filter(entry, entry_data):
def get_size():
total_size = 0
for element in entry_data["children"].itervalues():
if "size" in element:
total_size += element["size"]
return total_size
# only add folders passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
extended_entry_data["size"] = get_size()
result[entry] = extended_entry_data
# TODO recreate links if we have metadata less entries
# save metadata
@@ -980,13 +1130,53 @@ class LocalFileStorage(StorageInterface):
return hash.hexdigest()
def _get_metadata(self, path):
if path in self._metadata_cache:
return self._metadata_cache[path]
def _get_metadata_entry(self, path, name, default=None):
with self._get_metadata_lock(path):
metadata = self._get_metadata(path)
return metadata.get(name, default)
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
with self._metadata_lock:
def _remove_metadata_entry(self, path, name):
with self._get_metadata_lock(path):
metadata = self._get_metadata(path)
if not name in metadata:
return
if "hash" in metadata[name]:
hash = metadata[name]["hash"]
for m in metadata.values():
if not "links" in m:
continue
links_hash = lambda link: "hash" in link and link["hash"] == hash and "rel" in link and (link["rel"] == "model" or link["rel"] == "machinecode")
m["links"] = [link for link in m["links"] if not links_hash(link)]
del metadata[name]
self._save_metadata(path, metadata)
def _update_metadata_entry(self, path, name, data):
with self._get_metadata_lock(path):
metadata = self._get_metadata(path)
metadata[name] = data
self._save_metadata(path, metadata)
def _copy_metadata_entry(self, source_path, source_name, destination_path, destination_name, delete_source=False):
with self._get_metadata_lock(source_path):
source_data = self._get_metadata_entry(source_path, source_name, default=dict())
if not source_data:
return
if delete_source:
self._remove_metadata_entry(source_path, source_name)
with self._get_metadata_lock(destination_path):
self._update_metadata_entry(destination_path, destination_name, source_data)
def _get_metadata(self, path):
with self._get_metadata_lock(path):
if path in self._metadata_cache:
return deepcopy(self._metadata_cache[path])
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
with open(metadata_path) as f:
try:
import yaml
@@ -994,30 +1184,49 @@ class LocalFileStorage(StorageInterface):
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
else:
self._metadata_cache[path] = metadata
self._metadata_cache[path] = deepcopy(metadata)
return metadata
return dict()
return dict()
def _save_metadata(self, path, metadata):
metadata_path = os.path.join(path, ".metadata.yaml")
with self._metadata_lock:
with self._get_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.yaml")
try:
import yaml
import shutil
file_obj = tempfile.NamedTemporaryFile(delete=False)
try:
yaml.safe_dump(metadata, stream=file_obj, default_flow_style=False, indent=" ", allow_unicode=True)
file_obj.close()
shutil.move(file_obj.name, metadata_path)
finally:
try:
if os.path.exists(file_obj.name):
os.remove(file_obj.name)
except Exception as e:
self._logger.warn("Could not delete file {}: {}".format(file_obj.name, str(e)))
with atomic_write(metadata_path) as f:
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
else:
self._metadata_cache[path] = metadata
self._metadata_cache[path] = deepcopy(metadata)
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
try:
os.remove(metadata_path)
except:
self._logger.exception("Error while deleting .metadata.yaml from {path}".format(**locals()))
if path in self._metadata_cache:
del self._metadata_cache[path]
@contextmanager
def _get_metadata_lock(self, path):
with self._metadata_lock_mutex:
if path not in self._metadata_locks:
import threading
self._metadata_locks[path] = (0, threading.RLock())
counter, lock = self._metadata_locks[path]
counter += 1
self._metadata_locks[path] = (counter, lock)
yield lock
counter = self._metadata_locks[path][0]
counter -= 1
if counter <= 0:
del self._metadata_locks[path]
else:
self._metadata_locks[path] = (counter, lock)
+48 -10
View File
@@ -22,7 +22,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import logging
from octoprint.settings import settings
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
from octoprint.plugin.types import *
@@ -44,7 +44,7 @@ def _validate_plugin(phase, plugin_info):
setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks)
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -87,9 +87,12 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
else:
if init:
if settings is None:
settings = s()
if plugin_folders is None:
plugin_folders = (
settings().getBaseFolder("plugins"),
settings.getBaseFolder("plugins"),
(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True)
)
if plugin_types is None:
@@ -103,11 +106,13 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
EventHandlerPlugin,
SlicerPlugin,
AppPlugin,
ProgressPlugin]
ProgressPlugin,
WizardPlugin,
UiPlugin]
if plugin_entry_points is None:
plugin_entry_points = "octoprint.plugin"
if plugin_disabled_list is None:
plugin_disabled_list = settings().get(["plugins", "_disabled"])
plugin_disabled_list = settings.get(["plugins", "_disabled"])
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = [
"octoprint.server.http"
@@ -134,7 +139,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
return _instance
def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None, settings=None):
"""
Factory method for creating a :class:`PluginSettings` instance.
@@ -143,15 +148,48 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr
defaults (dict): The default settings for the plugin.
get_preprocessors (dict): The getter preprocessors for the plugin.
set_preprocessors (dict): The setter preprocessors for the plugin.
settings (octoprint.settings.Settings): The settings instance to use.
Returns:
PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
settings
"""
return PluginSettings(settings(), plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors)
if settings is None:
settings = s()
return PluginSettings(settings, plugin_key, defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None):
def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
"""
Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance.
Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance.
Arguments:
plugin_key (string): The plugin identifier for which to create the settings instance.
implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance.
settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings.
Returns:
PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's
settings, or `None` if the provided `instance` was not a class:`SettingsPlugin`
"""
if not isinstance(instance, SettingsPlugin):
return None
try:
defaults = instance.get_settings_defaults()
get_preprocessors, set_preprocessors = instance.get_settings_preprocessors()
except:
logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key))
return None
return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -197,7 +235,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if kwargs is None:
kwargs = dict()
plugins = plugin_manager().get_implementations(*types)
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if hasattr(plugin, method):
try:
@@ -330,7 +368,7 @@ class PluginSettings(object):
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
remove =("remove", prefix_path_in_args)
remove =("remove", prefix_path_in_args, lambda x: x)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
+175 -25
View File
@@ -12,6 +12,12 @@ way and could be extracted into a separate Python module in the future.
.. autoclass:: Plugin
:members:
.. autoclass:: RestartNeedingPlugin
:members:
.. autoclass:: SortablePlugin
:members:
"""
from __future__ import absolute_import
@@ -23,7 +29,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import imp
from collections import defaultdict, namedtuple
from collections import defaultdict, namedtuple, OrderedDict
import logging
import pkg_resources
@@ -127,6 +133,7 @@ class PluginInfo(object):
self.enabled = True
self.bundled = False
self.loaded = False
self.managable = True
self._name = name
self._version = version
@@ -449,10 +456,11 @@ class PluginManager(object):
self.enabled_plugins = dict()
self.disabled_plugins = dict()
self.plugin_hooks = defaultdict(list)
self.plugin_implementations = dict()
self.plugin_implementations_by_type = defaultdict(list)
self._plugin_hooks = defaultdict(list)
self.implementation_injects = dict()
self.implementation_inject_factories = []
self.implementation_pre_inits = []
@@ -468,14 +476,35 @@ class PluginManager(object):
self.marked_plugins = defaultdict(list)
self._python_install_dir = None
self._python_virtual_env = False
self._detect_python_environment()
self.reload_plugins(startup=True, initialize_implementations=False)
def _detect_python_environment(self):
from distutils.command.install import install as cmd_install
from distutils.dist import Distribution
import sys
cmd = cmd_install(Distribution())
cmd.finalize_options()
self._python_install_dir = cmd.install_lib
self._python_prefix = sys.prefix
self._python_virtual_env = hasattr(sys, "real_prefix") \
or (hasattr(sys, "base_prefix") and sys.prefix != sys.base_prefix)
@property
def plugins(self):
plugins = dict(self.enabled_plugins)
plugins.update(self.disabled_plugins)
return plugins
@property
def plugin_hooks(self):
return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
def find_plugins(self, existing=None, ignore_uninstalled=True):
if existing is None:
existing = dict(self.plugins)
@@ -492,12 +521,13 @@ class PluginManager(object):
result = dict()
for folder in folders:
readonly = False
flagged_readonly = False
if isinstance(folder, (list, tuple)):
if len(folder) == 2:
folder, readonly = folder
folder, flagged_readonly = folder
else:
continue
actual_readonly = not os.access(folder, os.W_OK)
if not os.path.exists(folder):
self.logger.warn("Plugin folder {folder} could not be found, skipping it".format(folder=folder))
@@ -520,8 +550,8 @@ class PluginManager(object):
plugin = self._import_plugin_from_module(key, folder=folder)
if plugin:
plugin.origin = FolderOrigin("folder", folder)
if readonly:
plugin.bundled = True
plugin.managable = not flagged_readonly and not actual_readonly
plugin.bundled = flagged_readonly
plugin.enabled = False
@@ -532,9 +562,18 @@ class PluginManager(object):
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
result = dict()
# let's make sure we have a current working set
# let's make sure we have a current working set ...
working_set = pkg_resources.WorkingSet()
# ... including the user's site packages
import site
import sys
if site.ENABLE_USER_SITE:
if not site.USER_SITE in working_set.entries:
working_set.add_entry(site.USER_SITE)
if not site.USER_SITE in sys.path:
site.addsitedir(site.USER_SITE)
if not isinstance(groups, (list, tuple)):
groups = [groups]
@@ -567,6 +606,16 @@ class PluginManager(object):
plugin = self._import_plugin_from_module(key, **kwargs)
if plugin:
plugin.origin = EntryPointOrigin("entry_point", group, module_name, package_name, version)
# plugin is manageable if its location is writable and OctoPrint
# is either not running from a virtual env or the plugin is
# installed in that virtual env - the virtual env's pip will not
# allow us to uninstall stuff that is installed outside
# of the virtual env, so this check is necessary
plugin.managable = os.access(plugin.location, os.W_OK) \
and (not self._python_virtual_env
or plugin.location.startswith(self._python_prefix))
plugin.enabled = False
result[key] = plugin
@@ -637,15 +686,24 @@ class PluginManager(object):
hooks=sum(map(lambda x: len(x), self.plugin_hooks.values()))
))
def mark_plugin(self, name, uninstalled=None):
def mark_plugin(self, name, **kwargs):
if not name in self.plugins:
self.logger.warn("Trying to mark an unknown plugin {name}".format(**locals()))
self.logger.debug("Trying to mark an unknown plugin {name}".format(**locals()))
if uninstalled is not None:
if uninstalled and not name in self.marked_plugins["uninstalled"]:
self.marked_plugins["uninstalled"].append(name)
elif not uninstalled and name in self.marked_plugins["uninstalled"]:
self.marked_plugins["uninstalled"].remove(name)
for key, value in kwargs.items():
if value is None:
continue
if value and not name in self.marked_plugins[key]:
self.marked_plugins[key].append(name)
elif not value and name in self.marked_plugins[key]:
self.marked_plugins[key].remove(name)
def is_plugin_marked(self, name, key):
if not name in self.plugins:
return False
return name in self.marked_plugins[key]
def load_plugin(self, name, plugin=None, startup=False, initialize_implementation=True):
if not name in self.plugins:
@@ -779,8 +837,15 @@ class PluginManager(object):
plugin.hotchangeable = self.is_restart_needing_plugin(plugin)
# evaluate registered hooks
for hook, callback in plugin.hooks.items():
self.plugin_hooks[hook].append((name, callback))
for hook, definition in plugin.hooks.items():
try:
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
self._plugin_hooks[hook].append((order, name, callback))
self._sort_hooks(hook)
# evaluate registered implementation
if plugin.implementation:
@@ -791,9 +856,16 @@ class PluginManager(object):
self.plugin_implementations[name] = plugin.implementation
def _deactivate_plugin(self, name, plugin):
for hook, callback in plugin.hooks.items():
for hook, definition in plugin.hooks.items():
try:
self.plugin_hooks[hook].remove((name, callback))
callback, order = self._get_callback_and_order(definition)
except ValueError as e:
self.logger.warn("There is something wrong with the hook definition {} for plugin {}: {}".format(definition, name, str(e)))
continue
try:
self._plugin_hooks[hook].remove((order, name, callback))
self._sort_hooks(hook)
except ValueError:
# that's ok, the plugin was just not registered for the hook
pass
@@ -1017,9 +1089,13 @@ class PluginManager(object):
if not hook in self.plugin_hooks:
return dict()
return {hook[0]: hook[1] for hook in self.plugin_hooks[hook]}
def get_implementations(self, *types):
result = OrderedDict()
for h in self.plugin_hooks[hook]:
result[h[0]] = h[1]
return result
def get_implementations(self, *types, **kwargs):
"""
Get all mixin implementations that implement *all* of the provided ``types``.
@@ -1030,6 +1106,8 @@ class PluginManager(object):
list: A list of all found implementations
"""
sorting_context = kwargs.get("sorting_context", None)
result = None
for t in types:
@@ -1040,10 +1118,28 @@ class PluginManager(object):
result = result.intersection(implementations)
if result is None:
return dict()
return [impl[1] for impl in result]
return []
def get_filtered_implementations(self, f, *types):
def sort_func(impl):
sorting_value = None
if sorting_context is not None and isinstance(impl[1], SortablePlugin):
try:
sorting_value = impl[1].get_sorting_key(sorting_context)
except:
self.logger.exception("Error while trying to retrieve sorting order for plugin {}".format(impl[0]))
if sorting_value is not None:
try:
int(sorting_value)
except ValueError:
self.logger.warn("The order value returned by {} for sorting context {} is not a valid integer, ignoring it".format(impl[0], sorting_context))
sorting_value = None
return sorting_value is None, sorting_value, impl[0]
return [impl[1] for impl in sorted(result, key=sort_func)]
def get_filtered_implementations(self, f, *types, **kwargs):
"""
Get all mixin implementation that implementat *all* of the provided ``types`` and match the provided filter `f`.
@@ -1056,7 +1152,7 @@ class PluginManager(object):
"""
assert callable(f)
implementations = self.get_implementations(*types)
implementations = self.get_implementations(*types, sorting_context=kwargs.get("sorting_context", None))
return filter(f, implementations)
def get_helpers(self, name, *helpers):
@@ -1116,6 +1212,32 @@ class PluginManager(object):
try: client(plugin, data)
except: self.logger.exception("Exception while sending plugin data to client")
def _sort_hooks(self, hook):
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
key=lambda x: (x[0] is None, x[0], x[1], x[2]))
def _get_callback_and_order(self, hook):
if callable(hook):
return hook, None
elif isinstance(hook, tuple) and len(hook) == 2:
callback, order = hook
# test that callback is a callable
if not callable(callback):
raise ValueError("Hook callback is not a callable")
# test that number is an int
try:
int(order)
except ValueError:
raise ValueError("Hook order is not a number")
return callback, order
else:
raise ValueError("Invalid hook definition, neither a callable nor a 2-tuple (callback, order): {!r}".format(hook))
class InstalledEntryPoint(pkginfo.Installed):
@@ -1209,7 +1331,35 @@ class Plugin(object):
pass
class RestartNeedingPlugin(Plugin):
pass
"""
Mixin for plugin types that need a restart in order to be enabled.
"""
class SortablePlugin(Plugin):
"""
Mixin for plugin types that are sortable.
"""
def get_sorting_key(self, context=None):
"""
Returns the sorting key to use for the implementation in the specified ``context``.
May return ``None`` if order is irrelevant.
Implementations returning None will be ordered by plugin identifier
after all implementations which did return a sorting key value that was
not None sorted by that.
Arguments:
context (str): The sorting context for which to provide the
sorting key value.
Returns:
int or None: An integer signifying the sorting key value of the plugin
(sorting will be done ascending), or None if the implementation
doesn't care about calling order.
"""
return None
class PluginNeedsRestart(Exception):
def __init__(self, name):
+429 -5
View File
@@ -9,6 +9,9 @@ Please note that the plugin implementation types are documented in the section
.. autoclass:: OctoPrintPlugin
:show-inheritance:
.. autoclass:: ReloadNeedingPlugin
:show-inheritance:
"""
from __future__ import absolute_import
@@ -18,7 +21,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 .core import (Plugin, RestartNeedingPlugin)
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
class OctoPrintPlugin(Plugin):
@@ -77,7 +80,7 @@ class OctoPrintPlugin(Plugin):
and if not creating it before returning it. Injected by the plugin core system upon initialization of the
implementation.
.. automethod:: get_plugin_data_folder
.. automethod:: get_plugin_data_folder
"""
def get_plugin_data_folder(self):
@@ -97,12 +100,18 @@ class OctoPrintPlugin(Plugin):
class ReloadNeedingPlugin(Plugin):
pass
"""
Mixin for plugin types that need a reload of the UI in order to become usable.
"""
class StartupPlugin(OctoPrintPlugin):
class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
The ``StartupPlugin`` allows hooking into the startup of OctoPrint. It can be used to start up additional services
on or just after the startup of the server.
``StartupPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`. The
relevant sorting context for :meth:`on_startup` is ``StartupPlugin.on_startup``,
the one for :meth:`on_after_startup` will be ``StartupPlugin.on_after_startup``.
"""
def on_startup(self, host, port):
@@ -127,11 +136,14 @@ class StartupPlugin(OctoPrintPlugin):
pass
class ShutdownPlugin(OctoPrintPlugin):
class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
"""
The ``ShutdownPlugin`` allows hooking into the shutdown of OctoPrint. It's usually used in conjunction with the
:class:`StartupPlugin` mixin, to cleanly shut down additional services again that where started by the :class:`StartupPlugin`
part of the plugin.
``ShutdownPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`.
The relevant sorting context will be ``ShutdownPlugin.on_shutdown``.
"""
def on_shutdown(self):
@@ -149,6 +161,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
A typical usage of the ``AssetPlugin`` functionality is to embed a custom view model to be used by templates injected
through a :class:`TemplatePlugin`.
``AssetPlugin`` is a :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
"""
def get_asset_folder(self):
@@ -249,6 +263,30 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
wrapper div and the link in the navigation will have the additional classes and styles applied as defined via the
supplied configuration supplied through :func:`get_template_configs`.
Wizards
Plugins may define wizard dialogs to display to the user if necessary (e.g. in case of missing information that
needs to be queried from the user to make the plugin work). Note that with the current implementations, all
wizard dialogs will be will always be sorted by their ``mandatory`` attribute (which defaults to ``False``) and then
alphabetically by their ``name``. Hence, mandatory wizard steps will come first, sorted alphabetically, then the
optional steps will follow, also alphabetically. A wizard dialog provided through a plugin will only be displayed
if the plugin reports the wizard as being required through :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required`.
Please also refer to the :class:`~octoprint.plugin.WizardPlugin` mixin for further details on this.
The included template must be called ``<plugin identifier>_wizard.jinja2`` (e.g. ``myplugin_wizard.jinja2``) unless
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 wizard navigation will have the additional classes and styles applied as defined
via the supplied configuration supplied through :func:`get_template_configs`.
.. note::
A note about ``mandatory`` wizard steps: In the current implementation, marking a wizard step as
mandatory will *only* make it styled accordingly. It is the task of the :ref:`view model <sec-plugins-viewmodels>`
to actually prevent the user from skipping the dialog by implementing the ``onWizardTabChange``
callback and returning ``false`` there if it is detected that the user hasn't yet filled in the
wizard step.
Generic
Plugins may also inject arbitrary templates into the page of the web interface itself, e.g. in order to
add overlays or dialogs to be called from within the plugin's javascript code.
@@ -273,6 +311,8 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
responsibility to ensure that all core functionality is still maintained.
Plugins can also add additional template types by implementing the :ref:`octoprint.ui.web.templatetypes <sec-plugins-hook-ui-web-templatetypes>` hook.
``TemplatePlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
"""
def get_template_configs(self):
@@ -396,6 +436,17 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
* - styles_content
- Like ``styles`` but only applied to the content pane itself.
``wizard`` type
.. list-table::
:widths: 5 95
* - mandatory
- Whether the wizard step is mandatory (True) or not (False). Optional,
defaults to False. If set to True, OctoPrint will sort visually mark
the step as mandatory in the UI (bold in the navigation and a little
alert) and also sort it into the first half.
.. note::
As already outlined above, each template type has a default template name (i.e. the default navbar template
@@ -450,6 +501,377 @@ class TemplatePlugin(OctoPrintPlugin, ReloadNeedingPlugin):
return os.path.join(self._basefolder, "templates")
class UiPlugin(OctoPrintPlugin, SortablePlugin):
"""
The ``UiPlugin`` mixin allows plugins to completely replace the UI served
by OctoPrint when requesting the main page hosted at `/`.
OctoPrint will query whether your mixin implementation will handle a
provided request by calling :meth:`~octoprint.plugin.UiPlugin.will_handle_ui` with the Flask
`Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object as
parameter. If you plugin returns `True` here, OctoPrint will next call
:meth:`~octoprint.plugin.UiPlugin.on_ui_render` with a couple of parameters like
- again - the Flask Request object and the render keyword arguments as
used by the default OctoPrint web interface. For more information see below.
There are two methods used in order to allow for caching of the actual
response sent to the client. Whatever a plugin implementation returns
from the call to its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method
will be cached server side. The cache will be emptied in case of explicit
no-cache headers sent by the client, or if the ``_refresh`` query parameter
on the request exists and is set to ``true``. To prevent caching of the
response altogether, a plugin may set no-cache headers on the returned
response as well.
``UiPlugin`` is a :class:`~octoprint.plugin.core.SortablePlugin`. The
relevant sorting context when acting as a UiPlugin is ``UiPlugin.will_handle_ui``.
The first plugin to return ``True`` will be the one whose ui will be used,
no further calls to :meth:`~octoprint.plugin.UiPlugin.on_ui_render` will be performed.
If implementations want to serve custom templates in the :meth:`~octoprint.plugin.UiPlugin.on_ui_render`
method it is recommended to also implement the :class:`~octoprint.plugin.TemplatePlugin`
mixin.
**Example**
What follows is a very simple example that renders a different (non functional and
only exemplary) UI if the requesting client has a UserAgent string hinting
at it being a mobile device:
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/__init__.py
:linenos:
:tab-width: 4
:caption: `dummy_mobile_ui/__init__.py <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/__init__.py>`_
.. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2
:linenos:
:tab-width: 4
:caption: `dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2 <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui/templates/dummy_mobile_ui_index.jinja2>`_
Try installing the above plugin ``dummy_mobile_ui`` (also available in the
`plugin examples repository <https://github.com/OctoPrint/Plugin-Examples/blob/master/dummy_mobile_ui>`_)
into your OctoPrint instance. If you access it from a regular desktop browser,
you should still see the default UI. However if you access it from a mobile
device (make sure to not have that request the desktop version of pages!)
you should see the very simple dummy page defined above.
"""
def will_handle_ui(self, request):
"""
Called by OctoPrint to determine if the mixin implementation will be
able to handle the ``request`` provided as a parameter.
Return ``True`` here to signal that your implementation will handle
the request and that the result of its :meth:`~octoprint.plugin.UiPlugin.on_ui_render` method
is what should be served to the user.
Arguments:
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_
object.
Returns:
bool: ``True`` if the the implementation will serve the request,
``False`` otherwise.
"""
return False
def on_ui_render(self, now, request, render_kwargs):
"""
Called by OctoPrint to retrieve the response to send to the client
for the ``request`` to ``/``. Only called if :meth:`~octoprint.plugin.UiPlugin.will_handle_ui`
returned ``True``.
``render_kwargs`` will be a dictionary (whose contents are cached) which
will contain the following key and value pairs (note that not all
key value pairs contained in the dictionary are listed here, only
those you should depend on as a plugin developer at the current time):
.. list-table::
:widths: 5 95
* - debug
- ``True`` if debug mode is enabled, ``False`` otherwise.
* - firstRun
- ``True`` if the server is being run for the first time (not
configured yet), ``False`` otherwise.
* - version
- OctoPrint's version information. This is a ``dict`` with the
following keys:
.. list-table::
:widths: 5 95
* - number
- The version number (e.g. ``x.y.z``)
* - branch
- The GIT branch from which the OctoPrint instance was built
(e.g. ``master``)
* - display
- The full human readable version string, including the
branch information (e.g. ``x.y.z (master branch)``
* - uiApiKey
- The UI API key to use for unauthorized API requests. This is
freshly generated on every server restart.
* - templates
- Template data to render in the UI. Will be a ``dict`` containing entries
for all known template types.
The sub structure for each key will be as follows:
.. list-table::
:widths: 5 95
* - order
- A list of template names in the order they should appear
in the final rendered page
* - entries
- The template entry definitions to render. Depending on the
template type those are either 2-tuples of a name and a ``dict``
or directly ``dicts`` with information regarding the
template to render.
For the possible contents of the data ``dicts`` see the
:class:`~octoprint.plugin.TemplatePlugin` mixin.
* - pluginNames
- A list of names of :class:`~octoprint.plugin.TemplatePlugin`
implementation that were enabled when creating the ``templates``
value.
* - locales
- The locales for which there are translations available.
On top of that all additional template variables as provided by :meth:`~octoprint.plugin.TemplatePlugin.get_template_vars`
will be contained in the dictionary as well.
Arguments:
now (datetime.datetime): The datetime instance representing "now"
for this request, in case your plugin implementation needs this
information.
request (flask.Request): A Flask `Request <http://flask.pocoo.org/docs/0.10/api/#flask.Request>`_ object.
render_kwargs (dict): The (cached) render keyword arguments that
would usually be provided to the core UI render function.
Returns:
flask.Response: Should return a Flask `Response <http://flask.pocoo.org/docs/0.10/api/#flask.Response>`_
object that can be served to the requesting client directly. May be
created with ``flask.make_response`` combined with something like
``flask.render_template``.
"""
return None
def get_ui_additional_key_data_for_cache(self):
return None
def get_ui_additional_tracked_files(self):
return None
def get_ui_custom_tracked_files(self):
return None
def get_ui_custom_etag(self):
return None
def get_ui_custom_lastmodified(self):
return None
def get_ui_data_for_preemptive_caching(self):
return None
def get_ui_additional_request_data_for_preemptive_caching(self):
return None
class WizardPlugin(OctoPrintPlugin, ReloadNeedingPlugin):
"""
The ``WizardPlugin`` mixin allows plugins to report to OctoPrint whether
the ``wizard`` templates they define via the :class:`~octoprint.plugin.TemplatePlugin`
should be displayed to the user, what details to provide to their respective
wizard frontend components and what to do when the wizard is finished
by the user.
OctoPrint will only display such wizard dialogs to the user which belong
to plugins that
* report ``True`` in their :func:`is_wizard_required` method and
* have not yet been shown to the user in the version currently being reported
by the :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version` method
Example: If a plugin with the identifier ``myplugin`` has a specific
setting ``some_key`` it needs to have filled by the user in order to be
able to work at all, it would probably test for that setting's value in
the :meth:`~octoprint.plugin.WizardPlugin.is_wizard_required` method and
return ``True`` if the value is unset:
.. code-block:: python
class MyPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin):
def get_default_settings(self):
return dict(some_key=None)
def is_wizard_required(self):
return self._settings.get(["some_key"]) is None
OctoPrint will then display the wizard dialog provided by the plugin through
the :class:`TemplatePlugin` mixin. Once the user finishes the wizard on the
frontend, OctoPrint will store that it already showed the wizard of ``myplugin``
in the version reported by :meth:`~octoprint.plugin.WizardPlugin.get_wizard_version`
- here ``None`` since that is the default value returned by that function
and the plugin did not override it.
If the plugin in a later version needs another setting from the user in order
to function, it will also need to change the reported version in order to
have OctoPrint reshow the dialog. E.g.
.. code-block:: python
class MyPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin):
def get_default_settings(self):
return dict(some_key=None, some_other_key=None)
def is_wizard_required(self):
some_key_unset = self._settings.get(["some_key"]) is None
some_other_key_unset = self._settings.get(["some_other_key"]) is None
return some_key_unset or some_other_key_unset
def get_wizard_version(self):
return 1
``WizardPlugin`` is a :class:`~octoprint.plugin.core.ReloadNeedingPlugin`.
"""
def is_wizard_required(self):
"""
Allows the plugin to report whether it needs to display a wizard to the
user or not.
Defaults to ``False``.
OctoPrint will only include those wizards from plugins which are reporting
their wizards as being required through this method returning ``True``.
Still, if OctoPrint already displayed that wizard in the same version
to the user once it won't be displayed again regardless whether this
method returns ``True`` or not.
"""
return False
def get_wizard_version(self):
"""
The version of this plugin's wizard. OctoPrint will only display a wizard
of the same plugin and wizard version once to the user. After they
finish the wizard, OctoPrint will remember that it already showed this
wizard in this particular version and not reshow it.
If a plugin needs to show its wizard to the user again (e.g. because
of changes in the required settings), increasing this value is the
way to notify OctoPrint of these changes.
Returns:
int or None: an int signifying the current wizard version, should be incremented by plugins whenever there
are changes to the plugin that might necessitate reshowing the wizard if it is required. ``None``
will also be accepted and lead to the wizard always be ignored unless it has never been finished
so far
"""
return None
def get_wizard_details(self):
"""
Called by OctoPrint when the wizard wrapper dialog is shown. Allows the plugin to return data
that will then be made available to the view models via the view model callback ``onWizardDetails``.
Use this if your plugin's view model that handles your wizard dialog needs additional
data to perform its task.
Returns:
dict: a dictionary containig additional data to provide to the frontend. Whatever the plugin
returns here will be made available on the wizard API under the plugin's identifier
"""
return dict()
def on_wizard_finish(self, handled):
"""
Called by OctoPrint whenever the user finishes a wizard session is finished.
The ``handled`` parameter will indicate whether that plugin's wizard was
included in the wizard dialog presented to the user (so the plugin providing
it was reporting that the wizard was required and the wizard plus version was not
ignored/had already been seen).
Use this to do any clean up tasks necessary after wizard completion.
Arguments:
handled (bool): True if the plugin's wizard was previously reported as
required, not ignored and thus presented to the user,
False otherwise
"""
pass
@classmethod
def is_wizard_ignored(cls, seen_wizards, implementation):
"""
Determines whether the provided implementation is ignored based on the
provided information about already seen wizards and their versions or not.
A wizard is ignored if
* the current and seen versions are identical
* the current version is None and the seen version is not
* the current version is less or equal than the seen one
.. code-block:: none
| current |
| N | 1 | 2 | N = None
----+---+---+---+ X = ignored
s N | X | | |
e --+---+---+---+
e 1 | X | X | |
n --+---+---+---+
2 | X | X | X |
----+---+---+---+
Arguments:
seen_wizards (dict): A dictionary with information about already seen
wizards and their versions. Mappings from the identifiers of
the plugin providing the wizard to the reported wizard
version (int or None) that was already seen by the user.
implementation (object): The plugin implementation to check.
Returns:
bool: False if the provided ``implementation`` is either not a :class:`WizardPlugin`
or has not yet been seen (in this version), True otherwise
"""
if not isinstance(implementation, cls):
return False
name = implementation._identifier
if not name in seen_wizards:
return False
seen = seen_wizards[name]
wizard_version = implementation.get_wizard_version()
current = None
if wizard_version is not None:
try:
current = int(wizard_version)
except ValueError as e:
import logging
logging.getLogger(__name__).log("WizardPlugin {} returned invalid value {} for wizard version: {}".format(name, wizard_version, str(e)))
return (current == seen) \
or (current is None and seen is not None) \
or (current <= seen)
class SimpleApiPlugin(OctoPrintPlugin):
"""
Utilizing the ``SimpleApiPlugin`` mixin plugins may implement a simple API based around one GET resource and one
@@ -627,6 +1049,8 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin):
flask.url_for("plugin.myblueprintplugin.myEcho") # will return "/plugin/myblueprintplugin/echo"
``BlueprintPlugin`` implements :class:`~octoprint.plugins.core.RestartNeedingPlugin`.
"""
@staticmethod
@@ -0,0 +1,147 @@
# coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin):
#~~ TemplatePlugin API
def get_template_configs(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
result = list()
for key, method in required.iteritems():
if not method():
continue
if not key in names:
continue
name = names[key]()
if not name:
continue
config = dict(type="wizard", name=name, template="corewizard_{}_wizard.jinja2".format(key), div="wizard_plugin_corewizard_{}".format(key))
if key in additional:
additional_result = additional[key]()
if additional_result:
config.update(additional_result)
result.append(config)
return result
#~~ AssetPlugin API
def get_assets(self):
return dict(
js=["js/corewizard.js"]
)
#~~ WizardPlugin API
def is_wizard_required(self):
methods = self._get_subwizard_attrs("_is_", "_wizard_required")
return self._settings.global_get(["server", "firstRun"]) and any(map(lambda m: m(), methods.values()))
def get_wizard_details(self):
result = dict()
def add_result(key, method):
result[key] = method()
self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
return result
#~~ ACL subwizard
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.hasBeenCustomized()
def _get_acl_wizard_details(self):
return dict()
def _get_acl_wizard_name(self):
return "Access Control"
def _get_acl_additional_wizard_template_data(self):
return dict(mandatory=self._is_acl_wizard_required())
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
def acl_wizard_api(self):
from flask import request
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
data = request.values
if hasattr(request, "json") and request.json:
data = request.json
if "ac" in data and data["ac"] in valid_boolean_trues and \
"user" in data.keys() and "pass1" in data.keys() and \
"pass2" in data.keys() and data["pass1"] == data["pass2"]:
# configure access control
self._settings.global_set_boolean(["accessControl", "enabled"], True)
self._user_manager.enable()
self._user_manager.addUser(data["user"], data["pass1"], True, ["user", "admin"], overwrite=True)
elif "ac" in data.keys() and not data["ac"] in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
self._user_manager.disable()
self._settings.save()
return NO_CONTENT
#~~ Webcam subwizard
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshotUrl"])
webcam_stream_url = self._settings.global_get(["webcam", "streamUrl"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
def _get_webcam_wizard_details(self):
return dict()
def _get_webcam_wizard_name(self):
return "Webcam & Timelapse"
#~~ helpers
def _get_subwizard_attrs(self, start, end, callback=None):
result = dict()
for item in dir(self):
if not item.startswith(start) or not item.endswith(end):
continue
key = item[len(start):-len(end)]
if not key:
continue
attr = getattr(self, item)
if callable(callback):
callback(key, attr)
result[key] = attr
return result
__plugin_name__ = "Core Wizard"
__plugin_description__ = "Provides wizard dialogs for core components"
__plugin_implementation__ = CoreWizardPlugin()
@@ -0,0 +1,114 @@
$(function() {
function CoreWizardAclViewModel(parameters) {
var self = this;
self.loginStateViewModel = parameters[0];
self.username = ko.observable(undefined);
self.password = ko.observable(undefined);
self.confirmedPassword = ko.observable(undefined);
self.setup = ko.observable(false);
self.decision = ko.observable();
self.passwordMismatch = ko.computed(function() {
return self.password() != self.confirmedPassword();
});
self.validUsername = ko.computed(function() {
return self.username() && self.username().trim() != "";
});
self.validPassword = ko.computed(function() {
return self.password() && self.password().trim() != "";
});
self.validData = ko.computed(function() {
return !self.passwordMismatch() && self.validUsername() && self.validPassword();
});
self.keepAccessControl = function() {
if (!self.validData()) return;
var data = {
"ac": true,
"user": self.username(),
"pass1": self.password(),
"pass2": self.confirmedPassword()
};
self._sendData(data);
};
self.disableAccessControl = function() {
var message = gettext("If you disable Access Control <strong>and</strong> your OctoPrint installation is accessible from the internet, your printer <strong>will be accessible by everyone - that also includes the bad guys!</strong>");
showConfirmationDialog({
message: message,
onproceed: function (e) {
var data = {
"ac": false
};
self._sendData(data);
}
});
};
self._sendData = function(data, callback) {
OctoPrint.postJson("plugin/corewizard/acl", data)
.done(function() {
self.setup(true);
self.decision(data.ac);
if (data.ac) {
// we now log the user in
var user = data.user;
var pass = data.pass1;
self.loginStateViewModel.login(user, pass, true)
.done(function() {
if (callback) callback();
});
} else {
if (callback) callback();
}
});
};
self.onWizardTabChange = function(current, next) {
if (!current || !_.startsWith(current, "wizard_plugin_corewizard_acl_") || self.setup()) {
return true;
}
showMessageDialog({
title: gettext("Please set up Access Control"),
message: gettext("You haven't yet set up access control. You need to either setup a username and password and click \"Keep Access Control Enabled\" or click \"Disable Access Control\" before continuing")
});
return false;
};
self.onWizardFinish = function() {
if (!self.decision()) {
return "reload";
}
};
}
function CoreWizardWebcamViewModel(parameters) {
var self = this;
self.settingsViewModel = parameters[0];
self.onWizardFinish = function() {
if (self.settingsViewModel.webcam_streamUrl()
|| (self.settingsViewModel.webcam_snapshotUrl() && self.settingsViewModel.webcam_ffmpegPath())) {
return "reload";
}
}
}
OCTOPRINT_VIEWMODELS.push([
CoreWizardAclViewModel,
["loginStateViewModel"],
"#wizard_plugin_corewizard_acl"
], [
CoreWizardWebcamViewModel,
["settingsViewModel"],
"#wizard_plugin_corewizard_webcam"
]);
});
@@ -0,0 +1,59 @@
<h3>{{ _('Access Control') }}</h3>
{% trans %}<p>
<strong>Please read the following, it is very important for your printer's health!</strong>
</p>
<p>
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
and using it in such a way that it is damaged or worse (i.e. causes a fire).
</p>
<p>
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
on "Keep Access Control Enabled":
</p>{% endtrans %}
<form class="form-horizontal">
<div class="control-group" data-bind="css: {success: validUsername()}">
<label class="control-label" for="first_run_username">{{ _('Username') }}</label>
<div class="controls">
<input type="text" class="input-medium" data-bind="value: username, valueUpdate: 'afterkeydown', enable: !setup(), css: {disabled: setup()}">
</div>
</div>
<div class="control-group" data-bind="css: {success: validPassword()}">
<label class="control-label" for="first_run_username">{{ _('Password') }}</label>
<div class="controls">
<input type="password" class="input-medium" data-bind="value: password, valueUpdate: 'afterkeydown', enable: !setup(), css: {disabled: setup()}">
</div>
</div>
<div class="control-group" data-bind="css: {error: passwordMismatch(), success: validPassword() && !passwordMismatch()}">
<label class="control-label" for="first_run_username">{{ _('Confirm Password') }}</label>
<div class="controls">
<input type="password" class="input-medium" data-bind="value: confirmedPassword, valueUpdate: 'afterkeydown', enable: !setup(), css: {disabled: setup()}">
<span class="help-inline" data-bind="visible: passwordMismatch()">{{ _('Passwords do not match') }}</span>
</div>
</div>
</form>
{% trans %}<p>
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
need Access Control for other reasons, you may alternatively disable Access Control. You should only
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
</p>
<p>
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
</p>{% endtrans %}
<div class="row-fluid">
<a href="#" class="btn btn-danger span6" data-bind="click: function() { if(!setup()){disableAccessControl()}}, enable: !setup(), css: {disabled: setup()}">{{ _('Disable Access Control') }}</a>
<a href="#" class="btn btn-primary span6" data-bind="click: function() { if(!setup()){keepAccessControl()}}, enable: !setup() && validData(), css: {disabled: !validData() || setup()}">{{ _('Keep Access Control Enabled') }}</a>
</div>
<div class="acl_decision" style="display: none" data-bind="visible: setup()">
<div class="text-center" style="display: none" data-bind="visible: decision()">{% trans %}
Access control is <strong class="text-success">enabled</strong>.
{% endtrans %}</div>
<div class="text-center" style="display: none" data-bind="visible: !decision()">{% trans %}
Access control is <strong class="text-danger">disabled</strong>.
{% endtrans %}</div>
</div>
@@ -0,0 +1,42 @@
<h3>{{ _('Webcam &amp; Timelapse Recordings') }}</h3>
{% trans %}<p>
If you have a webcam, you may now configure it here.
</p>{% endtrans %}
<h4>{{ _('Webcam') }}</h4>
{% trans %}<p>
The <strong>Stream URL</strong> is the URL OctoPrint uses to embed the
actual webcam stream (which should be an MJPG stream) into the web
interface. This needs to be reachable <strong>from your browser</strong>.
</p><p>
It may be
<ul>
<li>a fully qualified URL (<code>http://host:port/path</code>),</li>
<li>a URL defaulting to the protocol used for accessing the web
interface (e.g. <code>//host:port/path</code>),</li>
<li>an absolute path on the same host as OctoPrint (e.g. <code>/absolute/path</code>) or</li>
<li>a relative path on the same host as OctoPrint (e.g. <code>relative/path</code>)</li>
</ul>
</p><p>
The <strong>Snapshot URL</strong> is the URL OctoPrint uses to fetch single
images from the webcam for creating timelapse recordings. This needs to be
a fully qualified URL reachable <strong>from the OctoPrint server</strong>.
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/webcam/webcamStreamUrl.jinja2" %}
{% include "_snippets/settings/webcam/webcamSnapshotUrl.jinja2" %}
</form>
<h4>{{ _('Timelapse Recordings') }}</h4>
{% trans %}<p>
To render the snapshots into timelapse recordings, OctoPrint also needs to
know the correct <strong>path to FFMPEG</strong>.
</p>{% endtrans %}
<form class="form-horizontal" data-bind="with: settingsViewModel">
{% include "_snippets/settings/webcam/ffmpegPath.jinja2" %}
</form>
+137 -26
View File
@@ -16,14 +16,19 @@ import octoprint.util
import octoprint.slicing
import octoprint.settings
from octoprint.util.paths import normalize as normalize_path
from .profile import Profile
from .profile import GcodeFlavors
from .profile import parse_gcode_flavor
class CuraPlugin(octoprint.plugin.SlicerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin):
octoprint.plugin.StartupPlugin,
octoprint.plugin.WizardPlugin):
def __init__(self):
self._logger = logging.getLogger("octoprint.plugins.cura")
@@ -35,6 +40,14 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cancelled_jobs = []
self._job_mutex = threading.Lock()
def _is_engine_configured(self, cura_engine=None):
if cura_engine is None:
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
return cura_engine is not None and os.path.isfile(cura_engine) and os.access(cura_engine, os.X_OK)
def _is_profile_available(self):
return bool(self._slicing_manager.all_profiles("cura", require_configured=False))
##~~ TemplatePlugin API
def get_template_vars(self):
@@ -42,6 +55,17 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
homepage=__plugin_url__
)
##~~ WizardPlugin API
def is_wizard_required(self):
return not self._is_engine_configured() or not self._is_profile_available()
def get_wizard_details(self):
return dict(
engine=self._is_engine_configured(),
profile=self._is_profile_available()
)
##~~ StartupPlugin API
def on_startup(self, host, port):
@@ -59,9 +83,6 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
@octoprint.plugin.BlueprintPlugin.route("/import", methods=["POST"])
def import_cura_profile(self):
import datetime
import tempfile
from octoprint.server import slicingManager
input_name = "file"
input_upload_name = input_name + "." + self._settings.global_get(["server", "uploads", "nameSuffix"])
@@ -90,8 +111,10 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
profile_display_name = name
profile_description = "Imported from {filename} on {date}".format(filename=filename, date=octoprint.util.get_formatted_datetime(datetime.datetime.now()))
profile_allow_overwrite = False
profile_make_default = False
# overrides
from octoprint.server.api import valid_boolean_trues
if "name" in flask.request.values:
profile_name = flask.request.values["name"]
if "displayName" in flask.request.values:
@@ -99,22 +122,31 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
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
if "default" in flask.request.values:
profile_make_default = flask.request.values["default"] in valid_boolean_trues
try:
slicingManager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
self._slicing_manager.save_profile("cura",
profile_name,
profile_dict,
allow_overwrite=profile_allow_overwrite,
display_name=profile_display_name,
description=profile_description)
except octoprint.slicing.ProfileAlreadyExists:
self._logger.warn("Profile {profile_name} already exists, aborting".format(**locals()))
return flask.make_response("A profile named {profile_name} already exists for slicer cura".format(**locals()), 409)
if profile_make_default:
try:
self._slicing_manager.set_default_profile("cura", profile_name)
except octoprint.slicing.UnknownProfile:
self._logger.warn("Profile {profile_name} could not be set as default, aborting".format(**locals()))
return flask.make_response("The profile {profile_name} for slicer cura could not be set as default".format(**locals()), 500)
result = dict(
resource=flask.url_for("api.slicingGetSlicerProfile", slicer="cura", name=profile_name, _external=True),
name=profile_name,
displayName=profile_display_name,
description=profile_description
)
@@ -155,11 +187,12 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
##~~ SlicerPlugin API
def is_slicer_configured(self):
cura_engine = self._settings.get(["cura_engine"])
if cura_engine is not None and os.path.exists(cura_engine):
cura_engine = normalize_path(self._settings.get(["cura_engine"]))
if self._is_engine_configured(cura_engine=cura_engine):
return True
else:
self._logger.info("Path to CuraEngine has not been configured yet or does not exist (currently set to %r), Cura will not be selectable for slicing" % cura_engine)
return False
def get_slicer_properties(self):
return dict(
@@ -227,15 +260,29 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
self._cura_logger.info(u"### Slicing %s to %s using profile stored at %s" % (model_path, machinecode_path, profile_path))
engine_settings = self._convert_to_engine(profile_path, printer_profile, posX, posY)
executable = self._settings.get(["cura_engine"])
executable = normalize_path(self._settings.get(["cura_engine"]))
if not executable:
return False, "Path to CuraEngine is not configured "
working_dir, _ = os.path.split(executable)
working_dir = os.path.dirname(executable)
# Start building the argument list for the CuraEngine command execution
args = [executable, '-v', '-p']
for k, v in engine_settings.items():
# Get the CuraEngine version out of the "usage" line that is gotten when calling the CuraEngine with the -h argument
new_engine = self._is_new_engine_version(executable)
# If the CuraEngine is the new version, add the JSON file path as argument
if new_engine:
args += ['-j', os.path.join(self._basefolder, "profiles", "fdmprinter.json")]
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
engine_settings = self._convert_to_engine(profile, new_engine=new_engine)
# Add the settings (sorted alphabetically) to the command
for k, v in sorted(engine_settings.items(), key=lambda s: s[0]):
args += ["-s", "%s=%s" % (k, str(v))]
args += ["-o", machinecode_path, model_path]
@@ -318,6 +365,8 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
except:
pass
# Get the filament usage
elif line.startswith(u"Filament:") or line.startswith(u"Filament2:"):
if line.startswith(u"Filament:"):
filament_str = line[len(u"Filament:"):].strip()
@@ -328,17 +377,25 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
try:
filament = int(filament_str)
if analysis is None:
analysis = dict()
if not "filament" in analysis:
analysis["filament"] = dict()
if not tool_key in analysis["filament"]:
analysis["filament"][tool_key] = dict()
analysis["filament"][tool_key]["length"] = filament
if "filamentDiameter" in engine_settings:
radius_in_cm = float(int(engine_settings["filamentDiameter"]) / 10000.0) / 2.0
filament_in_cm = filament / 10.0
analysis["filament"][tool_key]["volume"] = filament_in_cm * math.pi * radius_in_cm * radius_in_cm
if profile.get_float("filament_diameter") != None:
# The new CuraEngine outputs the "Filament" value as volume independently from the Gcode flavor
if new_engine:
analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
# The old CuraEngine outputs the "Filament" value as volume only for ULTIGCODE and REPRAP_VOLUME
else:
if profile.get("gcode_flavor") == GcodeFlavors.ULTIGCODE or profile.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
analysis["filament"][tool_key] = _get_usage_from_volume(filament, profile.get_float("filament_diameter"))
else:
analysis["filament"][tool_key] = _get_usage_from_length(filament, profile.get_float("filament_diameter"))
except:
pass
finally:
@@ -388,6 +445,11 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
profile_dict = yaml.safe_load(f)
except:
raise IOError("Couldn't read profile from {path}".format(path=path))
if "gcode_flavor" in profile_dict and not isinstance(profile_dict["gcode_flavor"], (list, tuple)):
profile_dict["gcode_flavor"] = parse_gcode_flavor(profile_dict["gcode_flavor"])
self._save_profile(path, profile_dict)
return profile_dict
def _save_profile(self, path, profile, allow_overwrite=True):
@@ -395,9 +457,28 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
with octoprint.util.atomic_write(path, "wb") as f:
yaml.safe_dump(profile, f, default_flow_style=False, indent=" ", allow_unicode=True)
def _convert_to_engine(self, profile_path, printer_profile, posX, posY):
profile = Profile(self._load_profile(profile_path), printer_profile, posX, posY)
return profile.convert_to_engine()
def _convert_to_engine(self, profile, new_engine):
if new_engine:
return profile.convert_to_new_engine()
else:
return profile.convert_to_engine()
def _is_new_engine_version(self, executable):
import sarge
command = [executable, "-j", os.path.join(self._basefolder, "profiles", "fdmprinter.json")]
p = sarge.run(command, stdout=sarge.Capture(), stderr=sarge.Capture())
if p.returncode != 0:
self._logger.warn("Could not run {} -j, returned {}".format(executable, p.returncode))
self._logger.info(u"Assuming pre 15.06 version of CuraEngine.")
return False
for line in p.stderr.read().split('\n'):
if "unknown option: j" in line.strip().lower():
self._logger.info(u"Using pre 15.06 version of CuraEngine.")
return False
self._logger.info(u"Using post 15.06 version of CuraEngine.")
return True
def _sanitize_name(name):
if name is None:
@@ -412,9 +493,39 @@ def _sanitize_name(name):
sanitized_name = sanitized_name.replace(" ", "_")
return sanitized_name.lower()
def _get_usage_from_volume(filament_volume, filament_diameter):
# filament_volume is expressed in mm^3
# usage["volume"] is in cm^3 and usage["length"] is in mm
usage = dict()
usage["volume"] = filament_volume / 1000.0
radius_in_mm = filament_diameter / 2.0
usage["length"] = filament_volume / (math.pi * radius_in_mm * radius_in_mm)
return usage
def _get_usage_from_length(filament_length, filament_diameter):
# filament_length is expressed in mm
# usage["volume"] is in cm^3 and usage["length"] is in mm
usage = dict()
usage["length"] = filament_length
radius_in_cm = (filament_diameter / 10.0) / 2.0
length_in_cm = filament_length / 10.0
usage["volume"] = length_in_cm * math.pi * radius_in_cm * radius_in_cm
return usage
__plugin_name__ = "CuraEngine (<= 15.04)"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Cura"
__plugin_description__ = "Adds support for slicing via CuraEngine versions up to and including version 15.04 from within OctoPrint"
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = CuraPlugin()
+228 -62
View File
@@ -32,12 +32,12 @@ class MachineShapeTypes(object):
CIRCULAR = "circular"
class GcodeFlavors(object):
REPRAP = "reprap"
REPRAP_VOLUME = "reprap_volume"
ULTIGCODE = "ultigcode"
MAKERBOT = "makerbot"
BFB = "bfb"
MACH3 = "mach3"
REPRAP = (0, "reprap")
ULTIGCODE = (1, "ultigcode")
MAKERBOT = (2, "makerbot")
BFB = (3, "bfb")
MACH3 = (4, "mach3")
REPRAP_VOLUME = (5, "reprap_volume")
defaults = dict(
@@ -393,15 +393,45 @@ class Profile(object):
}
)
# Translation dict for new CuraEngine option names
new_engine_options = dict(
fill_sparse_density="fill_density",
machine_nozzle_size="nozzle_size",
material_print_temperature="print_temperature",
#support_type="support", # In conflict with "support_type" from old CuraEngine
support_pattern="support_type",
adhesion_type="platform_adhesion",
material_diameter="filament_diameter",
material_flow="filament_flow",
speed_travel="travel_speed",
speed_layer_0="bottom_layer_speed",
speed_print="print_speed",
speed_infill="infill_speed",
speed_wall_0="outer_shell_speed",
speed_wall_x="inner_shell_speed",
cool_fan_enabled="fan_enabled",
cool_fan_full_at_height="fan_full_height",
cool_fan_speed="fan_speed",
cool_fan_speed_max="fan_speed_max",
cool_lift_head="cool_head_lift",
cool_min_speed="cool_min_feedrate",
machine_start_gcode="start_gcode",
machine_end_gcode="end_gcode",
machine_gcode_flavor="gcode_flavor")
result = dict()
for section in config.sections():
if not section in ("profile", "alterations"):
if not section in ("profile", "alterations", "machine"):
continue
for option in config.options(section):
ignored = False
key = option
if section == "machine" and key != "gcode_flavor":
continue
# try to fetch the value in the correct type
try:
value = config.getboolean(section, option)
@@ -438,9 +468,16 @@ class Profile(object):
# if the key has to be translated to a new value, do that now
key = translated_options[key]
if key in new_engine_options:
# if the key has to be translated from the new CuraEngine versions, do that now
key = new_engine_options[key]
if key in value_conversions and value in value_conversions[key]:
value = value_conversions[key][value]
if key == "gcode_flavor":
value = parse_gcode_flavor(value)
if index is not None:
# if we have an array to fill, make sure the target array exists and has the right size
if not key in result:
@@ -710,61 +747,70 @@ class Profile(object):
return pre + str(f)
def get_gcode(self, key):
extruder_count = self.get_int("extruder_amount")
def get_gcode(self, key, new_engine=False):
prefix = ""
postfix = ""
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
if key == "end_gcode":
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
return "M25 ;Stop reading from this point on.\n;CURA_OCTO_PROFILE_STRING:%s\n" % (self.get_profile_string())
return ""
if key == "start_gcode":
contents = self.get_gcode_template("start_gcode")
e_steps = self.get_float("steps_per_e")
if e_steps > 0:
prefix += "M92 E{e_steps}\n" % (e_steps)
temp = self.get_float("print_temperature")
bed_temp = 0
if self.get_boolean("has_heated_bed"):
bed_temp = self.get_float("print_bed_temperature")
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temp:
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if extruder_count > 0:
def temp_line(temp, extruder, template):
t = temp
if extruder > 0:
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
if print_temp > 0:
t = print_temp
return template.format(extruder=extruder, temp=t)
prefix_preheat = ""
prefix_waitheat = ""
for n in xrange(0, extruder_count):
if n > 0:
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += prefix_preheat + prefix_waitheat + "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
if include_bed_temp:
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
# If using the new CuraEngine, there is no need to extend the start_gcode
if not new_engine:
prefix += self.get_start_gcode_prefix(contents)
else:
contents = self.get_gcode_template(key)
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
def get_start_gcode_prefix(self, contents):
extruder_count = self.get_int("extruder_amount")
prefix = ""
e_steps = self.get_float("steps_per_e")
if e_steps > 0:
prefix += "M92 E{e_steps}\n" % (e_steps)
temp = self.get_float("print_temperature")
bed_temp = 0
if self.get_boolean("has_heated_bed"):
bed_temp = self.get_float("print_bed_temperature")
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temp:
prefix += "M140 S{bed_temp}\n".format(bed_temp=bed_temp)
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if extruder_count > 0:
def temp_line(temp, extruder, template):
t = temp
if extruder > 0:
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
if print_temp > 0:
t = print_temp
return template.format(extruder=extruder, temp=t)
prefix_preheat = ""
prefix_waitheat = ""
for n in xrange(0, extruder_count):
if n > 0:
prefix_preheat += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
prefix_waitheat += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += prefix_preheat + prefix_waitheat + "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
if include_bed_temp:
prefix += "M190 S{bed_temp}\n".format(bed_temp=bed_temp)
return prefix
def calculate_edge_width_and_line_count(self):
wall_thickness = self.get_float("wall_thickness")
nozzle_size = self._printer_profile["extruder"]["nozzleDiameter"]
@@ -810,20 +856,20 @@ class Profile(object):
def get_pos_x(self):
if self._posX:
try:
return int(float(self._posX) * 1000)
return int(float(self._posX))
except ValueError:
pass
return int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
return int(self.get_float("machine_width") / 2.0 ) if not self.get_boolean("machine_center_is_zero") else 0.0
def get_pos_y(self):
if self._posY:
try:
return int(float(self._posY) * 1000)
return int(float(self._posY))
except ValueError:
pass
return int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0
return int(self.get_float("machine_depth") / 2.0) if not self.get_boolean("machine_center_is_zero") else 0.0
def convert_to_engine(self):
@@ -873,8 +919,8 @@ class Profile(object):
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
# model positioning
"posx": self.get_pos_x(),
"posy": self.get_pos_y(),
"posx": self.get_pos_x() * 1000, # in microns
"posy": self.get_pos_y() * 1000, # in microns
# gcodes
"startCode": self.get_gcode("start_gcode"),
@@ -953,16 +999,7 @@ class Profile(object):
settings["layerThickness"] = 1000
# gcode flavor
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
settings["gcodeFlavor"] = 1
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
settings["gcodeFlavor"] = 2
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
settings["gcodeFlavor"] = 3
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
settings["gcodeFlavor"] = 4
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
settings["gcodeFlavor"] = 5
settings["gcodeFlavor"] = self.get("gcode_flavor")[0]
# extras
if self.get_boolean("spiralize"):
@@ -978,3 +1015,132 @@ class Profile(object):
settings["enableOozeShield"] = 1
return settings
def convert_to_new_engine(self):
settings = {
"layer_height": self.get_float("layer_height"),
"wall_thickness": self.get_float("wall_thickness"),
"retraction_enable": self.get_boolean("retraction_enable"),
"top_bottom_thickness": self.get_float("solid_layer_thickness"),
"fill_sparse_density": self.get_float("fill_density"),
"machine_nozzle_size": self.get_float("nozzle_size"),
"speed_print": self.get_float("print_speed"),
"material_print_temperature": self.get_float("print_temperature"),
"material_diameter": self.get_float("filament_diameter"),
"material_flow": self.get_float("filament_flow"),
"retraction_speed": self.get_float("retraction_speed"),
"retraction_amount": self.get_float("retraction_amount") if self.get_boolean("retraction_enable") else 0,
"retraction_min_travel": self.get_float("retraction_min_travel"),
"retraction_combing": self.get_boolean("retraction_combing"),
"retraction_hop": self.get_float("retraction_hop"),
"bottom_thickness": self.get_float("bottom_thickness"),
"top_layers": self.calculate_solid_layer_count(),
"bottom_layers": self.calculate_solid_layer_count(),
"speed_travel": self.get_float("travel_speed"),
"speed_layer_0": self.get_float("bottom_layer_speed"),
"speed_infill": self.get_float("infill_speed") if self.get_float("infill_speed") > 0 else self.get_float("print_speed"),
"speed_wall_0": self.get_float("outer_shell_speed") if self.get_float("outer_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "inset0_speed"
"speed_wall_x": self.get_float("inner_shell_speed") if self.get_float("inner_shell_speed") > 0 else self.get_float("print_speed"), # Translated from "insetx_speed"
"cool_min_layer_time": self.get_float("cool_min_layer_time"),
"cool_fan_enabled": self.get_boolean("fan_enabled"),
"cool_fan_full_at_height": self.get_int("fan_full_height"),
"cool_fan_speed": self.get_float("fan_speed"),
"cool_fan_speed_max": self.get_float("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
"cool_lift_head": self.get_boolean("cool_head_lift"),
"cool_min_speed": self.get_float("cool_min_feedrate"),
"skirt_line_count": self.get_int("skirt_line_count"),
"fill_overlap": self.get_float("fill_overlap"),
"magic_spiralize": self.get_boolean("spiralize"),
# machine settings
"machine_width": self.get_float("machine_width"),
"machine_depth": self.get_float("machine_depth"),
"machine_center_is_zero": self.get_boolean("machine_center_is_zero"),
"machine_heated_bed": self.get_boolean("has_heated_bed"),
# gcodes
"machine_start_gcode": self.get_gcode("start_gcode", new_engine=True),
"machine_end_gcode": self.get_gcode("end_gcode", new_engine=True),
}
# gcode flavor
settings["machine_gcode_flavor"] = self.get("gcode_flavor")[0]
# heated bed - The new CuraEngine uses the integer "material_bed_temperature" instead of the boolean "machine_heated_bed"
if self.get_boolean("has_heated_bed"):
settings["material_bed_temperature"] = self.get_float("print_bed_temperature")
else:
settings["material_bed_temperature"] = 0
# support
if self.get("support") == SupportLocationTypes.NONE:
settings["support_enable"] = False
else:
settings["support_enable"] = True
settings["support_angle"] = self.get_float("support_angle")
settings["support_fill_rate"] = self.get_float("support_fill_rate")
settings["support_xy_distance"] = self.get_float("support_xy_distance")
settings["support_z_distance"] = self.get_float("support_z_distance")
# support type
if self.get("support") == SupportLocationTypes.TOUCHING_BUILDPLATE:
settings["support_type"] = "Touching Buildplate"
elif self.get("support") == SupportLocationTypes.EVERYWHERE:
settings["support_type"] = "Everywhere"
# support pattern
if self.get("support_type") == SupportTypes.GRID:
settings["support_pattern"] = "Grid"
elif self.get("support_type") == SupportTypes.LINES:
settings["support_pattern"] = "Lines"
# adhesion type
if self.get("platform_adhesion") == PlatformAdhesionTypes.NONE:
settings["adhesion_type"] = "None"
elif self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
settings["adhesion_type"] = "Brim"
settings["brim_line_count"] = self.get_int("brim_line_count")
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
settings["adhesion_type"] = "Raft"
settings["raft_margin"] = self.get_int("raft_margin")
settings["raft_line_spacing"] = self.get_float("raft_line_spacing")
settings["raft_base_thickness"] = self.get_float("raft_base_thickness")
settings["raft_base_linewidth"] = self.get_float("raft_base_linewidth")
settings["raft_interface_thickness"] = self.get_float("raft_interface_thickness")
settings["raft_interface_linewidth"] = self.get_float("raft_interface_linewidth")
settings["raft_airgap"] = self.get_float("raft_airgap")
settings["raft_surface_layers"] = self.get_int("raft_surface_layers")
# skirt
if self.get_int("skirt_line_count") != 0:
settings["skirt_gap"] = self.get_float("skirt_gap")
settings["skirt_minimal_length"] = self.get_float("skirt_minimal_length")
return settings
def parse_gcode_flavor(value):
value = value.lower()
if "reprap" in value and ("volume" in value or "volumatric" in value):
return GcodeFlavors.REPRAP_VOLUME
elif "ultigcode" in value:
return GcodeFlavors.ULTIGCODE
elif "makerbot" in value:
return GcodeFlavors.MAKERBOT
elif "bfb" in value:
return GcodeFlavors.BFB
elif "mach3" in value:
return GcodeFlavors.MACH3
else:
return GcodeFlavors.REPRAP
File diff suppressed because it is too large. Load diff
+75 -24
View File
@@ -6,6 +6,13 @@ $(function() {
self.settingsViewModel = parameters[1];
self.slicingViewModel = parameters[2];
self.pathBroken = ko.observable(false);
self.pathOk = ko.observable(false);
self.pathText = ko.observable();
self.pathHelpVisible = ko.computed(function() {
return self.pathBroken() || self.pathOk();
});
self.fileName = ko.observable();
self.placeholderName = ko.observable();
@@ -16,6 +23,10 @@ $(function() {
self.profileDisplayName = ko.observable();
self.profileDescription = ko.observable();
self.profileAllowOverwrite = ko.observable(true);
self.profileMakeDefault = ko.observable(false);
self.unconfiguredCuraEngine = ko.observable();
self.unconfiguredSlicingProfile = ko.observable();
self.uploadElement = $("#settings-cura-import");
self.uploadButton = $("#settings-cura-import-start");
@@ -59,6 +70,7 @@ $(function() {
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length == 0) {
return false;
@@ -86,6 +98,9 @@ $(function() {
if (self.profileDescription() !== undefined) {
form["description"] = self.profileDescription();
}
if (self.profileMakeDefault()) {
form["default"] = true;
}
data.formData = form;
data.submit();
@@ -100,6 +115,7 @@ $(function() {
self.profileDisplayName(undefined);
self.profileDescription(undefined);
self.profileAllowOverwrite(true);
self.profileMakeDefault(false);
$("#settings_plugin_cura_import").modal("hide");
self.requestData();
@@ -116,14 +132,11 @@ $(function() {
return (item.key == data.key);
});
$.ajax({
url: data.resource(),
type: "DELETE",
success: function() {
OctoPrint.slicing.deleteProfileForSlicer("cura", data.key, {url: data.resource()})
.done(function() {
self.requestData();
self.slicingViewModel.requestData();
}
});
});
};
self.makeProfileDefault = function(data) {
@@ -141,29 +154,42 @@ $(function() {
item.isdefault(true);
}
$.ajax({
url: data.resource(),
type: "PATCH",
dataType: "json",
data: JSON.stringify({default: true}),
contentType: "application/json; charset=UTF-8",
success: function() {
OctoPrint.slicing.updateProfileForSlicer("cura", data.key, {default: true}, {url: data.resource()})
.done(function() {
self.requestData();
}
});
});
};
self.showImportProfileDialog = function() {
self.showImportProfileDialog = function(makeDefault) {
if (makeDefault == undefined) {
makeDefault = _.filter(self.profiles.items(), function(profile) { profile.isdefault() }).length == 0;
}
self.profileMakeDefault(makeDefault);
$("#settings_plugin_cura_import").modal("show");
};
self.testEnginePath = function() {
OctoPrint.util.testExecutable(self.settings.plugins.cura.cura_engine())
.done(function(response) {
if (!response.result) {
if (!response.exists) {
self.pathText(gettext("The path doesn't exist"));
} else if (!response.typeok) {
self.pathText(gettext("The path is not a file"));
} else if (!response.access) {
self.pathText(gettext("The path is not an executable"));
}
} else {
self.pathText(gettext("The path is valid"));
}
self.pathOk(response.result);
self.pathBroken(!response.result);
});
};
self.requestData = function() {
$.ajax({
url: API_BASEURL + "slicing/cura/profiles",
type: "GET",
dataType: "json",
success: self.fromResponse
});
OctoPrint.slicing.listProfilesForSlicer("cura")
.done(self.fromResponse);
};
self.fromResponse = function(data) {
@@ -184,12 +210,37 @@ $(function() {
self.settings = self.settingsViewModel.settings;
self.requestData();
};
self.onSettingsHidden = function() {
self.resetPathTest();
};
self.resetPathTest = function() {
self.pathBroken(false);
self.pathOk(false);
self.pathText("");
};
self.onWizardDetails = function(response) {
if (!response.hasOwnProperty("cura") || !response.cura.required) return;
if (response.cura.details.hasOwnProperty("engine")) {
self.unconfiguredCuraEngine(!response.cura.details.engine);
}
if (response.cura.details.hasOwnProperty("profile")) {
self.unconfiguredSlicingProfile(!response.cura.details.profile);
}
};
self.onWizardFinish = function() {
self.resetPathTest();
};
}
// view model class, parameters for constructor, container to bind to
OCTOPRINT_VIEWMODELS.push([
CuraViewModel,
["loginStateViewModel", "settingsViewModel", "slicingViewModel"],
"#settings_plugin_cura"
["#settings_plugin_cura", "#wizard_plugin_cura"]
]);
});
});
@@ -0,0 +1,7 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to plugin_cura_engine.log') }}
</label>
</div>
</div>
@@ -0,0 +1,10 @@
<div class="control-group" data-bind="css: {error: pathBroken(), success: pathOk()}">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'">
<button class="btn" type="button" data-bind="click: testEnginePath, enable: settings.plugins.cura.cura_engine(), css: {disabled: !settings.plugins.cura.cura_engine()}">{{ _('Test') }}</button>
</div>
<span class="help-block" data-bind="visible: pathBroken() || pathOk(), text: pathText"></span>
</div>
</div>
@@ -0,0 +1,64 @@
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Import Existing Cura Profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Profile ini file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileMakeDefault"> {{ _('Make default profile') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
</form>
<small>{% trans %}
You can import your existing profile <code>.ini</code> files from Cura (version up to and
including 15.04) here. Please be aware that neither the <code>.json</code> profile format
from Cura versions starting with 15.06 is supported, nor are the custom Cura profile formats
that third party tools like e.g. Repetier create.
{% endtrans %}</small>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
</div>
</div>
@@ -0,0 +1,34 @@
<div data-bind="visible: profiles.items().length > 0" style="display: none">
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: profiles.pages">
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
</ul>
</div>
</div>
@@ -8,55 +8,13 @@
{% endtrans %}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: settings.plugins.cura.debug_logging"> {{ _('Log the output of CuraEngine to <code>plugin_cura_engine.log</code>') }}
</label>
</div>
</div>
{% include "_snippets/settings/cura/enginePath.jinja2" %}
{% include "_snippets/settings/cura/engineLog.jinja2" %}
</form>
<h4>{{ _('Profiles') }}</h4>
<div class="pull-right">
<small>{{ _('Sort by') }}: <a href="#" data-bind="click: function() { profiles.changeSorting('id'); }">{{ _('Identifier') }} ({{ _('ascending') }})</a> | <a href="#" data-bind="click: function() { profiles.changeSorting('name'); }">{{ _('Name') }} ({{ _('ascending') }})</a></small>
</div>
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_cura_profiles_key">{{ _('Identifier') }}</th>
<th class="settings_plugin_cura_profiles_name">{{ _('Name') }}</th>
<th class="settings_plugin_cura_profiles_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: profiles.paginatedItems">
<tr data-bind="attr: {title: description}">
<td class="settings_plugin_cura_profiles_key"><span class="icon-star" data-bind="invisible: !isdefault()"></span> <span data-bind="text: key"></span></td>
<td class="settings_plugin_cura_profiles_name" data-bind="text: name"></td>
<td class="settings_plugin_cura_profiles_actions">
<a href="#" class="icon-star" title="{{ _('Make default') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.makeProfileDefault($data); } }"></a>&nbsp;|&nbsp;<a href="#" class="icon-trash" title="{{ _('Delete Profile') }}" data-bind="enable: !isdefault(), css: {disabled: isdefault()}, click: function() { if (!$data.isdefault()) { $root.removeProfile($data); } }"></a>
</td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === 0}"><a href="#" data-bind="click: profiles.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: profiles.pages">
<li data-bind="css: { active: $data.number === $root.profiles.currentPage(), disabled: $data.number === -1 }"><a href="#" data-bind="text: $data.text, click: function() { $root.profiles.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: profiles.currentPage() === profiles.lastPage()}"><a href="#" data-bind="click: profiles.nextPage">»</a></li>
</ul>
</div>
{% include "_snippets/settings/cura/profiles.jinja2" %}
<button class="btn pull-right" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
@@ -64,62 +22,4 @@
<small>{% trans %}For more information on configuration and usage please <a href="{{ plugin_cura_homepage }}" target="_blank">see the Plugin's homepage</a>.{% endtrans %}</small>
</div>
<div id="settings_plugin_cura_import" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Import Existing Cura Profile') }}</h3>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Profile ini file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-cura-import" type="file" name="file" data-url="{{ url_for("plugin.cura.import_cura_profile") }}">
</span>
<span class="add-on" data-bind="text: fileName"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Identifier') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileName, attr: {placeholder: placeholderName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Name') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDisplayName, attr: {placeholder: placeholderDisplayName}">
</div>
</div>
<div class="control-group">
<label class="control-label">{{ _('Description') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: profileDescription, attr: {placeholder: placeholderDescription}">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: profileAllowOverwrite"> {{ _('Overwrite existing file') }}
</label>
</div>
</div>
</form>
<small>{% trans %}
You can import your existing profile <code>.ini</code> files from Cura (version up to and
including 15.04) here. Please be aware that neither the <code>.json</code> profile format
from Cura versions starting with 15.06 is supported, nor are the custom Cura profile formats
that third party tools like e.g. Repetier create.
{% endtrans %}</small>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Abort') }}</button>
<button class="btn btn-primary" id="settings-cura-import-start">{{ _('Confirm') }}</button>
</div>
</div>
{% include "_snippets/settings/cura/profileImporter.jinja2" %}
@@ -0,0 +1,34 @@
<div data-bind="visible: unconfiguredCuraEngine">
<h3>{{ _('Configure CuraEngine') }}</h3>
<p>{% trans %}
The path to CuraEngine has not yet been set up, in order to be able to use
CuraEngine for slicing it needs to be specified.
{% endtrans %}</p>
<div style="margin-top: 1em">
<form class="form-horizontal">
{% include "_snippets/settings/cura/enginePath.jinja2" %}
</form>
</div>
</div>
<div data-bind="visible: unconfiguredSlicingProfile">
<h3>{{ _('Set up a slicing profile') }}</h3>
<p>{% trans %}You haven't imported a slicing profile to use for slicing with CuraEngine
yet. You should do this now.{% endtrans %}</p>
<div>
{% include "_snippets/settings/cura/profiles.jinja2" %}
</div>
<button class="btn btn-block" data-bind="click: function() { $root.showImportProfileDialog() }">{{ _('Import Profile...') }}</button>
<div style="clear: both; margin-top: 20px;">
<small>{% trans %}
<strong>Don't know where to get a profile?</strong> In order to export
a slicing profile from the Cura desktop UI up to and including version 15.04,
open it, set up your profile, then click on "File" and there on "Save Profile". You can
import the <code>.ini</code> file this creates via the "Import Profile" button.
{% endtrans %}</small>
</div>
</div>
+83 -30
View File
@@ -11,7 +11,7 @@ import octoprint.plugin.core
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission
from octoprint.server import admin_permission, VERSION
from octoprint.util.pip import PipCaller, UnknownPip
from flask import jsonify, make_response
@@ -39,19 +39,21 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._pending_uninstall = set()
self._pip_caller = None
self._pip_version_dependency_links = pkg_resources.parse_version("1.5")
self._repository_available = False
self._repository_plugins = []
self._repository_cache_path = None
self._repository_cache_ttl = 0
self._console_logger = None
def initialize(self):
self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console")
self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json")
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._pip_caller = PipCaller(configured=self._settings.get(["pip"]))
self._pip_caller = PipCaller(configured=self._settings.get(["pip"]),
force_user=self._settings.get_boolean(["pip_force_user"]))
self._pip_caller.on_log_call = self._log_call
self._pip_caller.on_log_stdout = self._log_stdout
self._pip_caller.on_log_stderr = self._log_stderr
@@ -83,6 +85,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
repository_ttl=24*60,
pip=None,
pip_args=None,
pip_force_user=False,
dependency_links=False,
hidden=[]
)
@@ -93,6 +96,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
new_pip = self._settings.get(["pip"])
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
if old_pip != new_pip:
self._pip_caller.configured = new_pip
try:
@@ -113,7 +117,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def get_template_configs(self):
return [
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True)
dict(type="settings", name=gettext("Plugin Manager"), template="pluginmanager_settings.jinja2", custom_bindings=True),
dict(type="about", name=gettext("Plugin Licenses"), template="pluginmanager_about.jinja2")
]
def get_template_vars(self):
plugins = sorted(self._get_plugins(), key=lambda x: x["name"].lower())
return dict(
all=plugins,
thirdparty=filter(lambda p: not p["bundled"], plugins)
)
def get_template_types(self, template_sorting, template_rules, *args, **kwargs):
return [
("about_thirdparty", dict(), dict(template=lambda x: x + "_about_thirdparty.jinja2"))
]
##~~ BlueprintPlugin
@@ -169,27 +186,24 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if not admin_permission.can():
return make_response("Insufficient rights", 403)
plugins = self._plugin_manager.plugins
result = []
for name, plugin in plugins.items():
result.append(self._to_external_representation(plugin))
if "refresh_repository" in request.values and request.values["refresh_repository"] in valid_boolean_trues:
self._repository_available = self._refresh_repository()
return jsonify(plugins=result,
return jsonify(plugins=self._get_plugins(),
repository=dict(
available=self._repository_available,
plugins=self._repository_plugins
),
os=self._get_os(),
octoprint=self._get_octoprint_version(),
octoprint=self._get_octoprint_version_string(),
pip=dict(
available=self._pip_caller.available,
command=self._pip_caller.command,
version=self._pip_caller.version_string,
install_dir=self._pip_caller.install_dir,
use_sudo=self._pip_caller.use_sudo,
use_user=self._pip_caller.use_user,
virtual_env=self._pip_caller.virtual_env,
additional_args=self._settings.get(["pip_args"])
))
@@ -323,12 +337,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._send_result_notification("install", result)
return jsonify(result)
self._plugin_manager.mark_plugin(new_plugin_key, uninstalled=False)
self._plugin_manager.reload_plugins()
needs_restart = self._plugin_manager.is_restart_needing_plugin(new_plugin) or new_plugin_key in all_plugins_before or reinstall is not None
needs_refresh = new_plugin.implementation and isinstance(new_plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
is_reinstall = self._plugin_manager.is_plugin_marked(new_plugin_key, "uninstalled")
self._plugin_manager.mark_plugin(new_plugin_key,
uninstalled=False,
installed=not is_reinstall and needs_restart)
self._plugin_manager.log_all_plugins()
result = dict(result=True, url=url, needs_restart=needs_restart, needs_refresh=needs_refresh, was_reinstalled=new_plugin_key in all_plugins_before or reinstall is not None, plugin=self._to_external_representation(new_plugin))
@@ -337,10 +354,13 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
def command_uninstall(self, plugin):
if plugin.key == "pluginmanager":
return make_response("Can't uninstall Plugin Manager", 400)
return make_response("Can't uninstall Plugin Manager", 403)
if not plugin.managable:
return make_response("Plugin is not managable and hence cannot be uninstalled", 403)
if plugin.bundled:
return make_response("Bundled plugins cannot be uninstalled", 400)
return make_response("Bundled plugins cannot be uninstalled", 403)
if plugin.origin is None:
self._logger.warn(u"Trying to uninstall plugin {plugin} but origin is unknown".format(**locals()))
@@ -384,7 +404,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
self._plugin_manager.mark_plugin(plugin.key, uninstalled=True)
was_pending_install = self._plugin_manager.is_plugin_marked(plugin.key, "installed")
self._plugin_manager.mark_plugin(plugin.key,
uninstalled=not was_pending_install and needs_restart,
installed=False)
if not needs_restart:
try:
@@ -447,8 +470,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if "--process-dependency-links" in args:
self._log_message(u"Installation needs to process external dependencies, that might make it take a bit longer than usual depending on the pip version")
if self._pip_caller < self._pip_version_dependency_links:
args.remove("--process-dependency-links")
additional_args = self._settings.get(["pip_args"])
if additional_args:
@@ -550,9 +571,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return False
current_os = self._get_os()
octoprint_version = self._get_octoprint_version()
if "-" in octoprint_version:
octoprint_version = octoprint_version[:octoprint_version.find("-")]
octoprint_version = self._get_octoprint_version(base=True)
def map_repository_entry(entry):
result = dict(entry)
@@ -577,12 +596,11 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_plugins = map(map_repository_entry, repo_data)
return True
def _is_octoprint_compatible(self, octoprint_version_string, compatibility_entries):
def _is_octoprint_compatible(self, octoprint_version, compatibility_entries):
"""
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
"""
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
for octo_compat in compatibility_entries:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
@@ -611,9 +629,42 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
else:
return "unknown"
def _get_octoprint_version(self):
from octoprint._version import get_versions
return get_versions()["version"]
def _get_octoprint_version_string(self):
return VERSION
def _get_octoprint_version(self, base=False):
octoprint_version_string = self._get_octoprint_version_string()
if "-" in octoprint_version_string:
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
if base:
if isinstance(octoprint_version, tuple):
# old setuptools
base_version = []
for part in octoprint_version:
if part.startswith("*"):
break
base_version.append(part)
base_version.append("*final")
octoprint_version = tuple(base_version)
else:
# new setuptools
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
return octoprint_version
def _get_plugins(self):
plugins = self._plugin_manager.plugins
hidden = self._settings.get(["hidden"])
result = []
for name, plugin in plugins.items():
if name in hidden:
continue
result.append(self._to_external_representation(plugin))
return result
def _to_external_representation(self, plugin):
return dict(
@@ -625,11 +676,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
url=plugin.url,
license=plugin.license,
bundled=plugin.bundled,
managable=plugin.managable,
enabled=plugin.enabled,
pending_enable=(not plugin.enabled and plugin.key in self._pending_enable),
pending_disable=(plugin.enabled and plugin.key in self._pending_disable),
pending_install=(plugin.key in self._pending_install),
pending_uninstall=(plugin.key in self._pending_uninstall),
pending_install=(self._plugin_manager.is_plugin_marked(plugin.key, "installed")),
pending_uninstall=(self._plugin_manager.is_plugin_marked(plugin.key, "uninstalled")),
origin=plugin.origin.type
)
@@ -645,5 +697,6 @@ def __plugin_load__():
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize
"octoprint.server.http.bodysize": __plugin_implementation__.increase_upload_bodysize,
"octoprint.ui.web.templatetypes": __plugin_implementation__.get_template_types
}
@@ -1,3 +1,70 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
} else {
factory(window.OctoPrint);
}
})(window || this, function(OctoPrint) {
var exports = {};
exports.get = function(refresh, opts) {
return OctoPrint.get(OctoPrint.getSimpleApiUrl("pluginmanager") + ((refresh) ? "?refresh_repository=true" : ""), opts);
};
exports.getWithRefresh = function(opts) {
return exports.get(true, opts);
};
exports.getWithoutRefresh = function(opts) {
return exports.get(false, opts);
};
exports.install = function(pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks
};
return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts);
};
exports.reinstall = function(plugin, pluginUrl, dependencyLinks, opts) {
var data = {
url: pluginUrl,
dependency_links: !!dependencyLinks,
reinstall: plugin,
force: true
};
return OctoPrint.simpleApiCommand("pluginmanager", "install", data, opts);
};
exports.uninstall = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
exports.enable = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "enable", data, opts);
};
exports.disable = function(plugin, opts) {
var data = {
plugin: plugin
};
return OctoPrint.simpleApiCommand("pluginmanager", "disable", data, opts);
};
exports.upload = function(file) {
return OctoPrint.upload(OctoPrint.getBlueprintUrl("pluginmanager") + "upload_archive", file);
};
OctoPrint.plugins.pluginmanager = exports;
});
$(function() {
function PluginManagerViewModel(parameters) {
var self = this;
@@ -5,11 +72,13 @@ $(function() {
self.loginState = parameters[0];
self.settingsViewModel = parameters[1];
self.printerState = parameters[2];
self.systemViewModel = parameters[3];
self.config_repositoryUrl = ko.observable();
self.config_repositoryTtl = ko.observable();
self.config_pipCommand = ko.observable();
self.config_pipAdditionalArgs = ko.observable();
self.config_pipForceUser = ko.observable();
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
@@ -82,14 +151,41 @@ $(function() {
self.pipAvailable = ko.observable(false);
self.pipCommand = ko.observable();
self.pipVersion = ko.observable();
self.pipInstallDir = ko.observable();
self.pipUseUser = ko.observable();
self.pipUseSudo = ko.observable();
self.pipVirtualEnv = ko.observable();
self.pipAdditionalArgs = ko.observable();
self.pipUseSudoString = ko.computed(function() {
return self.pipUseSudo() ? "yes" : "no";
});
self.pipUseUserString = ko.computed(function() {
return self.pipUseUser() ? "yes" : "no";
});
self.pipVirtualEnvString = ko.computed(function() {
return self.pipVirtualEnv() ? "yes" : "no";
});
self.working = ko.observable(false);
self.workingTitle = ko.observable();
self.workingDialog = undefined;
self.workingOutput = undefined;
self.restartCommandSpec = undefined;
self.systemViewModel.systemActions.subscribe(function() {
var lastResponse = self.systemViewModel.lastCommandResponse;
if (!lastResponse || !lastResponse.core) {
self.restartCommandSpec = undefined;
return;
}
var restartSpec = _.filter(lastResponse.core, function(spec) { return spec.action == "restart" });
self.restartCommandSpec = restartSpec != undefined && restartSpec.length > 0 ? restartSpec[0] : undefined;
});
self.notifications = [];
self.enableManagement = ko.computed(function() {
return !self.printerState.isPrinting();
});
@@ -101,6 +197,7 @@ $(function() {
self.enableUninstall = function(data) {
return self.enableManagement()
&& (data.origin != "entry_point" || self.pipAvailable())
&& data.managable
&& !data.bundled
&& data.key != 'pluginmanager'
&& !data.pending_uninstall;
@@ -211,12 +308,18 @@ $(function() {
if (data.available) {
self.pipCommand(data.command);
self.pipVersion(data.version);
self.pipInstallDir(data.install_dir);
self.pipUseUser(data.use_user);
self.pipUseSudo(data.use_sudo);
self.pipVirtualEnv(data.virtual_env);
self.pipAdditionalArgs(data.additional_args);
} else {
self.pipCommand(undefined);
self.pipVersion(undefined);
self.pipInstallDir(undefined);
self.pipUseUser(undefined);
self.pipUseSudo(undefined);
self.pipVirtualEnv(undefined);
self.pipAdditionalArgs(undefined);
}
};
@@ -226,12 +329,8 @@ $(function() {
return;
}
$.ajax({
url: API_BASEURL + "plugin/pluginmanager" + ((includeRepo) ? "?refresh_repository=true" : ""),
type: "GET",
dataType: "json",
success: self.fromResponse
});
OctoPrint.plugins.pluginmanager.get(includeRepo)
.done(self.fromResponse);
};
self.togglePlugin = function(data) {
@@ -245,19 +344,25 @@ $(function() {
if (data.key == "pluginmanager") return;
var command = self._getToggleCommand(data);
var onSuccess = self.requestData,
onError = function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
})
};
var payload = {plugin: data.key};
self._postCommand(command, payload, function(response) {
self.requestData();
}, function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
})
});
if (self._getToggleCommand(data) == "enable") {
OctoPrint.plugins.pluginmanager.enable(data.key)
.done(onSuccess)
.fail(onError);
} else {
OctoPrint.plugins.pluginmanager.disable(data.key)
.done(onSuccess)
.fail(onError);
}
};
self.showRepository = function() {
@@ -277,11 +382,7 @@ $(function() {
return;
}
if (self.installed(data)) {
self.installPlugin(data.archive, data.title, data.id, data.follow_dependency_links || self.followDependencyLinks());
} else {
self.installPlugin(data.archive, data.title, undefined, data.follow_dependency_links || self.followDependencyLinks());
}
self.installPlugin(data.archive, data.title, (self.installed(data) ? data.id : undefined), data.follow_dependency_links || self.followDependencyLinks());
};
self.installPlugin = function(url, name, reinstall, followDependencyLinks) {
@@ -316,26 +417,33 @@ $(function() {
}
self._markWorking(workTitle, workText);
var command = "install";
var payload = {url: url, dependency_links: followDependencyLinks};
if (reinstall) {
payload["plugin"] = reinstall;
payload["force"] = true;
}
var onSuccess = function() {
self.requestData();
self.installUrl("");
},
onError = function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
},
onAlways = function() {
self._markDone();
};
self._postCommand(command, payload, function(response) {
self.requestData();
self._markDone();
self.installUrl("");
}, function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
self._markDone();
});
if (reinstall) {
OctoPrint.plugins.pluginmanager.reinstall(reinstall, url, followDependencyLinks)
.done(onSuccess)
.fail(onError)
.always(onAlways);
} else {
OctoPrint.plugins.pluginmanager.install(url, followDependencyLinks)
.done(onSuccess)
.fail(onError)
.always(onAlways);
}
};
self.uninstallPlugin = function(data) {
@@ -352,20 +460,19 @@ $(function() {
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
var command = "uninstall";
var payload = {plugin: data.key};
self._postCommand(command, payload, function(response) {
self.requestData();
self._markDone();
}, function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
OctoPrint.plugins.pluginmanager.uninstall(data.key)
.done(self.requestData)
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
})
.always(function() {
self._markDone();
});
self._markDone();
});
};
self.refreshRepository = function() {
@@ -410,7 +517,8 @@ $(function() {
repository: repository,
repository_ttl: repositoryTtl,
pip: pipCommand,
pip_args: pipArgs
pip_args: pipArgs,
pip_force_user: self.config_pipForceUser()
}
}
};
@@ -426,6 +534,7 @@ $(function() {
self.config_repositoryTtl(self.settingsViewModel.settings.plugins.pluginmanager.repository_ttl());
self.config_pipCommand(self.settingsViewModel.settings.plugins.pluginmanager.pip());
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
};
self.installed = function(data) {
@@ -441,15 +550,59 @@ $(function() {
};
self._displayNotification = function(response, titleSuccess, textSuccess, textRestart, textReload, titleError, textError) {
var notification;
var beforeClose = function(notification) {
self.notifications = _.without(self.notifications, notification);
};
if (response.result) {
if (response.needs_restart) {
new PNotify({
var options = {
title: titleSuccess,
text: textRestart,
buttons: {
closer: false,
sticker: false
},
callbacks: {
before_close: beforeClose
},
hide: false
});
};
if (self.restartCommandSpec) {
options.confirm = {
confirm: true,
buttons: [{
text: gettext("Restart now"),
click: function () {
showConfirmationDialog({
message: gettext("This will restart your OctoPrint server."),
onproceed: function() {
OctoPrint.system.executeCommand("core", "restart")
.done(function() {
new PNotify({
title: gettext("Restart in progress"),
text: gettext("The server is now being restarted in the background")
})
})
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Trying to restart the server produced an error, please check octoprint.log for details. You'll have to restart manually.")
})
});
}
});
}
}]
}
}
notification = PNotify.singleButtonNotify(options);
} else if (response.needs_refresh) {
new PNotify({
notification = PNotify.singleButtonNotify({
title: titleSuccess,
text: textReload,
confirm: {
@@ -465,51 +618,35 @@ $(function() {
closer: false,
sticker: false
},
callbacks: {
before_close: beforeClose
},
hide: false
})
} else {
new PNotify({
notification = new PNotify({
title: titleSuccess,
text: textSuccess,
type: "success",
callbacks: {
before_close: beforeClose
},
hide: false
})
}
} else {
new PNotify({
notification = new PNotify({
title: titleError,
text: textError,
type: "error",
callbacks: {
before_close: beforeClose
},
hide: false
});
}
};
self._postCommand = function (command, data, successCallback, failureCallback, alwaysCallback, timeout) {
var payload = _.extend(data, {command: command});
var params = {
url: API_BASEURL + "plugin/pluginmanager",
type: "POST",
dataType: "json",
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function(response) {
if (successCallback) successCallback(response);
},
error: function() {
if (failureCallback) failureCallback();
},
complete: function() {
if (alwaysCallback) alwaysCallback();
}
};
if (timeout != undefined) {
params.timeout = timeout;
}
$.ajax(params);
self.notifications.push(notification);
};
self._markWorking = function(title, line) {
@@ -554,6 +691,16 @@ $(function() {
self.onUserLoggedIn = function(user) {
if (user.admin) {
self.requestData();
} else {
self.onUserLoggedOut();
}
};
self.onUserLoggedOut = function() {
if (self.notifications) {
_.each(self.notifications, function(notification) {
notification.remove();
});
}
};
@@ -707,5 +854,9 @@ $(function() {
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([PluginManagerViewModel, ["loginStateViewModel", "settingsViewModel", "printerStateViewModel"], "#settings_plugin_pluginmanager"]);
ADDITIONAL_VIEWMODELS.push([
PluginManagerViewModel,
["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel"],
"#settings_plugin_pluginmanager"
]);
});
@@ -0,0 +1,18 @@
<h3>Plugin Licenses</h3>
<ul>
{% for plugin in plugin_pluginmanager_thirdparty %}
<li><a href="{{ plugin.url }}">{{ plugin.name }}</a>: {{ plugin.license }}</li>
{% endfor %}
</ul>
{% if templates.plugin_pluginmanager_about_thirdparty.order %}
<h3>Licenses of Plugin Dependencies</h3>
{% for key in templates.plugin_pluginmanager_about_thirdparty.order %}
{% set heading, config = templates.plugin_pluginmanager_about_thirdparty.entries[key] %}
<h4>{{ heading }}</h4>
{% include config.template ignore missing %}
{% endfor %}
{% endif %}
@@ -6,8 +6,9 @@
{% macro pluginmanager_nopip() %}
<div class="alert" data-bind="visible: !pipAvailable()">{% trans %}
The <code>pip</code> command could not be found.
Please configure it manually. No installation and uninstallation of plugin
The <code>pip</code> command could not be found or does not work correctly
for this installation of OctoPrint - please consult the log file for details
and if necessary configure it manually. No installation and uninstallation of plugin
packages is possible while <code>pip</code> is unavailable.
{% endtrans %}</div>
{% endmacro %}
@@ -42,7 +43,7 @@
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i title="Restart needed" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_uninstall"></i> <i title="Uninstalled" class="icon-remove" data-bind="visible: pending_uninstall"></i></div>
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="icon-th-large" data-bind="visible: bundled"></i> <i class="icon-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="icon-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="icon-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="icon-minus" data-bind="visible: pending_uninstall"></i></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="icon-home"></i> <a data-bind="attr: {href: url}">{{ _('Homepage') }}</a></small>
@@ -71,9 +72,22 @@
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
<p class="muted" data-bind="visible: pipAvailable()">
<small>Using pip at "<span data-bind="text: pipCommand"></span>" (Version <span data-bind="text: pipVersion"></span><span data-bind="visible: pipAdditionalArgs">, additional arguments: <span data-bind="text: pipAdditionalArgs"></span></span>)</small>
</p>
<div class="muted" data-bind="visible: pipAvailable()">
<div>
<small>
<a href="#" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('icon-caret-right icon-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow icon-caret-right"></i> Using pip at "<span data-bind="text: pipCommand"></span>", Version <span data-bind="text: pipVersion"></span>
</a>
</small>
</div>
<div class="hide">
<small>
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>, sudo: <span data-bind="text: pipUseSudoString"></span>)<br />
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
</small>
</div>
</div>
<div id="settings_plugin_pluginmanager_workingdialog" class="modal hide fade">
<div class="modal-header">
@@ -99,8 +113,10 @@
{{ pluginmanager_sudopip() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='http://plugins.octoprint.org') }}
<a class="dropdown-toggle pull-right" data-toggle="dropdown" href="#">
<span class="icon-wrench"></span>
<div class="dropdown pull-right">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<span class="icon-wrench"></span>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('title'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'title' ? 'visible' : 'hidden'}"></i> {{ _('Sort by title') }} ({{ _('ascending') }})</a></li>
<li><a href="#" data-bind="click: function() { repositoryplugins.changeSorting('published'); }"><i class="icon-ok" data-bind="style: {visibility: repositoryplugins.currentSorting() == 'published' ? 'visible' : 'hidden'}"></i> {{ _('Sort by publication date') }} ({{ _('descending') }})</a></li>
@@ -110,7 +126,7 @@
<li class="divider"></li>
<li><a href="#" data-bind="click: function() { refreshRepository(); }"><i class="icon-refresh"></i> {{ _('Refresh list from repository') }}</a></li>
</ul>
</a>
</div>
</h4>
<form class="form-search" data-bind="submit: performRepositorySearch">
@@ -205,19 +221,31 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
<legend>{{ _('pip configuration') }}</legend>
<div class="control-group" title="{{ _('pip command to use for managing plugins. You might have to configure this if auto detection fails.') }}">
<label class="control-label">{{ _('pip command') }}</label>
<label class="control-label">{{ _('Command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipCommand" placeholder="{{ _('Autodetect') }}">
<span class="help-inline">{{ _('<strong>Only</strong> set this if OctoPrint cannot autodetect the path to <code>pip</code> to use for managing plugins.') }}</span>
</div>
</div>
<div class="control-group" title="{{ _('Additional arguments for pip command. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Additional pip arguments') }}</label>
<label class="control-label">{{ _('Additional arguments') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: config_pipForceUser"> {{ _('Force the user of the <code>--user</code> flag with <code>pip install</code>') }}
</label>
</div>
</div>
<legend>{{ _('Plugin repository configuration') }}</legend>
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository URL') }}</label>
<div class="controls">
@@ -12,13 +12,15 @@ import flask
import os
import threading
import time
import logging
import logging.handlers
import hashlib
from . import version_checks, updaters, exceptions, util
from . import version_checks, updaters, exceptions, util, cli
from octoprint.server.util.flask import restricted_access
from octoprint.server import admin_permission
from octoprint.server import admin_permission, VERSION, REVISION
from octoprint.util import dict_merge
import octoprint.settings
@@ -29,7 +31,8 @@ import octoprint.settings
class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin):
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin):
def __init__(self):
self._update_in_progress = False
self._configured_checks_mutex = threading.Lock()
@@ -41,7 +44,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_path = None
self._version_cache_dirty = False
self._console_logger = None
def initialize(self):
self._console_logger = logging.getLogger("octoprint.plugins.softwareupdate.console")
self._version_cache_ttl = self._settings.get_int(["cache_ttl"]) * 60
self._version_cache_path = os.path.join(self.get_plugin_data_folder(), "versioncache.yaml")
self._load_version_cache()
@@ -53,6 +60,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._plugin_lifecycle_manager.add_callback("enabled", refresh_checks)
self._plugin_lifecycle_manager.add_callback("disabled", refresh_checks)
def on_startup(self, host, port):
console_logging_handler = logging.handlers.RotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="console"), maxBytes=2*1024*1024)
console_logging_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
console_logging_handler.setLevel(logging.DEBUG)
self._console_logger.addHandler(console_logging_handler)
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
def _get_configured_checks(self):
with self._configured_checks_mutex:
if self._refresh_configured_checks or self._configured_checks is None:
@@ -335,7 +351,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
@restricted_access
def check_for_update(self):
if "check" in flask.request.values:
check_targets = map(str.strip, flask.request.values["check"].split(","))
check_targets = map(lambda x: x.strip(), flask.request.values["check"].split(","))
else:
check_targets = None
@@ -365,7 +381,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
json_data = flask.request.json
if "check" in json_data:
check_targets = map(str.strip, json_data["check"])
check_targets = map(lambda x: x.strip(), json_data["check"])
else:
check_targets = None
@@ -425,22 +441,33 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._logger.warn("Unknown update check type for target {}: {}".format(target, check.get("type", "<n/a>")))
continue
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown")), target_information)
target_information = dict_merge(dict(local=dict(name="unknown", value="unknown"), remote=dict(name="unknown", value="unknown", release_notes=None)), target_information)
update_available = update_available or target_update_available
update_possible = update_possible or (target_update_possible and target_update_available)
from octoprint._version import get_versions
octoprint_version = get_versions()["version"]
local_name = target_information["local"]["name"]
local_value = target_information["local"]["value"]
release_notes = None
if target_information and target_information["remote"] and target_information["remote"]["value"]:
if "release_notes" in populated_check and populated_check["release_notes"]:
release_notes = populated_check["release_notes"]
elif "release_notes" in target_information["remote"]:
release_notes = target_information["remote"]["release_notes"]
if release_notes:
release_notes = release_notes.format(octoprint_version=VERSION,
target_name=target_information["remote"]["name"],
target_version=target_information["remote"]["value"])
information[target] = dict(updateAvailable=target_update_available,
updatePossible=target_update_possible,
information=target_information,
displayName=populated_check["displayName"],
displayVersion=populated_check["displayVersion"].format(octoprint_version=octoprint_version, local_name=local_name, local_value=local_value),
check=populated_check)
displayVersion=populated_check["displayVersion"].format(octoprint_version=VERSION, local_name=local_name, local_value=local_value),
check=populated_check,
releaseNotes=release_notes)
if self._version_cache_dirty:
self._save_version_cache()
@@ -492,9 +519,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_dirty = True
return information, update_available, update_possible
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message("softwareupdate", dict(type=message_type, data=data))
def perform_updates(self, check_targets=None, force=False):
"""
Performs the updates for the given check_targets. Will update all possible targets by default.
@@ -524,7 +548,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
updater_thread.daemon = False
updater_thread.start()
return to_be_updated, dict((key, check["displayName"] if "displayName" in check else key) for key, check in populated_checks.items() if key in to_be_updated)
check_data = dict((key, check["displayName"] if "displayName" in check else key) for key, check in populated_checks.items() if key in to_be_updated)
return to_be_updated, check_data
def _update_worker(self, checks, check_targets, force):
@@ -616,33 +641,34 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
### The actual update procedure starts here...
populated_check = self._populated_check(target, check)
try:
self._logger.info("Starting update of %s to %s..." % (target, target_version))
self._send_client_message("updating", dict(target=target, version=target_version))
self._send_client_message("updating", dict(target=target, version=target_version, name=populated_check["displayName"]))
updater = self._get_updater(target, check)
if updater is None:
raise exceptions.UnknownUpdateType()
update_result = updater.perform_update(target, check, target_version)
update_result = updater.perform_update(target, populated_check, target_version, log_cb=self._log)
target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version))
except exceptions.UnknownUpdateType:
self._logger.warn("Update of %s can not be performed, unknown update type" % target)
self._send_client_message("update_failed", dict(target=target, version=target_version, reason="Unknown update type"))
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="Unknown update type"))
return False, None
except Exception as e:
self._logger.exception("Update of %s can not be performed" % target)
if not "ignorable" in check or not check["ignorable"]:
if not "ignorable" in populated_check or not populated_check["ignorable"]:
target_error = True
if isinstance(e, exceptions.UpdateError):
target_result = ("failed", e.data)
self._send_client_message("update_failed", dict(target=target, version=target_version, reason=e.data))
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason=e.data))
else:
target_result = ("failed", None)
self._send_client_message("update_failed", dict(target=target, version=target_version, reason="unknown"))
self._send_client_message("update_failed", dict(target=target, version=target_version, name=populated_check["displayName"], reason="unknown"))
else:
# make sure that any external changes to config.yaml are loaded into the system
@@ -689,12 +715,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
result["displayName"] = check.get("displayName", gettext("OctoPrint"))
result["displayVersion"] = check.get("displayVersion", "{octoprint_version}")
from octoprint._version import get_versions
versions = get_versions()
if check["type"] == "github_commit":
result["current"] = versions.get("full-revisionid", versions.get("full", "unknown"))
result["current"] = REVISION if REVISION else "unknown"
else:
result["current"] = versions["version"]
result["current"] = VERSION
else:
result["displayName"] = check.get("displayName", target)
result["displayVersion"] = check.get("displayVersion", check.get("current", "unknown"))
@@ -705,6 +729,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return result
def _log(self, lines, prefix=None, stream=None, strip=True):
if strip:
lines = map(lambda x: x.strip(), lines)
self._send_client_message("loglines", data=dict(loglines=[dict(line=line, stream=stream) for line in lines]))
for line in lines:
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(self._identifier, dict(type=message_type, data=data))
def _get_version_checker(self, target, check):
"""
Retrieves the version checker to use for given target and check configuration. Will raise an UnknownCheckType
@@ -745,6 +780,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
else:
raise exceptions.UnknownUpdateType()
__plugin_name__ = "Software Update"
__plugin_author__ = "Gina Häußge"
__plugin_url__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Software-Update"
@@ -762,4 +798,9 @@ def __plugin_load__():
util=util
)
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.cli.commands": cli.commands
}
+167
View File
@@ -0,0 +1,167 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
import sys
import requests.exceptions
import octoprint_client as client
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.argument("targets", nargs=-1)
def check_command(force, targets):
"""Check for updates."""
params = dict(force=force)
if targets:
params["check"] = ",".join(targets)
client.init_client(cli_group.settings)
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
data = r.json()
status = data["status"]
information = data["information"]
lines = []
octoprint_line = None
for key, info in information.items():
status_text = "Up to date"
if info["updateAvailable"]:
if info["updatePossible"]:
status_text = "Update available"
else:
status_text = "Update available (manual)"
line = "{}\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
if key == "octoprint":
octoprint_line = line
else:
lines.append(line)
lines.sort()
if octoprint_line:
lines = [octoprint_line] + lines
for line in lines:
click.echo(line)
click.echo()
if status == "current":
click.echo("Everything is up to date")
else:
click.echo("There are updates available!")
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@click.argument("targets", nargs=-1)
def update_command(force, targets):
"""Apply updates."""
data = dict(force=force)
if targets:
data["check"] = targets
client.init_client(cli_group.settings)
flags = dict(
waiting_for_restart=False,
seen_close=False
)
def on_message(ws, msg_type, msg):
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
return
plugin_message = msg["data"]
if not "type" in plugin_message:
return
plugin_message_type = plugin_message["type"]
plugin_message_data = plugin_message["data"]
if plugin_message_type == "updating":
click.echo("Updating {} to {}...".format(plugin_message_data["name"], plugin_message_data["target"]))
elif plugin_message_type == "update_failed":
click.echo("\t... failed: {}".format(plugin_message_data["reason"]))
elif plugin_message_type == "loglines" and "loglines" in plugin_message_data:
for entry in plugin_message_data["loglines"]:
prefix = ">>> " if entry["stream"] == "call" else ""
error = entry["stream"] == "stderr"
click.echo("\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")), err=error)
elif plugin_message_type == "success" or plugin_message_type == "restart_manually":
results = plugin_message_data["results"] if "results" in plugin_message_data else dict()
if results:
click.echo("The update finished successfully.")
if plugin_message_type == "restart_manually":
click.echo("Please restart the OctoPrint server.")
else:
click.echo("No update necessary")
ws.close()
elif plugin_message_type == "restarting":
flags["waiting_for_restart"] = True
click.echo("Restarting to apply changes...")
elif plugin_message_type == "failure":
click.echo("Error")
ws.close()
def on_open(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(" Reconnected!")
else:
click.echo("Connected to server...")
def on_close(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(".", nl=False)
else:
flags["seen_close"] = True
click.echo("Disconnected from server...")
socket = client.connect_socket(on_message=on_message,
on_open=on_open,
on_close=on_close)
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
data = r.json()
to_be_updated = data["order"]
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if not name in checks else checks[name]))
socket.wait()
if flags["waiting_for_restart"]:
if socket.reconnect(timeout=60):
click.echo("The update finished successfully.")
else:
click.echo("The update finished successfully but the server apparently didn't restart as expected.")
click.echo("Please restart the OctoPrint server.")
return [check_command, update_command]
@@ -1,5 +1,5 @@
#!/bin/env python
from __future__ import absolute_import
from __future__ import absolute_import, print_function
__author__ = "Gina Haeussge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
@@ -7,9 +7,76 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import errno
import subprocess
import sys
def _log_call(*lines):
_log(lines, prefix=">", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=" ", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix=" ", stream="stderr")
def _log(lines, prefix=None, stream=None):
output_stream = sys.stdout
if stream == "stderr":
output_stream = sys.stderr
for line in lines:
print(u"{} {}".format(prefix, line.strip()), file=output_stream)
def _execute(command, **kwargs):
import sarge
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
_log_call(joined_command)
kwargs.update(dict(async=True, stdout=sarge.Capture(), stderr=sarge.Capture()))
p = sarge.run(command, **kwargs)
p.wait_events()
all_stdout = []
all_stderr = []
try:
while p.returncode is None:
line = p.stderr.readline(timeout=0.5)
if line:
_log_stderr(line)
all_stderr.append(line)
line = p.stdout.readline(timeout=0.5)
if line:
_log_stdout(line)
all_stdout.append(line)
p.commands[0].poll()
finally:
p.close()
stderr = p.stderr.text
if stderr:
split_lines = stderr.split("\n")
_log_stderr(*split_lines)
all_stderr += split_lines
stdout = p.stdout.text
if stdout:
split_lines = stdout.split("\n")
_log_stdout(*split_lines)
all_stdout += split_lines
return p.returncode, all_stdout, all_stderr
def _get_git_executables():
GITS = ["git"]
@@ -18,7 +85,7 @@ def _get_git_executables():
return GITS
def _git(args, cwd, hide_stderr=False, verbose=False, git_executable=None):
def _git(args, cwd, verbose=False, git_executable=None):
if git_executable is not None:
commands = [git_executable]
else:
@@ -26,10 +93,8 @@ def _git(args, cwd, hide_stderr=False, verbose=False, git_executable=None):
for c in commands:
try:
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
returncode, stdout, stderr = _execute([c] + args, cwd=cwd)
return returncode, "\n".join(stdout), "\n".join(stderr)
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
@@ -43,37 +108,20 @@ def _git(args, cwd, hide_stderr=False, verbose=False, git_executable=None):
print("unable to find command, tried %s" % (commands,))
return None, None
stdout = p.communicate()[0].strip()
if sys.version >= '3':
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % args[0])
return p.returncode, stdout
def _python(args, cwd, python_executable, sudo=False):
command = [python_executable] + args
if sudo:
command = ["sudo"] + command
try:
p = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return _execute(command, cwd=cwd)
except:
return None, None
stdout = p.communicate()[0].strip()
if sys.version >= "3":
stdout = stdout.decode()
return p.returncode, stdout
def update_source(git_executable, folder, target, force=False):
print(">>> Running: git diff --shortstat")
returncode, stdout = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode %d: %s" % (returncode, stdout))
if stdout and stdout.strip():
@@ -84,7 +132,7 @@ def update_source(git_executable, folder, target, force=False):
patch = os.path.join(folder, "%s-preupdate.patch" % timestamp)
print(">>> Running: git diff and saving output to %s" % timestamp)
returncode, stdout = _git(["diff"], folder, git_executable=git_executable)
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to %s" % patch)
@@ -92,43 +140,39 @@ def update_source(git_executable, folder, target, force=False):
f.write(stdout)
print(">>> Running: git reset --hard")
returncode, stdout = _git(["reset", "--hard"], folder, git_executable=git_executable)
returncode, stdout, stderr = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode %d: %s" % (returncode, stdout))
print(">>> Running: git pull")
returncode, stdout = _git(["pull"], folder, git_executable=git_executable)
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode %d: %s" % (returncode, stdout))
print(stdout)
if force:
reset_command = ["reset"]
reset_command += [target]
print(">>> Running: git %s" % " ".join(reset_command))
returncode, stdout = _git(reset_command, folder, git_executable=git_executable)
returncode, stdout, stderr = _git(reset_command, folder, git_executable=git_executable)
if returncode != 0:
raise RuntimeError("Error while updating, \"git %s\" failed with returncode %d: %s" % (" ".join(reset_command), returncode, stdout))
print(stdout)
def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout = _python(["setup.py", "clean"], folder, python_executable)
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode != 0:
print("\"python setup.py clean\" failed with returncode %d: %s" % (returncode, stdout))
print("Continuing anyways")
print(stdout)
print(">>> Running: python setup.py install")
args = ["setup.py", "install"]
if user:
args.append("--user")
returncode, stdout = _python(args, folder, python_executable, sudo=sudo)
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
if returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode %d: %s" % (returncode, stdout))
print(stdout)
def parse_arguments():
@@ -1 +1 @@
td.settings_plugin_softwareupdate_column_update{width:16px}
td.settings_plugin_softwareupdate_column_update{width:16px}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:bold}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:bold;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:bold;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -1,3 +1,43 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
} else {
factory(window.OctoPrint);
}
})(window || this, function(OctoPrint) {
var exports = {};
var url = OctoPrint.getBlueprintUrl("softwareupdate");
var checkUrl = url + "check";
var updateUrl = url + "update";
exports.check = function(force, opts) {
return OctoPrint.get(checkUrl + ((!!force) ? "?force=true" : ""), opts);
};
exports.update = function(entries, force, opts) {
entries = entries || [];
if (typeof entries == "string") {
entries = [entries];
}
var data = {
entries: entries,
force: !!force
};
return OctoPrint.postJson(updateUrl, data, opts);
};
exports.updateAll = function(force, opts) {
var data = {
force: !!force
};
return OctoPrint.postJson(updateUrl, data, opts);
};
OctoPrint.plugins.softwareupdate = exports;
});
$(function() {
function SoftwareUpdateViewModel(parameters) {
var self = this;
@@ -7,12 +47,20 @@ $(function() {
self.settings = parameters[2];
self.popup = undefined;
self.forceUpdate = false;
self.updateInProgress = false;
self.waitingForRestart = false;
self.restartTimeout = undefined;
self.currentlyBeingUpdated = [];
self.working = ko.observable(false);
self.workingTitle = ko.observable();
self.workingDialog = undefined;
self.workingOutput = undefined;
self.loglines = ko.observableArray([]);
self.octoprintUnconfigured = ko.observable();
self.octoprintUnreleased = ko.observable();
@@ -21,6 +69,7 @@ $(function() {
self.config_checkType = ko.observable();
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
self.config_availableCheckTypes = [
{"key": "github_release", "name": gettext("Release")},
@@ -49,6 +98,10 @@ $(function() {
5
);
self.availableAndPossible = ko.computed(function() {
return _.filter(self.versions.items(), function(info) { return info.updateAvailable && info.updatePossible; });
});
self.onUserLoggedIn = function() {
self.performCheck();
};
@@ -84,7 +137,10 @@ $(function() {
self.configurationDialog.modal();
};
self.savePluginSettings = function() {
self.savePluginSettings = function(viewModel, event) {
var target = $(event.target);
target.prepend('<i class="icon-spinner icon-spin"></i> ');
var data = {
plugins: {
softwareupdate: {
@@ -94,10 +150,16 @@ $(function() {
}
}
};
self.settings.saveData(data, function() {
self.configurationDialog.modal("hide");
self._copyConfig();
self.performCheck();
self.settings.saveData(data, {
success: function() {
self.configurationDialog.modal("hide");
self._copyConfig();
self.performCheck();
},
complete: function() {
$("i.icon-spinner", target).remove();
},
sending: true
});
};
@@ -118,6 +180,18 @@ $(function() {
if (!value.hasOwnProperty("displayVersion") || value.displayVersion == "") {
value.displayVersion = value.information.local.name;
}
if (!value.hasOwnProperty("releaseNotes") || value.releaseNotes == "") {
value.releaseNotes = undefined;
}
var fullNameTemplate = gettext("%(name)s: %(version)s");
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: value.displayName, version: value.displayVersion});
var fullNameRemoteVars = {name: value.displayName, version: gettext("unknown")};
if (value.hasOwnProperty("information") && value.information.hasOwnProperty("remote") && value.information.remote.hasOwnProperty("name")) {
fullNameRemoteVars.version = value.information.remote.name;
}
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
versions.push(value);
});
@@ -143,22 +217,24 @@ $(function() {
}
if (data.status == "updateAvailable" || data.status == "updatePossible") {
var text = gettext("There are updates available for the following components:");
var text = "<div class='softwareupdate_notification'>" + gettext("There are updates available for the following components:");
text += "<ul>";
text += "<ul class='icons-ul'>";
_.each(self.versions.items(), function(update_info) {
if (update_info.updateAvailable) {
var displayName = update_info.key;
if (update_info.hasOwnProperty("displayName")) {
displayName = update_info.displayName;
}
text += "<li>" + displayName + (update_info.updatePossible ? " <i class=\"icon-ok\"></i>" : "") + "</li>";
text += "<li>"
+ "<i class='icon-li " + (update_info.updatePossible ? "icon-ok" : "icon-remove")+ "'></i>"
+ "<span class='name' title='" + update_info.fullNameRemote + "'>" + update_info.fullNameRemote + "</span>"
+ (update_info.releaseNotes ? "<a href=\"" + update_info.releaseNotes + "\" target=\"_blank\">" + gettext("Release Notes") + "</a>" : "")
+ "</li>";
}
});
text += "</ul>";
text += "<small>" + gettext("Those components marked with <i class=\"icon-ok\"></i> can be updated directly.") + "</small>";
text += "</div>";
var options = {
title: gettext("Update Available"),
text: text,
@@ -208,20 +284,10 @@ $(function() {
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isUser()) return;
var url = PLUGIN_BASEURL + "softwareupdate/check";
if (force) {
url += "?force=true";
}
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
OctoPrint.plugins.softwareupdate.check(force)
.done(function(data) {
self.fromCheckResponse(data, ignoreSeen, showIfNothingNew);
}
});
});
};
self._markNotificationAsSeen = function(data) {
@@ -257,7 +323,7 @@ $(function() {
return result;
};
self.performUpdate = function(force) {
self.performUpdate = function(force, items) {
self.updateInProgress = true;
var options = {
@@ -272,13 +338,12 @@ $(function() {
};
self._showPopup(options);
$.ajax({
url: PLUGIN_BASEURL + "softwareupdate/update",
type: "POST",
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify({force: (force == true)}),
error: function() {
OctoPrint.plugins.softwareupdate.updateAll(force, items)
.done(function(data) {
self.currentlyBeingUpdated = data.checks;
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
})
.fail(function() {
self.updateInProgress = false;
self._showPopup({
title: gettext("Update not started!"),
@@ -289,19 +354,13 @@ $(function() {
sticker: false
}
});
},
success: function(data) {
self.currentlyBeingUpdated = data.checks;
}
});
});
};
self.update = function(force) {
if (self.updateInProgress) return;
if (!self.loginState.isAdmin()) return;
force = (force == true);
if (self.printerState.isPrinting()) {
self._showPopup({
title: gettext("Can't update while printing"),
@@ -309,18 +368,58 @@ $(function() {
type: "error"
});
} else {
$("#confirmation_dialog .confirmation_dialog_message").text(gettext("This will update your OctoPrint installation and restart the server."));
$("#confirmation_dialog .confirmation_dialog_acknowledge").unbind("click");
$("#confirmation_dialog .confirmation_dialog_acknowledge").click(function(e) {
e.preventDefault();
$("#confirmation_dialog").modal("hide");
self.performUpdate(force);
});
$("#confirmation_dialog").modal("show");
self.forceUpdate = (force == true);
self.confirmationDialog.modal("show");
}
};
self.confirmUpdate = function() {
self.confirmationDialog.hide();
self.performUpdate(self.forceUpdate,
_.map(self.availableAndPossible(), function(info) { return info.key }));
};
self._showWorkingDialog = function(title) {
if (!self.loginState.isAdmin()) {
return;
}
self.working(true);
self.workingTitle(title);
self.workingDialog.modal("show");
};
self._markWorking = function(title, line, stream) {
if (stream === undefined) {
stream = "message";
}
self.loglines.removeAll();
self.loglines.push({line: line, stream: stream});
self._showWorkingDialog(title);
};
self._markDone = function(line, stream) {
if (stream === undefined) {
stream = "message";
}
self.working(false);
self.loglines.push({line: "", stream: stream});
self.loglines.push({line: line, stream: stream});
self._scrollWorkingOutputToEnd();
};
self._scrollWorkingOutputToEnd = function() {
self.workingOutput.scrollTop(self.workingOutput[0].scrollHeight - self.workingOutput.height());
};
self.onStartup = function() {
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
};
self.onServerDisconnect = function() {
if (self.restartTimeout !== undefined) {
clearTimeout(self.restartTimeout);
@@ -348,26 +447,51 @@ $(function() {
var options = undefined;
var restartType = undefined;
var title = undefined;
var text = undefined;
switch (messageType) {
case "loglines": {
if (self.working()) {
_.each(messageData.loglines, function(line) {
self.loglines.push(line);
});
self._scrollWorkingOutputToEnd();
}
break;
}
case "updating": {
console.log(JSON.stringify(messageData));
var name = self.currentlyBeingUpdated[messageData.target];
if (name == undefined) {
name = messageData.target;
if (!self.working()) {
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
}
text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: messageData.name, version: messageData.version});
self.loglines.push({line: "", stream: "separator"});
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self.loglines.push({line: text, stream: "message"});
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self._updatePopup({
text: _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: name, version: messageData.version})
text: text,
hide: false,
buttons: {
sticker: false
}
});
break;
}
case "restarting": {
console.log(JSON.stringify(messageData));
title = gettext("Update successful, restarting!");
text = gettext("The update finished successfully and the server will now be restarted.");
options = {
title: gettext("Update successful, restarting!"),
text: gettext("The update finished successfully and the server will now be restarted."),
title: title,
text: text,
type: "success",
hide: false,
buttons: {
@@ -375,11 +499,16 @@ $(function() {
}
};
self.loglines.push({line: text, stream: "message"});
self.waitingForRestart = true;
self.restartTimeout = setTimeout(function() {
title = gettext("Restart failed");
text = gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong.");
self._showPopup({
title: gettext("Restart failed"),
text: gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong."),
title: title,
text: text,
type: "error",
hide: false,
buttons: {
@@ -387,6 +516,8 @@ $(function() {
}
});
self.waitingForRestart = false;
self._markDone(text, "message_error");
}, 60000);
break;
@@ -394,14 +525,15 @@ $(function() {
case "restart_manually": {
console.log(JSON.stringify(messageData));
var restartType = messageData.restart_type;
var text = gettext("The update finished successfully, please restart OctoPrint now.");
restartType = messageData.restart_type;
text = gettext("The update finished successfully, please restart OctoPrint now.");
if (restartType == "environment") {
text = gettext("The update finished successfully, please reboot the server now.");
}
title = gettext("Update successful, restart required!");
options = {
title: gettext("Update successful, restart required!"),
title: title,
text: text,
type: "success",
hide: false,
@@ -410,18 +542,20 @@ $(function() {
}
};
self.updateInProgress = false;
self._markDone(text);
break;
}
case "restart_failed": {
var restartType = messageData.restart_type;
var text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
restartType = messageData.restart_type;
text = gettext("Restarting OctoPrint failed, please restart it manually. You might also want to consult the log file on what went wrong here.");
if (restartType == "environment") {
text = gettext("Rebooting the server failed, please reboot it manually. You might also want to consult the log file on what went wrong here.");
}
title = gettext("Restart failed");
options = {
title: gettext("Restart failed"),
test: gettext("The server apparently did not restart by itself, you'll have to do it manually. Please consult the log file on what went wrong."),
title: title,
test: text,
type: "error",
hide: false,
buttons: {
@@ -430,12 +564,15 @@ $(function() {
};
self.waitingForRestart = false;
self.updateInProgress = false;
self._markDone(text, "message_error");
break;
}
case "success": {
title = gettext("Update successful!");
text = gettext("The update finished successfully.");
options = {
title: gettext("Update successful!"),
text: gettext("The update finished successfully."),
title: title,
text: text,
type: "success",
hide: false,
buttons: {
@@ -443,12 +580,15 @@ $(function() {
}
};
self.updateInProgress = false;
self._markDone(text);
break;
}
case "error": {
title = gettext("Update failed!");
text = gettext("The update did not finish successfully. Please consult the log for details.");
self._showPopup({
title: gettext("Update failed!"),
text: gettext("The update did not finish successfully. Please consult the log for details."),
title: title,
text: text,
type: "error",
hide: false,
buttons: {
@@ -456,6 +596,7 @@ $(function() {
}
});
self.updateInProgress = false;
self._markDone(text, "message_error");
break;
}
case "update_versions": {
@@ -472,5 +613,9 @@ $(function() {
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([SoftwareUpdateViewModel, ["loginStateViewModel", "printerStateViewModel", "settingsViewModel"], document.getElementById("settings_plugin_softwareupdate")]);
ADDITIONAL_VIEWMODELS.push([
SoftwareUpdateViewModel,
["loginStateViewModel", "printerStateViewModel", "settingsViewModel"],
["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog"]
]);
});
@@ -1,3 +1,47 @@
td.settings_plugin_softwareupdate_column_update {
width: 16px;
}
}
#settings_plugin_softwareupdate_workingdialog_output {
font-size: 0.8em;
.message {
font-weight: bold;
}
.separator {
font-weight: bold;
color: #666666;
}
.stdout {
color: #333333;
}
.stderr {
color: #990000;
}
.call {
color: #000099;
}
.message_error {
.message;
.stderr;
}
}
.softwareupdate_notification {
ul {
margin: 10px 0 10px 25px;
.name {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
display: block;
}
}
}
@@ -0,0 +1,29 @@
<div id="softwareupdate_confirmation_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Are you sure you want to update now?') }}</h3>
</div>
<div class="modal-body">
<p>
{{ _('This will update the following components and restart the server:') }}
</p>
<ul>
<!-- ko foreach: availableAndPossible -->
<li>
<span class="name" data-bind="text: fullNameRemote, attr: {title: fullNameRemote}"></span>
<div class="releaseNotes" data-bind="visible: releaseNotes"><a data-bind="attr: {href: releaseNotes}">{{ _('Release Notes') }}</a></div>
</li>
<!-- /ko -->
</ul>
<p>
{{ _('Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.') }}
</p>
<p>
{{ _('Are you sure you want to proceed?') }}
</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-danger" data-bind="click: function() { $root.confirmUpdate(); }">{{ _('Proceed') }}</a>
</div>
</div>
@@ -32,7 +32,8 @@
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="icon-exclamation-sign" title="{{ _('Update not possible, configuration ok?') }}"></i></span><br>
<small class="muted">
{{ _('Installed:') }} <span data-bind="text: information.local.name"></span><br>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span>
{{ _('Available:') }} <span data-bind="text: information.remote.name"></span><br>
<span data-bind="visible: releaseNotes">{{ _('Release Notes:') }} <a data-bind="attr: {href: releaseNotes}, text: releaseNotes" target="_blank"></a></span>
</small>
</td>
</tr>
@@ -102,3 +103,16 @@
</div>
</div>
<div id="settings_plugin_softwareupdate_workingdialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="terminal pre-scrollable" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span><br></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -30,15 +30,12 @@ def _get_pip_caller(command=None):
if not key in _pip_callers:
try:
_pip_callers[key] = PipCaller(configured=command)
_pip_callers[key].on_log_call = _log_call
_pip_callers[key].on_log_stdout = _log_stdout
_pip_callers[key].on_log_stderr = _log_stderr
except UnknownPip:
_pip_callers[key] = None
return _pip_callers[key]
def perform_update(target, check, target_version):
def perform_update(target, check, target_version, log_cb=None):
pip_command = None
if "pip_command" in check:
pip_command = check["pip_command"]
@@ -47,12 +44,31 @@ def perform_update(target, check, target_version):
if pip_caller is None:
raise exceptions.UpdateError("Can't run pip", None)
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
if log_cb is not None:
pip_caller.on_log_call = _log_call
pip_caller.on_log_stdout = _log_stdout
pip_caller.on_log_stderr = _log_stderr
install_arg = check["pip"].format(target_version=target_version)
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["install", check["pip"].format(target_version=target_version, target=target_version)]
if "dependency_links" in check and check["dependency_links"] and pip_caller >= _pip_version_dependency_links:
if "dependency_links" in check and check["dependency_links"]:
pip_args += ["--process-dependency-links"]
returncode, stdout, stderr = pip_caller.execute(*pip_args)
@@ -67,18 +83,3 @@ def perform_update(target, check, target_version):
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
return "ok"
def _log_call(*lines):
_log(lines, prefix=u" ")
def _log_stdout(*lines):
_log(lines, prefix=u">")
def _log_stderr(*lines):
_log(lines, prefix=u"!")
def _log(lines, prefix=None):
lines = map(lambda x: x.strip(), lines)
for line in lines:
console_logger.debug(u"{prefix} {line}".format(**locals()))
@@ -10,5 +10,5 @@ def can_perform_update(target, check):
return "python_updater" in check and check["python_updater"] is not None
def perform_update(target, check, target_version):
return check["python_updater"].perform_update(target, check, target_version)
def perform_update(target, check, target_version, log_cb=None):
return check["python_updater"].perform_update(target, check, target_version, log_cb=None)
@@ -8,8 +8,32 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import sys
import logging
from ..exceptions import ScriptError, ConfigurationInvalid, UpdateError
from ..util import execute
from ..exceptions import ConfigurationInvalid, UpdateError
from octoprint.util.commandline import CommandlineCaller, CommandlineError
def _get_caller(log_cb=None):
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
caller = CommandlineCaller()
if log_cb is not None:
caller.on_log_call = _log_call
caller.on_log_stdout = _log_stdout
caller.on_log_stderr = _log_stderr
return caller
def can_perform_update(target, check):
@@ -26,7 +50,7 @@ def can_perform_update(target, check):
return script_configured and folder_configured
def perform_update(target, check, target_version):
def perform_update(target, check, target_version, log_cb=None):
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
if not can_perform_update(target, check):
@@ -37,35 +61,26 @@ def perform_update(target, check, target_version):
pre_update_script = check["pre_update_script"] if "pre_update_script" in check else None
post_update_script = check["post_update_script"] if "post_update_script" in check else None
update_stdout = ""
update_stderr = ""
caller = _get_caller(log_cb=log_cb)
### pre update
if pre_update_script is not None:
logger.debug("Target: %s, running pre-update script: %s" % (target, pre_update_script))
try:
returncode, stdout, stderr = execute(pre_update_script, cwd=folder)
update_stdout += stdout
update_stderr += stderr
except ScriptError as e:
caller.checked_call(pre_update_script, cwd=folder)
except CommandlineError as e:
logger.exception("Target: %s, error while executing pre update script, got returncode %r" % (target, e.returncode))
logger.warn("Target: %s, pre-update stdout:\n%s" % (target, e.stdout))
logger.warn("Target: %s, pre-update stderr:\n%s" % (target, e.stderr))
### update
try:
update_command = update_script.format(python=sys.executable, folder=folder, target=target_version)
logger.debug("Target %s, running update script: %s" % (target, update_command))
returncode, stdout, stderr = execute(update_command, cwd=folder)
update_stdout += stdout
update_stderr += stderr
except ScriptError as e:
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
logger.exception("Target: %s, error while executing update script, got returncode %r" % (target, e.returncode))
logger.warn("Target: %s, update stdout:\n%s" % (target, e.stdout))
logger.warn("Target: %s, update stderr:\n%s" % (target, e.stderr))
raise UpdateError("Error while executing update script for %s", (e.stdout, e.stderr))
### post update
@@ -73,17 +88,8 @@ def perform_update(target, check, target_version):
if post_update_script is not None:
logger.debug("Target: %s, running post-update script %s..." % (target, post_update_script))
try:
returncode, stdout, stderr = execute(post_update_script, cwd=folder)
update_stdout += stdout
update_stderr += stderr
except ScriptError as e:
caller.checked_call(post_update_script, cwd=folder)
except CommandlineError as e:
logger.exception("Target: %s, error while executing post update script, got returncode %r" % (target, e.returncode))
logger.warn("Target: %s, post-update stdout:\n%s" % (target, e.stdout))
logger.warn("Target: %s, post-update stderr:\n%s" % (target, e.stderr))
logger.debug("Target: %s, update stdout:\n%s" % (target, update_stdout))
logger.debug("Target: %s, update stderr:\n%s" % (target, update_stderr))
### result
return update_stdout, update_stderr
return "ok"
@@ -15,33 +15,40 @@ RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
def _get_latest_release(user, repo, include_prerelease=False):
nothing = None, None, None
r = requests.get(RELEASE_URL.format(user=user, repo=repo))
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
if not r.status_code == requests.codes.ok:
return None, None
return nothing
releases = r.json()
# sanitize
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at"}
releases = filter(lambda rel: set(rel.keys()) & required_fields == required_fields,
releases)
# filter out prereleases and drafts
if include_prerelease:
releases = filter(lambda rel: not rel["draft"], releases)
else:
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"], releases)
releases = filter(lambda rel: not rel["prerelease"] and not rel["draft"],
releases)
if not releases:
return None, None
return nothing
# sort by date
comp = lambda a, b: cmp(a["published_at"], b["published_at"])
comp = lambda a, b: cmp(a.get("published_at", None), b["published_at"])
releases = sorted(releases, cmp=comp)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
def _get_sanitized_version(version_string):
@@ -122,14 +129,14 @@ def get_latest(target, check, custom_compare=None):
include_prerelease = check.get("prerelease", False)
force_base = check.get("force_base", True)
remote_name, remote_tag = _get_latest_release(check["user"],
check["repo"],
include_prerelease=include_prerelease)
remote_name, remote_tag, release_notes = _get_latest_release(check["user"],
check["repo"],
include_prerelease=include_prerelease)
compare_type = check["release_compare"] if "release_compare" in check else "python"
information =dict(
local=dict(name=current, value=current),
remote=dict(name=remote_name, value=remote_tag)
remote=dict(name=remote_name, value=remote_tag, release_notes=release_notes)
)
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
@@ -7,18 +7,34 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import octoprint.plugin
class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin):
def virtual_printer_factory(self, comm_instance, port, baudrate,
read_timeout):
if not port == "VIRTUAL":
return None
def virtual_printer_factory(self, comm_instance, port, baudrate, read_timeout):
if not port == "VIRTUAL":
return None
if not self._settings.global_get_boolean(
["devel", "virtualPrinter", "enabled"]):
return None
if not self._settings.global_get_boolean(["devel", "virtualPrinter", "enabled"]):
return None
import logging
import logging.handlers
seriallog_handler = logging.handlers.RotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="serial"),
maxBytes=2 * 1024 * 1024)
seriallog_handler.setFormatter(
logging.Formatter("%(asctime)s %(message)s"))
seriallog_handler.setLevel(logging.DEBUG)
from . import virtual
serial_obj = virtual.VirtualPrinter(
seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout))
return serial_obj
from . import virtual
serial_obj = virtual.VirtualPrinter(read_timeout=float(read_timeout))
return serial_obj
__plugin_name__ = "Virtual Printer"
__plugin_author__ = "Gina Häußge, based on work by Daid Braam"
@@ -26,13 +42,14 @@ __plugin_homepage__ = "https://github.com/foosel/OctoPrint/wiki/Plugin:-Virtual-
__plugin_license__ = "AGPLv3"
__plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes"
def __plugin_load__():
plugin = VirtualPrinterPlugin()
plugin = VirtualPrinterPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory
}
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory
}
+280 -153
View File
@@ -16,17 +16,28 @@ from serial import SerialTimeoutException
from octoprint.settings import settings
from octoprint.plugin import plugin_manager
class VirtualPrinter():
command_regex = re.compile("[GM]\d+")
class VirtualPrinter(object):
command_regex = re.compile("^([GMTF])(\d+)")
sleep_regex = re.compile("sleep (\d+)")
sleep_after_regex = re.compile("sleep_after ([GM]\d+) (\d+)")
sleep_after_next_regex = re.compile("sleep_after_next ([GM]\d+) (\d+)")
sleep_after_regex = re.compile("sleep_after ([GMTF]\d+) (\d+)")
sleep_after_next_regex = re.compile("sleep_after_next ([GMTF]\d+) (\d+)")
custom_action_regex = re.compile("action_custom ([a-zA-Z0-9_]+)(\s+.*)?")
def __init__(self, read_timeout=5.0, write_timeout=10.0):
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
import logging
self._logger = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter")
self._seriallog = logging.getLogger("octoprint.plugin.virtual_printer.VirtualPrinter.serial")
self._seriallog.setLevel(logging.CRITICAL)
self._seriallog.propagate = False
if seriallog_handler is not None:
import logging.handlers
self._seriallog.addHandler(seriallog_handler)
self._seriallog.setLevel(logging.INFO)
self._seriallog.info("-"*78)
self._read_timeout = read_timeout
self._write_timeout = write_timeout
@@ -35,7 +46,7 @@ class VirtualPrinter():
self.buffered = Queue.Queue(maxsize=settings().getInt(["devel", "virtualPrinter", "commandBuffer"]))
for item in ['start\n', 'Marlin: Virtual Marlin!\n', '\x80\n', 'SD card ok\n']:
self.outgoing.put(item)
self._send(item)
self.currentExtruder = 0
self.temp = [0.0] * settings().getInt(["devel", "virtualPrinter", "numExtruders"])
@@ -66,10 +77,13 @@ class VirtualPrinter():
self._okBeforeCommandOutput = settings().getBoolean(["devel", "virtualPrinter", "okBeforeCommandOutput"])
self._supportM112 = settings().getBoolean(["devel", "virtualPrinter", "supportM112"])
self._supportF = settings().getBoolean(["devel", "virtualPrinter", "supportF"])
self._sendWait = settings().getBoolean(["devel", "virtualPrinter", "sendWait"])
self._waitInterval = settings().getFloat(["devel", "virtualPrinter", "waitInterval"])
self._echoOnM117 = settings().getBoolean(["devel", "virtualPrinter", "echoOnM117"])
self.currentLine = 0
self.lastN = 0
@@ -86,9 +100,6 @@ class VirtualPrinter():
self._killed = False
waitThread = threading.Thread(target=self._sendWaitAfterTimeout)
waitThread.start()
readThread = threading.Thread(target=self._processIncoming)
readThread.start()
@@ -115,7 +126,7 @@ class VirtualPrinter():
data = self.incoming.get(timeout=0.01)
except Queue.Empty:
if self._sendWait and time.time() > next_wait_timeout:
self.outgoing.put("wait")
self._send("wait")
next_wait_timeout = time.time() + self._waitInterval
continue
@@ -135,7 +146,7 @@ class VirtualPrinter():
data = data[:data.rfind("*")]
self.currentLine += 1
elif settings().getBoolean(["devel", "virtualPrinter", "forceChecksum"]):
self.outgoing.put("Error: Missing checksum")
self._send("Error: Missing checksum")
continue
# track N = N + 1
@@ -170,135 +181,200 @@ class VirtualPrinter():
if data.strip() == "version":
from octoprint._version import get_versions
self.outgoing.put("OctoPrint VirtualPrinter v" + get_versions()["version"])
self._send("OctoPrint VirtualPrinter v" + get_versions()["version"])
continue
elif data.startswith("!!DEBUG:"):
self._debugTrigger(data[len("!!DEBUG:"):].strip())
elif data.startswith("!!DEBUG:") or data.strip() == "!!DEBUG":
debug_command = ""
if data.startswith("!!DEBUG:"):
debug_command = data[len("!!DEBUG:"):].strip()
self._debugTrigger(debug_command)
continue
# if we are sending oks before command output, send it now
if len(data.strip()) > 0 and self._okBeforeCommandOutput:
self._sendOk()
#print "Send: %s" % (data.rstrip())
if 'M104' in data or 'M109' in data:
self._parseHotendCommand(data)
# actual command handling
command_match = VirtualPrinter.command_regex.match(data)
if command_match is not None:
command = command_match.group(0)
letter = command_match.group(1)
if 'M140' in data or 'M190' in data:
self._parseBedCommand(data)
try:
# if we have a method _gcode_G, _gcode_M or _gcode_T, execute that first
letter_handler = "_gcode_{}".format(letter)
if hasattr(self, letter_handler):
code = command_match.group(2)
handled = getattr(self, letter_handler)(code, data)
if handled:
continue
if 'M105' in data:
self._processTemperatureQuery()
continue
elif 'M20' in data:
if self._sdCardReady:
self._listSd()
elif 'M21' in data:
self._sdCardReady = True
self.outgoing.put("SD card ok")
elif 'M22' in data:
self._sdCardReady = False
elif 'M23' in data:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._selectSdFile(filename)
elif 'M24' in data:
if self._sdCardReady:
self._startSdPrint()
elif 'M25' in data:
if self._sdCardReady:
self._pauseSdPrint()
elif 'M26' in data:
if self._sdCardReady:
pos = int(re.search("S([0-9]+)", data).group(1))
self._setSdPos(pos)
elif 'M27' in data:
if self._sdCardReady:
self._reportSdStatus()
elif 'M28' in data:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._writeSdFile(filename)
elif 'M29' in data:
if self._sdCardReady:
self._finishSdFile()
elif 'M30' in data:
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._deleteSdFile(filename)
elif "M114" in data:
# send dummy position report
output = "C: X:10.00 Y:3.20 Z:5.20 E:1.24"
if not self._okBeforeCommandOutput:
output = "ok " + output
self.outgoing.put(output)
continue
elif "M117" in data:
# we'll just use this to echo a message, to allow playing around with pause triggers
self.outgoing.put("echo:%s" % re.search("M117\s+(.*)", data).group(1))
elif "M999" in data:
# mirror Marlin behaviour
self.outgoing.put("Resend: 1")
elif data.startswith("T"):
self.currentExtruder = int(re.search("T(\d+)", data).group(1))
self.outgoing.put("Active Extruder: %d" % self.currentExtruder)
elif "G20" in data:
self._unitModifier = 1.0 / 2.54
if self._lastX is not None:
self._lastX *= 2.54
if self._lastY is not None:
self._lastY *= 2.54
if self._lastZ is not None:
self._lastZ *= 2.54
if self._lastE is not None:
self._lastE *= 2.54
elif "G21" in data:
self._unitModifier = 1.0
if self._lastX is not None:
self._lastX /= 2.54
if self._lastY is not None:
self._lastY /= 2.54
if self._lastZ is not None:
self._lastZ /= 2.54
if self._lastE is not None:
self._lastE /= 2.54
elif "G90" in data:
self._relative = False
elif "G91" in data:
self._relative = True
elif "G92" in data:
self._setPosition(data)
# then look for a method _gcode_<command> and execute that if it exists
command_handler = "_gcode_{}".format(command)
if hasattr(self, command_handler):
handled = getattr(self, command_handler)(data)
if handled:
continue
elif data.startswith("G28"):
self._performMove(data)
finally:
# make sure that the debug sleepAfter and sleepAfterNext stuff works even
# if we continued above
if len(self._sleepAfter) or len(self._sleepAfterNext):
interval = None
if command in self._sleepAfter:
interval = self._sleepAfter[command]
elif command in self._sleepAfterNext:
interval = self._sleepAfterNext[command]
del self._sleepAfterNext[command]
elif data.startswith("G0") or data.startswith("G1") or data.startswith("G2") or data.startswith("G3"):
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
self.buffered.put(data)
if len(self._sleepAfter) or len(self._sleepAfterNext):
command_match = VirtualPrinter.command_regex.match(data)
if command_match is not None:
command = command_match.group(0)
interval = None
if command in self._sleepAfter:
interval = self._sleepAfter[command]
elif command in self._sleepAfterNext:
interval = self._sleepAfterNext[command]
del self._sleepAfterNext[command]
if interval is not None:
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
if interval is not None:
self._send("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
# if we are sending oks after command output, send it now
if len(data.strip()) > 0 and not self._okBeforeCommandOutput:
self._sendOk()
##~~ command implementations
def _gcode_T(self, code, data):
self.currentExtruder = int(code)
self._send("Active Extruder: %d" % self.currentExtruder)
def _gcode_F(self, code, data):
if self._supportF:
self._send("echo:changed F value")
return False
else:
self._send("Error: Unknown command F")
return True
def _gcode_M104(self, data):
self._parseHotendCommand(data)
_gcode_M109 = _gcode_M104
def _gcode_M140(self, data):
self._parseBedCommand(data)
_gcode_M190 = _gcode_M140
def _gcode_M105(self, data):
self._processTemperatureQuery()
return True
def _gcode_M20(self, data):
if self._sdCardReady:
self._listSd()
def _gcode_M21(self, data):
self._sdCardReady = True
self._send("SD card ok")
def _gcode_M22(self, data):
self._sdCardReady = False
def _gcode_M23(self, data):
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._selectSdFile(filename)
def _gcode_M24(self, data):
if self._sdCardReady:
self._startSdPrint()
def _gcode_M25(self, data):
if self._sdCardReady:
self._pauseSdPrint()
def _gcode_M26(self, data):
if self._sdCardReady:
pos = int(re.search("S([0-9]+)", data).group(1))
self._setSdPos(pos)
def _gcode_M27(self, data):
if self._sdCardReady:
self._reportSdStatus()
def _gcode_M28(self, data):
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._writeSdFile(filename)
def _gcode_M29(self, data):
if self._sdCardReady:
self._finishSdFile()
def _gcode_M30(self, data):
if self._sdCardReady:
filename = data.split(None, 1)[1].strip()
self._deleteSdFile(filename)
def _gcode_M114(self, data):
output = "C: X:{} Y:{} Z:{} E:{}".format(self._lastX, self._lastY, self._lastZ, self._lastE)
if not self._okBeforeCommandOutput:
output = "ok " + output
self._send(output)
return True
def _gcode_M117(self, data):
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
self._send("echo:%s" % re.search("M117\s+(.*)", data).group(1))
def _gcode_M400(self, data):
self.buffered.join()
def _gcode_M999(self, data):
# mirror Marlin behaviour
self._send("Resend: 1")
def _gcode_G20(self, data):
self._unitModifier = 1.0 / 2.54
if self._lastX is not None:
self._lastX *= 2.54
if self._lastY is not None:
self._lastY *= 2.54
if self._lastZ is not None:
self._lastZ *= 2.54
if self._lastE is not None:
self._lastE *= 2.54
def _gcode_G21(self, data):
self._unitModifier = 1.0
if self._lastX is not None:
self._lastX /= 2.54
if self._lastY is not None:
self._lastY /= 2.54
if self._lastZ is not None:
self._lastZ /= 2.54
if self._lastE is not None:
self._lastE /= 2.54
def _gcode_G90(self, data):
self._relative = False
def _gcode_G91(self, data):
self._relative = True
def _gcode_G92(self, data):
self._setPosition(data)
def _gcode_G28(self, data):
self._performMove(data)
def _gcode_G0(self, data):
# simulate reprap buffered commands via a Queue with maxsize which internally simulates the moves
self.buffered.put(data)
_gcode_G1 = _gcode_G0
_gcode_G2 = _gcode_G0
_gcode_G3 = _gcode_G0
##~~ further helpers
def _kill(self):
if not self._supportM112:
return
self._killed = True
self.outgoing.put("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
self._send("echo:EMERGENCY SHUTDOWN DETECTED. KILLED.")
def _triggerResend(self, expected=None, actual=None):
with self._incoming_lock:
@@ -308,25 +384,68 @@ class VirtualPrinter():
self.lastN = expected - 1
if actual is None:
self.outgoing.put("Error: Wrong checksum")
self._send("Error: Wrong checksum")
else:
self.outgoing.put("Error: expected line %d got %d" % (expected, actual))
self._send("Error: expected line %d got %d" % (expected, actual))
def request_resend():
self.outgoing.put("Resend:%d" % expected)
self.outgoing.put("ok")
self._send("Resend:%d" % expected)
self._send("ok")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
request_resend()
def _debugTrigger(self, data):
if data == "action_pause":
self.outgoing.put("// action:pause")
if data == "" or data == "help" or data == "?":
usage = """
OctoPrint Virtual Printer debug commands
help
?
| This help.
# Action Triggers
action_pause
| Sends a "// action:pause" action trigger to the host.
action_resume
| Sends a "// action:resume" action trigger to the host.
action_disconnect
| Sends a "// action:disconnect" action trigger to the
| host.
action_custom <action>[ <parameters>]
| Sends a custom "// action:<action> <parameters>"
| action trigger to the host.
# Communication Errors
dont_answer
| Will not acknowledge the next command.
trigger_resend_lineno
| Triggers a resend error with a line number mismatch
trigger_resend_checksum
| Triggers a resend error with a checksum mismatch
drop_connection
| Drops the serial connection
# Reply Timing / Sleeping
sleep <int:seconds>
| Sleep <seconds> s
sleep_after <str:command> <int:seconds>
| Sleeps <seconds> s after each execution of <command>
sleep_after_next <str:command> <int:seconds>
| Sleeps <seconds> s after execution of <command>
"""
for line in usage.split("\n"):
self._send("echo: {}".format(line.strip()))
elif data == "action_pause":
self._send("// action:pause")
elif data == "action_resume":
self.outgoing.put("// action:resume")
self._send("// action:resume")
elif data == "action_disconnect":
self.outgoing.put("// action:disconnect")
self._send("// action:disconnect")
elif data == "dont_answer":
self._dont_answer = True
elif data == "trigger_resend_lineno":
@@ -344,28 +463,28 @@ class VirtualPrinter():
if sleep_match is not None:
interval = int(sleep_match.group(1))
self.outgoing.put("// sleeping for {interval} seconds".format(interval=interval))
self._send("// sleeping for {interval} seconds".format(interval=interval))
time.sleep(interval)
elif sleep_after_match is not None:
command = sleep_after_match.group(1)
interval = int(sleep_after_match.group(2))
self._sleepAfter[command] = interval
self.outgoing.put("// going to sleep {interval} seconds after each {command}".format(**locals()))
self._send("// going to sleep {interval} seconds after each {command}".format(**locals()))
elif sleep_after_next_match is not None:
command = sleep_after_next_match.group(1)
interval = int(sleep_after_next_match.group(2))
self._sleepAfterNext[command] = interval
self.outgoing.put("// going to sleep {interval} seconds after next {command}".format(**locals()))
self._send("// going to sleep {interval} seconds after next {command}".format(**locals()))
elif custom_action_match is not None:
action = custom_action_match.group(1)
params = custom_action_match.group(2)
params = params.strip() if params is not None else ""
self.outgoing.put("// action:{action} {params}".format(**locals()).strip())
self._send("// action:{action} {params}".format(**locals()).strip())
except:
pass
def _listSd(self):
self.outgoing.put("Begin file list")
self._send("Begin file list")
if settings().getBoolean(["devel", "virtualPrinter", "extendedSdFileList"]):
items = map(
lambda x: "%s %d" % (x.upper(), os.stat(os.path.join(self._virtualSd, x)).st_size),
@@ -377,20 +496,20 @@ class VirtualPrinter():
os.listdir(self._virtualSd)
)
for item in items:
self.outgoing.put(item)
self.outgoing.put("End file list")
self._send(item)
self._send("End file list")
def _selectSdFile(self, filename):
if filename.startswith("/"):
filename = filename[1:]
file = os.path.join(self._virtualSd, filename.lower())
if not os.path.exists(file) or not os.path.isfile(file):
self.outgoing.put("open failed, File: %s." % filename)
self._send("open failed, File: %s." % filename)
else:
self._selectedSdFile = file
self._selectedSdFileSize = os.stat(file).st_size
self.outgoing.put("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
self.outgoing.put("File selected")
self._send("File opened: %s Size: %d" % (filename, self._selectedSdFileSize))
self._send("File selected")
def _startSdPrint(self):
if self._selectedSdFile is not None:
@@ -407,9 +526,9 @@ class VirtualPrinter():
def _reportSdStatus(self):
if self._sdPrinter is not None and self._sdPrintingSemaphore.is_set:
self.outgoing.put("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
self._send("SD printing byte %d/%d" % (self._selectedSdFilePos, self._selectedSdFileSize))
else:
self.outgoing.put("Not SD printing")
self._send("Not SD printing")
def _processTemperatureQuery(self):
includeTarget = not settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"])
@@ -446,7 +565,7 @@ class VirtualPrinter():
if includeOk:
output = "ok " + output
self.outgoing.put(output)
self._send(output)
def _parseHotendCommand(self, line):
tool = 0
@@ -468,7 +587,7 @@ class VirtualPrinter():
if "M109" in line:
self._waitForHeatup("tool%d" % tool)
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
self.outgoing.put("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
self._send("TargetExtr%d:%d" % (tool, self.targetTemp[tool]))
def _parseBedCommand(self, line):
try:
@@ -479,7 +598,7 @@ class VirtualPrinter():
if "M190" in line:
self._waitForHeatup("bed")
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleTargetTemperature"]):
self.outgoing.put("TargetBed:%d" % self.bedTargetTemp)
self._send("TargetBed:%d" % self.bedTargetTemp)
def _performMove(self, line):
matchX = re.search("X([0-9.]+)", line)
@@ -573,11 +692,11 @@ class VirtualPrinter():
if os.path.isfile(file):
os.remove(file)
else:
self.outgoing.put("error writing to file")
self._send("error writing to file")
self._writingToSd = True
self._selectedSdFile = file
self.outgoing.put("Writing to file: %s" % filename)
self._send("Writing to file: %s" % filename)
def _finishSdFile(self):
self._writingToSd = False
@@ -612,7 +731,7 @@ class VirtualPrinter():
self._sdPrintingSemaphore.clear()
self._selectedSdFilePos = 0
self._sdPrinter = None
self.outgoing.put("Done printing file")
self._send("Done printing file")
def _waitForHeatup(self, heater):
delta = 1
@@ -621,12 +740,12 @@ class VirtualPrinter():
toolNum = int(heater[len("tool"):])
while not self._killed and (self.temp[toolNum] < self.targetTemp[toolNum] - delta or self.temp[toolNum] > self.targetTemp[toolNum] + delta):
self._simulateTemps(delta=delta)
self.outgoing.put("T:%0.2f" % self.temp[toolNum])
self._send("T:%0.2f" % self.temp[toolNum])
time.sleep(delay)
elif heater == "bed":
while not self._killed and (self.bedTemp < self.bedTargetTemp - delta or self.bedTemp > self.bedTargetTemp + delta):
self._simulateTemps(delta=delta)
self.outgoing.put("B:%0.2f" % self.bedTemp)
self._send("B:%0.2f" % self.bedTemp)
time.sleep(delay)
def _deleteSdFile(self, filename):
@@ -666,6 +785,7 @@ class VirtualPrinter():
continue
self._performMove(line)
self.buffered.task_done()
def write(self, data):
if self._debug_drop_connection:
@@ -677,11 +797,13 @@ class VirtualPrinter():
return
if "M112" in data and self._supportM112:
self._seriallog.info("<<< {}".format(data.strip()))
self._kill()
return
try:
self.incoming.put(data, timeout=self._write_timeout)
self._seriallog.info("<<< {}".format(data.strip()))
except Queue.Full:
self._logger.info("Incoming queue is full, raising SerialTimeoutException")
raise SerialTimeoutException()
@@ -693,6 +815,7 @@ class VirtualPrinter():
try:
line = self.outgoing.get(timeout=self._read_timeout)
time.sleep(settings().getFloat(["devel", "virtualPrinter", "throttle"]))
self._seriallog.info(">>> {}".format(line.strip()))
return line
except Queue.Empty:
return ""
@@ -707,14 +830,18 @@ class VirtualPrinter():
return
if settings().getBoolean(["devel", "virtualPrinter", "okWithLinenumber"]):
self.outgoing.put("ok %d" % self.lastN)
self._send("ok %d" % self.lastN)
else:
self.outgoing.put("ok")
self._send("ok")
def _sendWaitAfterTimeout(self, timeout=5):
time.sleep(timeout)
if self.outgoing is not None:
self.outgoing.put("wait")
self._send("wait")
def _send(self, line):
if self.outgoing is not None:
self.outgoing.put(line)
class CharCountingQueue(Queue.Queue):
+29
View File
@@ -221,6 +221,10 @@ class PrinterInterface(object):
Arguments:
path (str): The path to select for printing. Either an absolute path (local file) or a
filename (SD card).
sd (boolean): Indicates whether the file is on the SD card or not.
printAfterSelect (boolean): Indicates whether a print should be started
after the file is selected.
"""
raise NotImplementedError()
@@ -255,6 +259,31 @@ class PrinterInterface(object):
"""
raise NotImplementedError()
def get_state_id(self):
"""
Identifier of the current communication state.
Possible values are:
* OPEN_SERIAL
* DETECT_SERIAL
* DETECT_BAUDRATE
* CONNECTING
* OPERATIONAL
* PRINTING
* PAUSED
* CLOSED
* ERROR
* CLOSED_WITH_ERROR
* TRANFERING_FILE
* OFFLINE
* UNKNOWN
* NONE
Returns:
(str) A unique identifier corresponding to the current communication state.
"""
def get_current_data(self):
"""
Returns:
+22 -9
View File
@@ -191,7 +191,9 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
will be attempted.
"""
if self._comm is not None:
self._comm.close()
self.disconnect()
eventManager().fire(Events.CONNECTING)
self._printerProfileManager.select(profile)
self._comm = comm.MachineCom(port, baudrate, callbackObject=self, printerProfileManager=self._printerProfileManager)
@@ -199,11 +201,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"""
Closes the connection to the printer.
"""
eventManager().fire(Events.DISCONNECTING)
if self._comm is not None:
self._comm.close()
self._comm = None
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
else:
eventManager().fire(Events.DISCONNECTED)
def get_transport(self):
@@ -426,14 +428,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload["origin"] = FileDestinations.SDCARD
eventManager().fire(Events.PRINT_FAILED, payload)
def get_state_string(self):
"""
Returns a human readable string corresponding to the current communication state.
"""
def get_state_string(self, state=None):
if self._comm is None:
return "Offline"
else:
return self._comm.getStateString()
return self._comm.getStateString(state=state)
def get_state_id(self, state=None):
if self._comm is None:
return "OFFLINE"
else:
return self._comm.getStateId(state=state)
def get_current_data(self):
return self._stateMonitor.get_current_data()
@@ -561,6 +566,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._state = state
self._stateMonitor.set_state({"text": self.get_state_string(), "flags": self._getStateFlags()})
payload = dict(
state_id=self.get_state_id(self._state),
state_string=self.get_state_string(self._state)
)
eventManager().fire(Events.PRINTER_STATE_CHANGED, payload)
def _addLog(self, log):
self._log.append(log)
self._stateMonitor.add_log(log)
@@ -777,6 +788,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._setProgressData(0, None, None, None)
self._setCurrentZ(None)
self._setJobData(None, None, None)
self._printerProfileManager.deselect()
eventManager().fire(Events.DISCONNECTED)
self._setState(state)
+319 -176
View File
@@ -12,6 +12,7 @@ from flask.ext.login import LoginManager, current_user
from flask.ext.principal import Principal, Permission, RoleNeed, identity_loaded, UserNeed
from flask.ext.babel import Babel, gettext, ngettext
from flask.ext.assets import Environment, Bundle
from flaskext.markdown import Markdown
from babel import Locale
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
@@ -22,9 +23,11 @@ import logging
import logging.config
import atexit
import signal
import base64
SUCCESS = {}
NO_CONTENT = ("", 204)
NOT_MODIFIED = ("Not Modified", 304)
app = Flask("octoprint")
assets = None
@@ -42,12 +45,14 @@ loginManager = None
pluginManager = None
appSessionManager = None
pluginLifecycleManager = None
preemptiveCache = None
principals = Principal(app)
admin_permission = Permission(RoleNeed("admin"))
user_permission = Permission(RoleNeed("user"))
# only import the octoprint stuff down here, as it might depend on things defined above to be initialized already
from octoprint import __version__, __branch__, __display_version__, __revision__
from octoprint.printer import get_connection_options
from octoprint.printer.profile import PrinterProfileManager
from octoprint.printer.standard import Printer
@@ -61,16 +66,16 @@ import octoprint.util
import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
from octoprint.server.util.flask import PreemptiveCache
from . import util
UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
versions = octoprint._version.get_versions()
VERSION = versions['version']
BRANCH = versions['branch'] if 'branch' in versions else None
DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION
del versions
VERSION = __version__
BRANCH = __branch__
DISPLAY_VERSION = __display_version__
REVISION = __revision__
LOCALES = []
LANGUAGES = set()
@@ -96,7 +101,7 @@ def load_user(id):
else:
sessionid = None
if userManager is not None:
if userManager.enabled:
if sessionid:
return userManager.findUser(userid=id, session=sessionid)
else:
@@ -108,14 +113,13 @@ def load_user(id):
class Server():
def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False, logConf=None):
self._configfile = configfile
self._basedir = basedir
def __init__(self, settings=None, plugin_manager=None, host="0.0.0.0", port=5000, debug=False, allow_root=False):
self._settings = settings
self._plugin_manager = plugin_manager
self._host = host
self._port = port
self._debug = debug
self._allowRoot = allowRoot
self._logConf = logConf
self._allow_root = allow_root
self._server = None
self._logger = None
@@ -124,10 +128,17 @@ class Server():
self._template_searchpaths = []
self._intermediary_server = None
def run(self):
if not self._allowRoot:
if not self._allow_root:
self._check_for_root()
if self._settings is None:
self._settings = settings()
if self._plugin_manager is None:
self._plugin_manager = octoprint.plugin.plugin_manager()
global app
global babel
@@ -142,21 +153,20 @@ class Server():
global pluginManager
global appSessionManager
global pluginLifecycleManager
global preemptiveCache
global debug
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
import sys
debug = self._debug
# first initialize the settings singleton and make sure it uses given configfile and basedir if available
s = settings(init=True, basedir=self._basedir, configfile=self._configfile)
self._logger = logging.getLogger(__name__)
pluginManager = self._plugin_manager
# then monkey patch a bunch of stuff
# monkey patch a bunch of stuff
util.tornado.fix_ioloop_scheduling()
util.flask.enable_additional_translations(additional_folders=[s.getBaseFolder("translations")])
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
# setup app
self._setup_app()
@@ -164,27 +174,39 @@ class Server():
# setup i18n
self._setup_i18n(app)
# then initialize logging
self._setup_logging(self._debug, self._logConf)
self._logger = logging.getLogger(__name__)
def exception_logger(exc_type, exc_value, exc_tb):
self._logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb))
sys.excepthook = exception_logger
self._logger.info("Starting OctoPrint %s" % DISPLAY_VERSION)
if self._settings.getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
# start the intermediary server
self._start_intermediary_server()
# then initialize the plugin manager
pluginManager = octoprint.plugin.plugin_manager(init=True)
pluginManager.reload_plugins(startup=True, initialize_implementations=False)
printerProfileManager = PrinterProfileManager()
eventManager = events.eventManager()
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
slicingManager = octoprint.slicing.SlicingManager(s.getBaseFolder("slicingProfiles"), printerProfileManager)
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
storage_managers = dict()
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(s.getBaseFolder("uploads"))
storage_managers[octoprint.filemanager.FileDestinations.LOCAL] = octoprint.filemanager.storage.LocalFileStorage(self._settings.getBaseFolder("uploads"))
fileManager = octoprint.filemanager.FileManager(analysisQueue, slicingManager, printerProfileManager, initial_storage_managers=storage_managers)
printer = Printer(fileManager, analysisQueue, printerProfileManager)
appSessionManager = util.flask.AppSessionManager()
pluginLifecycleManager = LifecycleManager(pluginManager)
preemptiveCache = PreemptiveCache(os.path.join(self._settings.getBaseFolder("data"), "preemptive_cache_config.yaml"))
# setup access control
userManagerName = self._settings.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError, e:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
def octoprint_plugin_inject_factory(name, implementation):
if not isinstance(implementation, octoprint.plugin.OctoPrintPlugin):
@@ -199,18 +221,16 @@ class Server():
printer=printer,
app_session_manager=appSessionManager,
plugin_lifecycle_manager=pluginLifecycleManager,
data_folder=os.path.join(settings().getBaseFolder("data"), name)
data_folder=os.path.join(self._settings.getBaseFolder("data"), name),
user_manager=userManager,
preemptive_cache=preemptiveCache
)
def settings_plugin_inject_factory(name, implementation):
if not isinstance(implementation, octoprint.plugin.SettingsPlugin):
return None
default_settings = implementation.get_settings_defaults()
get_preprocessors, set_preprocessors = implementation.get_settings_preprocessors()
plugin_settings = octoprint.plugin.plugin_settings(name,
defaults=default_settings,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors)
plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin(name, implementation)
if plugin_settings is None:
return
return dict(settings=plugin_settings)
def settings_plugin_config_migration_and_cleanup(name, implementation):
@@ -277,46 +297,37 @@ class Server():
if self._debug:
events.DebugEventListener()
# setup access control
if s.getBoolean(["accessControl", "enabled"]):
userManagerName = s.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except AttributeError, e:
self._logger.exception("Could not instantiate user manager %s, will run with accessControl disabled!" % userManagerName)
app.wsgi_app = util.ReverseProxied(
app.wsgi_app,
s.get(["server", "reverseProxy", "prefixHeader"]),
s.get(["server", "reverseProxy", "schemeHeader"]),
s.get(["server", "reverseProxy", "hostHeader"]),
s.get(["server", "reverseProxy", "prefixFallback"]),
s.get(["server", "reverseProxy", "schemeFallback"]),
s.get(["server", "reverseProxy", "hostFallback"])
self._settings.get(["server", "reverseProxy", "prefixHeader"]),
self._settings.get(["server", "reverseProxy", "schemeHeader"]),
self._settings.get(["server", "reverseProxy", "hostHeader"]),
self._settings.get(["server", "reverseProxy", "prefixFallback"]),
self._settings.get(["server", "reverseProxy", "schemeFallback"]),
self._settings.get(["server", "reverseProxy", "hostFallback"])
)
secret_key = s.get(["server", "secretKey"])
secret_key = self._settings.get(["server", "secretKey"])
if not secret_key:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
secret_key = "".join(choice(chars) for _ in xrange(32))
s.set(["server", "secretKey"], secret_key)
s.save()
self._settings.set(["server", "secretKey"], secret_key)
self._settings.save()
app.secret_key = secret_key
loginManager = LoginManager()
loginManager.session_protection = "strong"
loginManager.user_callback = load_user
if userManager is None:
if not userManager.enabled:
loginManager.anonymous_user = users.DummyUser
principals.identity_loaders.appendleft(users.dummy_identity_loader)
loginManager.init_app(app)
if self._host is None:
self._host = s.get(["server", "host"])
self._host = self._settings.get(["server", "host"])
if self._port is None:
self._port = s.getInt(["server", "port"])
self._port = self._settings.getInt(["server", "port"])
app.debug = self._debug
@@ -330,7 +341,7 @@ class Server():
self._router = SockJSRouter(self._create_socket_connection, "/sockjs")
upload_suffixes = dict(name=s.get(["server", "uploads", "nameSuffix"]), path=s.get(["server", "uploads", "pathSuffix"]))
upload_suffixes = dict(name=self._settings.get(["server", "uploads", "nameSuffix"]), path=self._settings.get(["server", "uploads", "pathSuffix"]))
def mime_type_guesser(path):
from octoprint.filemanager import get_mime_type
@@ -355,13 +366,27 @@ class Server():
server_routes = self._router.urls + [
# various downloads
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("timelapse")), download_handler_kwargs, no_hidden_files_validator)),
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("uploads")), download_handler_kwargs, no_hidden_files_validator, additional_mime_types)),
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=s.getBaseFolder("logs")), download_handler_kwargs, admin_validator)),
(r"/downloads/timelapse/([^/]*\.mpg)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("timelapse")),
download_handler_kwargs,
no_hidden_files_validator)),
(r"/downloads/files/local/(.*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("uploads")),
download_handler_kwargs,
no_hidden_files_validator,
additional_mime_types)),
(r"/downloads/logs/([^/]*)", util.tornado.LargeResponseHandler, joined_dict(dict(path=self._settings.getBaseFolder("logs")),
download_handler_kwargs,
admin_validator)),
# camera snapshot
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=s.get(["webcam", "snapshot"]), as_attachment=True, access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
(r"/downloads/camera/current", util.tornado.UrlProxyHandler, dict(url=self._settings.get(["webcam", "snapshot"]),
as_attachment=True,
access_validation=util.tornado.access_validation_factory(app, loginManager, util.flask.user_validator))),
# generated webassets
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(s.getBaseFolder("generated"), "webassets")))
(r"/static/webassets/(.*)", util.tornado.LargeResponseHandler, dict(path=os.path.join(self._settings.getBaseFolder("generated"), "webassets"))),
# online indicators - text file with "online" as content and a transparent gif
(r"/online.txt", util.tornado.StaticDataHandler, dict(data="online\n")),
(r"/online.gif", util.tornado.StaticDataHandler, dict(data=bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")),
content_type="image/gif"))
]
for name, hook in pluginManager.get_hooks("octoprint.server.http.routes").items():
try:
@@ -388,7 +413,7 @@ class Server():
self._tornado_app = Application(server_routes)
max_body_sizes = [
("POST", r"/api/files/([^/]*)", s.getInt(["server", "uploads", "maxSize"])),
("POST", r"/api/files/([^/]*)", self._settings.getInt(["server", "uploads", "maxSize"])),
("POST", r"/api/languages", 5 * 1024 * 1024)
]
@@ -414,31 +439,34 @@ class Server():
self._logger.debug("Adding maximum body size of {size}B for {method} requests to {route})".format(**locals()))
max_body_sizes.append((method, route, size))
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=s.getInt(["server", "maxSize"]))
self._stop_intermediary_server()
self._server = util.tornado.CustomHTTPServer(self._tornado_app, max_body_sizes=max_body_sizes, default_max_body_size=self._settings.getInt(["server", "maxSize"]))
self._server.listen(self._port, address=self._host)
eventManager.fire(events.Events.STARTUP)
if s.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = s.get(["serial", "port"]), s.getInt(["serial", "baudrate"])
if self._settings.getBoolean(["serial", "autoconnect"]):
(port, baudrate) = self._settings.get(["serial", "port"]), self._settings.getInt(["serial", "baudrate"])
printer_profile = printerProfileManager.get_default()
connectionOptions = get_connection_options()
if port in connectionOptions["ports"]:
printer.connect(port=port, baudrate=baudrate, profile=printer_profile["id"] if "id" in printer_profile else "_default")
# start up watchdogs
if s.getBoolean(["feature", "pollWatched"]):
if self._settings.getBoolean(["feature", "pollWatched"]):
# use less performant polling observer if explicitely configured
observer = PollingObserver()
else:
# use os default
observer = Observer()
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), s.getBaseFolder("watched"))
observer.schedule(util.watchdog.GcodeWatchdogHandler(fileManager, printer), self._settings.getBaseFolder("watched"))
observer.start()
# run our startup plugins
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
"on_startup",
args=(self._host, self._port))
args=(self._host, self._port),
sorting_context="StartupPlugin.on_startup")
def call_on_startup(name, plugin):
implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)
@@ -458,7 +486,8 @@ class Server():
# control to the ioloop
def work():
octoprint.plugin.call_plugin(octoprint.plugin.StartupPlugin,
"on_after_startup")
"on_after_startup",
sorting_context="StartupPlugin.on_after_startup")
def call_on_after_startup(name, plugin):
implementation = plugin.get_implementation(octoprint.plugin.StartupPlugin)
@@ -467,6 +496,10 @@ class Server():
implementation.on_after_startup()
pluginLifecycleManager.add_callback("enabled", call_on_after_startup)
# when we are through with that we also run our preemptive cache
if settings().getBoolean(["devel", "cache", "preemptive"]):
self._execute_preemptive_flask_caching(preemptiveCache)
import threading
threading.Thread(target=work).start()
ioloop.add_callback(on_after_startup)
@@ -479,7 +512,8 @@ class Server():
observer.stop()
observer.join()
octoprint.plugin.call_plugin(octoprint.plugin.ShutdownPlugin,
"on_shutdown")
"on_shutdown",
sorting_context="ShutdownPlugin.on_shutdown")
self._logger.info("Goodbye!")
atexit.register(on_shutdown)
@@ -513,7 +547,7 @@ class Server():
if "l10n" in request.values:
return Locale.negotiate([request.values["l10n"]], LANGUAGES)
if hasattr(g, "identity") and g.identity and userManager is not None:
if hasattr(g, "identity") and g.identity and userManager.enabled:
userid = g.identity.id
try:
user_language = userManager.getUserSetting(userid, ("interface", "language"))
@@ -522,88 +556,11 @@ class Server():
except octoprint.users.UnknownUser:
pass
default_language = settings().get(["appearance", "defaultLanguage"])
default_language = self._settings.get(["appearance", "defaultLanguage"])
if default_language is not None and not default_language == "_default" and default_language in LANGUAGES:
return Locale.negotiate([default_language], LANGUAGES)
return request.accept_languages.best_match(LANGUAGES)
def _setup_logging(self, debug, logConf=None):
defaultConfig = {
"version": 1,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"file": {
"class": "logging.handlers.TimedRotatingFileHandler",
"level": "DEBUG",
"formatter": "simple",
"when": "D",
"backupCount": "1",
"filename": os.path.join(settings().getBaseFolder("logs"), "octoprint.log")
},
"serialFile": {
"class": "logging.handlers.RotatingFileHandler",
"level": "DEBUG",
"formatter": "simple",
"maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size
"filename": os.path.join(settings().getBaseFolder("logs"), "serial.log")
}
},
"loggers": {
"SERIAL": {
"level": "CRITICAL",
"handlers": ["serialFile"],
"propagate": False
},
"tornado.application": {
"level": "INFO"
},
"tornado.general": {
"level": "INFO"
},
"octoprint.server.util.flask": {
"level": "WARN"
}
},
"root": {
"level": "INFO",
"handlers": ["console", "file"]
}
}
if debug:
defaultConfig["root"]["level"] = "DEBUG"
if logConf is None:
logConf = os.path.join(settings().getBaseFolder("base"), "logging.yaml")
configFromFile = {}
if os.path.exists(logConf) and os.path.isfile(logConf):
import yaml
with open(logConf, "r") as f:
configFromFile = yaml.safe_load(f)
config = octoprint.util.dict_merge(defaultConfig, configFromFile)
logging.config.dictConfig(config)
logging.captureWarnings(True)
import warnings
warnings.simplefilter("always")
if settings().getBoolean(["serial", "log"]):
# enable debug logging to serial.log
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
def _setup_app(self):
@app.before_request
@@ -618,6 +575,8 @@ class Server():
response.headers.add("X-Clacks-Overhead", "GNU Terry Pratchett")
return response
Markdown(app)
def _setup_i18n(self, app):
global babel
global LOCALES
@@ -645,7 +604,41 @@ class Server():
return self._get_locale()
def _setup_jinja2(self):
import re
app.jinja_env.add_extension("jinja2.ext.do")
app.jinja_env.add_extension("octoprint.util.jinja.trycatch")
def regex_replace(s, find, replace):
return re.sub(find, replace, s)
html_header_regex = re.compile("<h(?P<number>[1-6])>(?P<content>.*?)</h(?P=number)>")
def offset_html_headers(s, offset):
def repl(match):
number = int(match.group("number"))
number += offset
if number > 6:
number = 6
elif number < 1:
number = 1
return "<h{number}>{content}</h{number}>".format(number=number, content=match.group("content"))
return html_header_regex.sub(repl, s)
markdown_header_regex = re.compile("^(?P<hashs>#+)\s+(?P<content>.*)$", flags=re.MULTILINE)
def offset_markdown_headers(s, offset):
def repl(match):
number = len(match.group("hashs"))
number += offset
if number > 6:
number = 6
elif number < 1:
number = 1
return "{hashs} {content}".format(hashs="#" * number, content=match.group("content"))
return markdown_header_regex.sub(repl, s)
app.jinja_env.filters["regex_replace"] = regex_replace
app.jinja_env.filters["offset_html_headers"] = offset_html_headers
app.jinja_env.filters["offset_markdown_headers"] = offset_markdown_headers
# configure additional template folders for jinja2
import jinja2
@@ -654,15 +647,58 @@ class Server():
path_filter=lambda x: not octoprint.util.is_hidden_path(x))
filesystem_loader.searchpath = self._template_searchpaths
jinja_loader = jinja2.ChoiceLoader([
app.jinja_loader,
filesystem_loader
])
loaders = [app.jinja_loader, filesystem_loader]
if octoprint.util.is_running_from_source():
root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
allowed = ["AUTHORS.md", "CHANGELOG.md", "THIRDPARTYLICENSES.md"]
files = {"_data/" + name: os.path.join(root, name) for name in allowed}
loaders.append(octoprint.util.jinja.SelectedFilesLoader(files))
jinja_loader = jinja2.ChoiceLoader(loaders)
app.jinja_loader = jinja_loader
del jinja2
self._register_template_plugins()
def _execute_preemptive_flask_caching(self, preemptive_cache):
from werkzeug.test import EnvironBuilder
import time
# we clean up entries from our preemptive cache settings that haven't been
# accessed longer than server.preemptiveCache.until days
preemptive_cache_timeout = settings().getInt(["server", "preemptiveCache", "until"])
cutoff_timestamp = time.time() - preemptive_cache_timeout * 24 * 60 * 60
def filter_old_entries(entry):
return "_timestamp" in entry and entry["_timestamp"] > cutoff_timestamp
cache_data = preemptive_cache.clean_all_data(lambda root, entries: filter(filter_old_entries, entries))
if not cache_data:
return
def execute_caching():
for route in sorted(cache_data.keys(), key=lambda x: (x.count("/"), x)):
entries = reversed(sorted(cache_data[route], key=lambda x: x.get("_count", 0)))
for kwargs in entries:
plugin = kwargs.get("plugin", None)
additional_request_data = kwargs.get("_additional_request_data", dict())
kwargs = dict((k, v) for k, v in kwargs.items() if not k.startswith("_") and not k == "plugin")
kwargs.update(additional_request_data)
try:
if plugin:
self._logger.info("Preemptively caching {} (plugin {}) for {!r}".format(route, plugin, kwargs))
else:
self._logger.info("Preemptively caching {} for {!r}".format(route, kwargs))
builder = EnvironBuilder(**kwargs)
with preemptive_cache.disable_access_logging():
app(builder.get_environ(), lambda *a, **kw: None)
except:
self._logger.exception("Error while trying to preemptively cache {} for {!r}".format(route, kwargs))
import threading
cache_thread = threading.Thread(target=execute_caching, name="Preemptive Cache Worker")
cache_thread.daemon = True
cache_thread.start()
def _register_template_plugins(self):
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
for plugin in template_plugins:
@@ -756,10 +792,10 @@ class Server():
util.flask.fix_webassets_cache()
util.flask.fix_webassets_filtertool()
base_folder = settings().getBaseFolder("generated")
base_folder = self._settings.getBaseFolder("generated")
# clean the folder
if settings().getBoolean(["devel", "webassets", "clean_on_startup"]):
if self._settings.getBoolean(["devel", "webassets", "clean_on_startup"]):
import shutil
import errno
import sys
@@ -823,15 +859,16 @@ class Server():
return base_folder
assets = CustomDirectoryEnvironment(app)
assets.debug = not settings().getBoolean(["devel", "webassets", "bundle"])
assets.debug = not self._settings.getBoolean(["devel", "webassets", "bundle"])
UpdaterType = type(util.flask.SettingsCheckUpdater)(util.flask.SettingsCheckUpdater.__name__, (util.flask.SettingsCheckUpdater,), dict(
updater=assets.updater
))
assets.updater = UpdaterType
enable_gcodeviewer = settings().getBoolean(["gcodeViewer", "enabled"])
preferred_stylesheet = settings().get(["devel", "stylesheet"])
enable_gcodeviewer = self._settings.getBoolean(["gcodeViewer", "enabled"])
preferred_stylesheet = self._settings.get(["devel", "stylesheet"])
minify = self._settings.getBoolean(["devel", "webassets", "minify"])
dynamic_assets = util.flask.collect_plugin_assets(
enable_gcodeviewer=enable_gcodeviewer,
@@ -839,7 +876,7 @@ class Server():
)
js_libs = [
"js/lib/jquery/jquery.min.js",
"js/lib/jquery/jquery-2.1.4.min.js" if minify else "js/lib/jquery/jquery-2.1.4.js",
"js/lib/modernizr.custom.js",
"js/lib/lodash.min.js",
"js/lib/sprintf.min.js",
@@ -860,6 +897,7 @@ class Server():
"js/lib/jquery/jquery.fileupload.js",
"js/lib/jquery/jquery.slimscroll.min.js",
"js/lib/jquery/jquery.qrcode.min.js",
"js/lib/jquery/jquery.bootstrap.wizard.js",
"js/lib/moment-with-locales.min.js",
"js/lib/pusher.color.min.js",
"js/lib/detectmobilebrowser.js",
@@ -869,6 +907,26 @@ class Server():
"js/lib/loglevel.min.js",
"js/lib/sockjs-0.3.4.min.js"
]
js_client = [
"js/app/client/base.js",
"js/app/client/socket.js",
"js/app/client/browser.js",
"js/app/client/connection.js",
"js/app/client/control.js",
"js/app/client/files.js",
"js/app/client/job.js",
"js/app/client/languages.js",
"js/app/client/logs.js",
"js/app/client/printer.js",
"js/app/client/printerprofiles.js",
"js/app/client/settings.js",
"js/app/client/slicing.js",
"js/app/client/system.js",
"js/app/client/timelapse.js",
"js/app/client/users.js",
"js/app/client/util.js",
"js/app/client/wizard.js"
]
js_app = dynamic_assets["js"] + [
"js/app/dataupdater.js",
"js/app/helpers.js",
@@ -885,12 +943,7 @@ class Server():
"css/pnotify.min.css"
]
css_app = list(dynamic_assets["css"])
if len(css_app) == 0:
css_app = ["empty"]
less_app = list(dynamic_assets["less"])
if len(less_app) == 0:
less_app = ["empty"]
from webassets.filter import register_filter, Filter
from webassets.filter.cssrewrite.base import PatternRewriter
@@ -922,22 +975,116 @@ class Server():
register_filter(JsDelimiterBundle)
js_libs_bundle = Bundle(*js_libs, output="webassets/packed_libs.js", filters="js_delimiter_bundler")
if settings().getBoolean(["devel", "webassets", "minify"]):
if minify:
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="rjsmin, js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="rjsmin, js_delimiter_bundler")
else:
js_client_bundle = Bundle(*js_client, output="webassets/packed_client.js", filters="js_delimiter_bundler")
js_app_bundle = Bundle(*js_app, output="webassets/packed_app.js", filters="js_delimiter_bundler")
css_libs_bundle = Bundle(*css_libs, output="webassets/packed_libs.css")
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
if len(css_app) == 0:
css_app_bundle = Bundle(*[])
else:
css_app_bundle = Bundle(*css_app, output="webassets/packed_app.css", filters="cssrewrite")
if len(less_app) == 0:
all_less_bundle = Bundle(*[])
else:
all_less_bundle = Bundle(*less_app, output="webassets/packed_app.less", filters="cssrewrite, less_importrewrite")
assets.register("js_libs", js_libs_bundle)
assets.register("js_client", js_client_bundle)
assets.register("js_app", js_app_bundle)
assets.register("css_libs", css_libs_bundle)
assets.register("css_app", css_app_bundle)
assets.register("less_app", all_less_bundle)
def _start_intermediary_server(self):
import BaseHTTPServer
import SimpleHTTPServer
import threading
host = self._host
port = self._port
if host is None:
host = self._settings.get(["server", "host"])
if port is None:
port = self._settings.getInt(["server", "port"])
self._logger.debug("Starting intermediary server on {}:{}".format(host, port))
class IntermediaryServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def __init__(self, rules=None, *args, **kwargs):
if rules is None:
rules = []
self.rules = rules
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
def do_GET(self):
request_path = self.path
if "?" in request_path:
request_path = request_path[0:request_path.find("?")]
for rule in self.rules:
path, data, content_type = rule
if request_path == path:
self.send_response(200)
if content_type:
self.send_header("Content-Type", content_type)
self.end_headers()
self.wfile.write(data)
break
else:
self.send_response(404)
self.wfile.write("Not found")
base_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "static"))
rules = [
("/", ["intermediary.html",], "text/html"),
("/favicon.ico", ["img", "tentacle-20x20.png"], "image/png"),
("/intermediary.gif", bytes(base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")), "image/gif")
]
def contents(args):
path = os.path.join(base_path, *args)
if not os.path.isfile(path):
return ""
with open(path, "rb") as f:
data = f.read()
return data
def process(rule):
if len(rule) == 2:
path, data = rule
content_type = None
else:
path, data, content_type = rule
if isinstance(data, (list, tuple)):
data = contents(data)
return path, data, content_type
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port), lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs))
thread = threading.Thread(target=self._intermediary_server.serve_forever)
thread.daemon = True
thread.start()
self._logger.debug("Intermediary server started")
def _stop_intermediary_server(self):
if self._intermediary_server is None:
return
self._logger.debug("Shutting down intermediary server...")
self._intermediary_server.shutdown()
self._intermediary_server.server_close()
self._logger.debug("Intermediary server shut down")
class LifecycleManager(object):
def __init__(self, plugin_manager):
@@ -981,7 +1128,3 @@ class LifecycleManager(object):
for event in events:
if callback in self._plugin_lifecycle_callbacks[event]:
self._plugin_lifecycle_callbacks[event].remove(callback)
if __name__ == "__main__":
server = Server()
server.run()
+204 -56
View File
@@ -38,6 +38,7 @@ from . import log as api_logs
from . import slicing as api_slicing
from . import printer_profiles as api_printer_profiles
from . import languages as api_languages
from . import system as api_system
VERSION = "0.1"
@@ -100,30 +101,66 @@ def pluginCommand(name):
#~~ first run setup
@api.route("/setup", methods=["POST"])
def firstRunSetup():
if not s().getBoolean(["server", "firstRun"]):
@api.route("/setup/wizard", methods=["GET"])
def wizardState():
if not s().getBoolean(["server", "firstRun"]) and not admin_permission.can():
abort(403)
if "ac" in request.values.keys() and request.values["ac"] in valid_boolean_trues and \
"user" in request.values.keys() and "pass1" in request.values.keys() and \
"pass2" in request.values.keys() and request.values["pass1"] == request.values["pass2"]:
# configure access control
s().setBoolean(["accessControl", "enabled"], True)
octoprint.server.userManager.addUser(request.values["user"], request.values["pass1"], True, ["user", "admin"])
s().setBoolean(["server", "firstRun"], False)
elif "ac" in request.values.keys() and not request.values["ac"] in valid_boolean_trues:
# disable access control
s().setBoolean(["accessControl", "enabled"], False)
seen_wizards = s().get(["server", "seenWizards"])
result = dict()
wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin)
for implementation in wizard_plugins:
name = implementation._identifier
try:
required = implementation.is_wizard_required()
details = implementation.get_wizard_details()
version = implementation.get_wizard_version()
ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation)
except:
logging.getLogger(__name__).exception("There was an error fetching wizard details for {}, ignoring".format(name))
else:
result[name] = dict(required=required, details=details, version=version, ignored=ignored)
return jsonify(result)
@api.route("/setup/wizard", methods=["POST"])
def wizardFinish():
if not s().getBoolean(["server", "firstRun"]) and not admin_permission.can():
abort(403)
data = dict()
try:
data = request.json
except:
abort(400)
if not "handled" in data:
abort(400)
handled = data["handled"]
if s().getBoolean(["server", "firstRun"]):
s().setBoolean(["server", "firstRun"], False)
octoprint.server.loginManager.anonymous_user = octoprint.users.DummyUser
octoprint.server.principals.identity_loaders.appendleft(octoprint.users.dummy_identity_loader)
seen_wizards = dict(s().get(["server", "seenWizards"]))
wizard_plugins = octoprint.server.pluginManager.get_implementations(octoprint.plugin.WizardPlugin)
for implementation in wizard_plugins:
name = implementation._identifier
try:
implementation.on_wizard_finish(name in handled)
if name in handled:
seen_wizards[name] = implementation.get_wizard_version()
except:
logging.getLogger(__name__).exceptino("There was an error finishing the wizard for {}, ignoring".format(name))
s().set(["server", "seenWizards"], seen_wizards)
s().save()
return NO_CONTENT
#~~ system state
@@ -141,51 +178,21 @@ def apiVersion():
"api": VERSION
})
#~~ system control
@api.route("/system", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def performSystemAction():
logger = logging.getLogger(__name__)
if "action" in request.values.keys():
action = request.values["action"]
available_actions = s().get(["system", "actions"])
for availableAction in available_actions:
if availableAction["action"] == action:
async = availableAction["async"] if "async" in availableAction else False
ignore = availableAction["ignore"] if "ignore" in availableAction else False
logger.info("Performing command: %s" % availableAction["command"])
try:
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(availableAction["command"], stderr=sarge.Capture(), shell=True, async=async)
if not async:
if not ignore and p.returncode != 0:
returncode = p.returncode
stderr_text = p.stderr.text
logger.warn("Command failed with return code %i: %s" % (returncode, stderr_text))
return make_response(("Command failed with return code %i: %s" % (returncode, stderr_text), 500, []))
except Exception, e:
if not ignore:
logger.warn("Command failed: %s" % e)
return make_response(("Command failed: %s" % e, 500, []))
break
return NO_CONTENT
#~~ Login/user handling
@api.route("/login", methods=["POST"])
def login():
if octoprint.server.userManager is not None and "user" in request.values.keys() and "pass" in request.values.keys():
username = request.values["user"]
password = request.values["pass"]
data = request.values
if hasattr(request, "json") and request.json:
data = request.json
if "remember" in request.values.keys() and request.values["remember"] == "true":
if octoprint.server.userManager.enabled and "user" in data and "pass" in data:
username = data["user"]
password = data["pass"]
if "remember" in data and data["remember"] in valid_boolean_trues:
remember = True
else:
remember = False
@@ -196,7 +203,7 @@ def login():
user = octoprint.server.userManager.findUser(username)
if user is not None:
if octoprint.server.userManager.checkPassword(username, password):
if octoprint.server.userManager is not None:
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(user)
session["usersession.id"] = user.get_session()
g.user = user
@@ -205,7 +212,7 @@ def login():
return jsonify(user.asDict())
return make_response(("User unknown or password incorrect", 401, []))
elif "passive" in request.values:
elif "passive" in data:
return passive_login()
return NO_CONTENT
@@ -228,3 +235,144 @@ def _logout(user):
if "usersession.id" in session:
del session["usersession.id"]
octoprint.server.userManager.logout_user(user)
@api.route("/util/test", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def utilTestPath():
valid_commands = dict(
path=["path"],
url=["url"]
)
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
if command == "path":
import os
from octoprint.util.paths import normalize
path = normalize(data["path"])
if not path:
return jsonify(path=path, exists=False, typeok=False, access=False, result=False)
check_type = None
check_access = []
if "check_type" in data and data["check_type"] in ("file", "dir"):
check_type = data["check_type"]
if "check_access" in data:
request_check_access = data["check_access"]
if not isinstance(request_check_access, list):
request_check_access = list(request_check_access)
check_access = [check for check in request_check_access if check in ("r", "w", "x")]
exists = os.path.exists(path)
# check if path exists
type_mapping = dict(file=os.path.isfile, dir=os.path.isdir)
if check_type:
typeok = type_mapping[check_type](path)
else:
typeok = True
# check if path allows requested access
access_mapping = dict(r=os.R_OK, w=os.W_OK, x=os.X_OK)
if check_access:
access = os.access(path, reduce(lambda x, y: x | y, map(lambda a: access_mapping[a], check_access)))
else:
access = True
return jsonify(path=path, exists=exists, typeok=typeok, access=access, result=exists and typeok and access)
elif command == "url":
import requests
class StatusCodeRange(object):
def __init__(self, start=None, end=None):
self.start = start
self.end = end
def __contains__(self, item):
if not isinstance(item, int):
return False
if self.start and self.end:
return self.start <= item < self.end
elif self.start:
return self.start <= item
elif self.end:
return item < self.end
else:
return False
def as_dict(self):
return dict(
start=self.start,
end=self.end
)
status_ranges = dict(
informational=StatusCodeRange(start=100,end=200),
success=StatusCodeRange(start=200,end=300),
redirection=StatusCodeRange(start=300,end=400),
client_error=StatusCodeRange(start=400,end=500),
server_error=StatusCodeRange(start=500),
normal=StatusCodeRange(end=400),
error=StatusCodeRange(start=400),
any=StatusCodeRange(start=100)
)
url = data["url"]
method = "HEAD"
check_status = [status_ranges["normal"]]
if "method" in data:
method = data["method"]
if "status" in data:
request_status = data["status"]
if not isinstance(request_status, list):
request_status = [request_status]
check_status = []
for rs in request_status:
if rs in status_ranges:
check_status.append(status_ranges[rs])
else:
code = requests.codes[rs]
if code is not None:
check_status.append([code])
try:
response = requests.request(method=method, url=url)
status = reduce(lambda x, y: x and response.status_code in y, check_status)
except:
status = False
result = dict(
url=url,
status=response.status_code,
result=status.as_dict() if isinstance(status, StatusCodeRange) else status
)
if "response" in data and (data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")):
import base64
content = base64.standard_b64encode(response.content)
if data["response"] == "json":
try:
content = response.json()
except:
logging.getLogger(__name__).exception("Couldn't convert response to json")
result["result"] = False
result["response"] = dict(
headers=dict(response.headers),
content=content
)
return jsonify(**result)
+338 -171
View File
@@ -15,6 +15,7 @@ from octoprint.server.api import api
from octoprint.events import Events
import octoprint.filemanager
import octoprint.filemanager.util
import octoprint.filemanager.storage
import octoprint.slicing
import psutil
@@ -25,11 +26,12 @@ import psutil
@api.route("/files", methods=["GET"])
def readGcodeFiles():
filter = None
if "filter" in request.values:
filter = request.values["filter"]
files = _getFileList(FileDestinations.LOCAL, filter=filter)
filter = "filter" in request.values and request.values["recursive"] in valid_boolean_trues
recursive = "recursive" in request.values and request.values["recursive"] in valid_boolean_trues
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive)
files.extend(_getFileList(FileDestinations.SDCARD))
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
return jsonify(files=files, free=usage.free, total=usage.total)
@@ -39,7 +41,11 @@ def readGcodeFilesForOrigin(origin):
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown origin: %s" % origin, 404)
files = _getFileList(origin)
recursive = False
if "recursive" in request.values:
recursive = request.values["recursive"] == 'true'
files = _getFileList(origin, recursive=recursive)
if origin == FileDestinations.LOCAL:
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
@@ -48,15 +54,47 @@ def readGcodeFilesForOrigin(origin):
return jsonify(files=files)
def _getFileDetails(origin, filename):
files = _getFileList(origin)
for file in files:
if file["name"] == filename:
return file
def _getFileDetails(origin, path):
files = _getFileList(origin, recursive=True)
path = path.split('/')
if len(path) == 1:
# shortcut for files in the root folder
name = path[0]
for f in files:
if f["name"] == name:
return f
return None
node = files
while path:
segment = path.pop(0)
for f in node:
if not f["name"] == segment:
# wrong name => next!
continue
if not path:
# no path left and name matches => found it!
return f
if not f["type"] == "folder":
# path left but not a folder => that doesn't work
return None
# we'll use this folder's children as the next iteration
node = f["children"]
break
else:
# nothing matched the name, we can't find it
return None
# nothing returned until now => not found
return None
def _getFileList(origin, filter=None):
def _getFileList(origin, filter=None, recursive=False):
if origin == FileDestinations.SDCARD:
sdFileList = printer.get_sd_files()
@@ -78,45 +116,59 @@ def _getFileList(origin, filter=None):
filter_func = None
if filter:
filter_func = lambda entry, entry_data: octoprint.filemanager.valid_file_type(entry, type=filter)
files = fileManager.list_files(origin, filter=filter_func, recursive=False)[origin].values()
for file in files:
file["origin"] = FileDestinations.LOCAL
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
file["gcodeAnalysis"] = file["analysis"]
del file["analysis"]
files = fileManager.list_files(origin, filter=filter_func, recursive=recursive)[origin].values()
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
# convert print log
history = file["history"]
del file["history"]
success = 0
failure = 0
last = None
for entry in history:
success += 1 if "success" in entry and entry["success"] else 0
failure += 1 if "success" in entry and not entry["success"] else 0
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
last = entry
if last:
prints = dict(
success=success,
failure=failure,
last=dict(
success=last["success"],
date=last["timestamp"]
)
)
if "printTime" in last:
prints["last"]["printTime"] = last["printTime"]
file["prints"] = prints
def analyse_recursively(files, path=None):
if path is None:
path = ""
for file in files:
file["origin"] = FileDestinations.LOCAL
if file["type"] == "folder":
file["children"] = analyse_recursively(file["children"].values(), path + file["name"] + "/")
else:
if "analysis" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
file["gcodeAnalysis"] = file["analysis"]
del file["analysis"]
if "history" in file and octoprint.filemanager.valid_file_type(file["name"], type="gcode"):
# convert print log
history = file["history"]
del file["history"]
success = 0
failure = 0
last = None
for entry in history:
success += 1 if "success" in entry and entry["success"] else 0
failure += 1 if "success" in entry and not entry["success"] else 0
if not last or ("timestamp" in entry and "timestamp" in last and entry["timestamp"] > last["timestamp"]):
last = entry
if last:
prints = dict(
success=success,
failure=failure,
last=dict(
success=last["success"],
date=last["timestamp"]
)
)
if "printTime" in last:
prints["last"]["printTime"] = last["printTime"]
file["prints"] = prints
file.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=path + file["name"], _external=True),
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + path + file["name"]
}
})
return files
analyse_recursively(files)
file.update({
"refs": {
"resource": url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=file["name"], _external=True),
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + file["name"]
}
})
return files
@@ -127,139 +179,192 @@ def _verifyFileExists(origin, filename):
return fileManager.file_exists(origin, filename)
def _verifyFolderExists(origin, foldername):
if origin == FileDestinations.SDCARD:
return False
else:
return fileManager.folder_exists(origin, foldername)
def _isBusy(target, path):
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and currentOrigin == target and fileManager.file_in_path(FileDestinations.LOCAL, path, currentFilename) and (printer.is_printing() or printer.is_paused()):
return True
return any(target == x[0] and fileManager.file_in_path(FileDestinations.LOCAL, path, x[1]) for x in fileManager.get_busy_files())
@api.route("/files/<string:target>", methods=["POST"])
@restricted_access
def uploadGcodeFile(target):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
input_name = "file"
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
if input_upload_name in request.values and input_upload_path in request.values:
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
upload = octoprint.filemanager.util.DiskFileWrapper(request.values[input_upload_name], request.values[input_upload_path])
else:
return make_response("No file included", 400)
# Store any additional user data the caller may have passed.
userdata = None
if "userdata" in request.values:
import json
# Store any additional user data the caller may have passed.
userdata = None
if "userdata" in request.values:
import json
try:
userdata = json.loads(request.values["userdata"])
except:
return make_response("userdata contains invalid JSON", 400)
if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD card support is disabled", 404)
sd = target == FileDestinations.SDCARD
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
if sd:
# validate that all preconditions for SD upload are met before attempting it
if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())):
return make_response("Can not upload to SD card, printer is either not operational or already busy", 409)
if not printer.is_sd_ready():
return make_response("Can not upload to SD card, not yet initialized", 409)
# determine current job
currentPath = None
currentFilename = None
currentOrigin = None
currentJob = printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if currentJobFile is not None and "name" in currentJobFile.keys() and "origin" in currentJobFile.keys() and currentJobFile["name"] is not None and currentJobFile["origin"] is not None:
currentPath, currentFilename = fileManager.sanitize(FileDestinations.LOCAL, currentJobFile["name"])
currentOrigin = currentJobFile["origin"]
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
userdata = json.loads(request.values["userdata"])
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
futurePath, futureFilename = fileManager.sanitize(FileDestinations.LOCAL, upload.filename)
except:
return make_response("userdata contains invalid JSON", 400)
futurePath = None
futureFilename = None
if target == FileDestinations.SDCARD and not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD card support is disabled", 404)
if futureFilename is None:
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
sd = target == FileDestinations.SDCARD
selectAfterUpload = "select" in request.values.keys() and request.values["select"] in valid_boolean_trues
printAfterSelect = "print" in request.values.keys() and request.values["print"] in valid_boolean_trues
if "path" in request.values and request.values["path"]:
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
futurePath = fileManager.sanitize_path(FileDestinations.LOCAL, request.values["path"])
if sd:
# validate that all preconditions for SD upload are met before attempting it
if not (printer.is_operational() and not (printer.is_printing() or printer.is_paused())):
return make_response("Can not upload to SD card, printer is either not operational or already busy", 409)
if not printer.is_sd_ready():
return make_response("Can not upload to SD card, not yet initialized", 409)
# prohibit overwriting currently selected file while it's being printed
if futurePath == currentPath and futureFilename == currentFilename and target == currentOrigin and (printer.is_printing() or printer.is_paused()):
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
# determine current job
currentFilename = None
currentOrigin = None
currentJob = printer.get_current_job()
if currentJob is not None and "file" in currentJob.keys():
currentJobFile = currentJob["file"]
if "name" in currentJobFile.keys() and "origin" in currentJobFile.keys():
currentFilename = currentJobFile["name"]
currentOrigin = currentJobFile["origin"]
def fileProcessingFinished(filename, absFilename, destination):
"""
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
finished.
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futureFilename = fileManager.sanitize_name(FileDestinations.LOCAL, upload.filename)
except:
futureFilename = None
if futureFilename is None:
return make_response("Can not upload file %s, wrong format?" % upload.filename, 415)
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
"""
# prohibit overwriting currently selected file while it's being printed
if futureFilename == currentFilename and target == currentOrigin and printer.is_printing() or printer.is_paused():
return make_response("Trying to overwrite file that is currently being printed: %s" % currentFilename, 409)
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
else:
selectAndOrPrint(filename, absFilename, destination)
return filename
def fileProcessingFinished(filename, absFilename, destination):
"""
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
finished.
def selectAndOrPrint(filename, absFilename, destination):
"""
Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only
the case after they have finished streaming to the printer, which is why this callback is also used
for the corresponding call to addSdFile.
Depending on the file's destination triggers either streaming to SD card or directly calls selectAndOrPrint.
"""
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
exact file is already selected, such reloading it.
"""
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
if destination == FileDestinations.SDCARD and octoprint.filemanager.valid_file_type(filename, "gcode"):
return filename, printer.add_sd_file(filename, absFilename, selectAndOrPrint)
# FileDestinations.LOCAL = should normally be target, but can't because SDCard handling isn't implemented yet
futureFullPath = fileManager.join_path(FileDestinations.LOCAL, futurePath, futureFilename)
try:
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPath, upload, allow_overwrite=True)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
return make_response("Could not upload the file \"{}\", invalid type".format(upload.filename), 400)
else:
return make_response("Could not upload the file \"{}\"".format(upload.filename), 500)
if octoprint.filemanager.valid_file_type(added_file, "stl"):
filename = added_file
done = True
else:
selectAndOrPrint(filename, absFilename, destination)
return filename
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
done = True
def selectAndOrPrint(filename, absFilename, destination):
"""
Callback for when the file is ready to be selected and optionally printed. For SD file uploads this is only
the case after they have finished streaming to the printer, which is why this callback is also used
for the corresponding call to addSdFile.
if userdata is not None:
# upload included userdata, add this now to the metadata
fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata)
Selects the just uploaded file if either selectAfterUpload or printAfterSelect are True, or if the
exact file is already selected, such reloading it.
"""
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or (currentFilename == filename and currentOrigin == destination)):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
sdFilename = None
if isinstance(filename, tuple):
filename, sdFilename = filename
added_file = fileManager.add_file(FileDestinations.LOCAL, upload.filename, upload, allow_overwrite=True)
if added_file is None:
return make_response("Could not upload the file %s" % upload.filename, 500)
if octoprint.filemanager.valid_file_type(added_file, "stl"):
filename = added_file
done = True
else:
filename = fileProcessingFinished(added_file, fileManager.path_on_disk(FileDestinations.LOCAL, added_file), target)
done = True
eventManager.fire(Events.UPLOAD, {"file": filename, "target": target})
if userdata is not None:
# upload included userdata, add this now to the metadata
fileManager.set_additional_metadata(FileDestinations.LOCAL, added_file, "userdata", userdata)
sdFilename = None
if isinstance(filename, tuple):
filename, sdFilename = filename
eventManager.fire(Events.UPLOAD, {"file": filename, "target": target})
files = {}
location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True)
files.update({
FileDestinations.LOCAL: {
"name": filename,
"origin": FileDestinations.LOCAL,
"refs": {
"resource": location,
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename
}
}
})
if sd and sdFilename:
location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True)
files = {}
location = url_for(".readGcodeFile", target=FileDestinations.LOCAL, filename=filename, _external=True)
files.update({
FileDestinations.SDCARD: {
"name": sdFilename,
"origin": FileDestinations.SDCARD,
FileDestinations.LOCAL: {
"name": filename,
"origin": FileDestinations.LOCAL,
"refs": {
"resource": location
"resource": location,
"download": url_for("index", _external=True) + "downloads/files/" + FileDestinations.LOCAL + "/" + filename
}
}
})
r = make_response(jsonify(files=files, done=done), 201)
r.headers["Location"] = location
return r
if sd and sdFilename:
location = url_for(".readGcodeFile", target=FileDestinations.SDCARD, filename=sdFilename, _external=True)
files.update({
FileDestinations.SDCARD: {
"name": sdFilename,
"origin": FileDestinations.SDCARD,
"refs": {
"resource": location
}
}
})
r = make_response(jsonify(files=files, done=done), 201)
r.headers["Location"] = location
return r
elif "foldername" in request.values:
foldername = request.values["foldername"]
if not target in [FileDestinations.LOCAL]:
return make_response("Unknown target: %s" % target, 400)
futurePath, futureName = fileManager.sanitize(target, foldername)
if not futureName or not futurePath:
return make_response("Can't create a folder with an empty name", 400)
futureFullPath = fileManager.join_path(target, futurePath, futureName)
if octoprint.filemanager.valid_file_type(futureName):
return make_response("Can't create a folder named %s, please try another name" % futureName, 409)
try:
fileManager.add_folder(target, futureFullPath)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:
return make_response("Could not create folder {}, invalid directory".format(futureName))
else:
return make_response("Could not create folder {}".format(futureName))
else:
return make_response("No file to upload and no folder to create", 400)
return NO_CONTENT
@api.route("/files/<string:target>/<path:filename>", methods=["GET"])
@@ -280,13 +385,12 @@ def gcodeFileCommand(filename, target):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"select": [],
"slice": []
"slice": [],
"copy": ["destination"],
"move": ["destination"]
}
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -294,7 +398,13 @@ def gcodeFileCommand(filename, target):
return response
if command == "select":
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
# selects/loads a file
if not octoprint.filemanager.valid_file_type(filename, type="machinecode"):
return make_response("Cannot select {filename} for printing, not a machinecode file".format(**locals()), 415)
printAfterLoading = False
if "print" in data.keys() and data["print"] in valid_boolean_trues:
if not printer.is_operational():
@@ -310,6 +420,9 @@ def gcodeFileCommand(filename, target):
printer.select_file(filenameToSelect, sd, printAfterLoading)
elif command == "slice":
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
try:
if "slicer" in data:
slicer = data["slicer"]
@@ -340,6 +453,13 @@ def gcodeFileCommand(filename, target):
name, _ = os.path.splitext(filename)
gcode_name = name + ".gco"
if "path" in data and data["path"]:
gcode_name = fileManager.join_path(target, data["path"], gcode_name)
else:
path, _ = fileManager.split_path(target, filename)
if path:
gcode_name = fileManager.join_path(target, path, gcode_name)
# prohibit overwriting the file that is currently being printed
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename == gcode_name and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
@@ -416,35 +536,82 @@ def gcodeFileCommand(filename, target):
r.headers["Location"] = location
return r
elif command == "copy" or command == "move":
# Copy and move are only possible on local storage
if not target in [FileDestinations.LOCAL]:
return make_response("Unsupported target for {}: {}".format(command, target), 400)
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
return make_response("File/Folder not found on '%s': %s" % (target, filename), 404)
destination = data["destination"]
if _verifyFolderExists(target, destination):
path, name = fileManager.split_path(target, filename)
destination = fileManager.join_path(target, destination, name)
if _verifyFileExists(target, destination) or _verifyFolderExists(target, destination):
return make_response("File/Folder already exists: %s" % filename, 409)
if command == "copy":
if fileManager.file_exists(target, filename):
fileManager.copy_file(target, filename, destination)
elif fileManager.folder_exists(target, filename):
fileManager.copy_folder(target, filename, destination)
elif command == "move":
if _isBusy(target, filename):
return make_response("Trying to move a file/folder that is currently in use: %s" % filename, 409)
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and filename == currentFilename:
printer.unselect_file()
if fileManager.file_exists(target, filename):
fileManager.move_file(target, filename, destination)
elif fileManager.folder_exists(target, filename):
fileManager.move_folder(target, filename, destination)
return NO_CONTENT
@api.route("/files/<string:target>/<path:filename>", methods=["DELETE"])
@restricted_access
def deleteGcodeFile(filename, target):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 404)
if not _verifyFileExists(target, filename) and not _verifyFolderExists(target, filename):
return make_response("File/Folder not found on '%s': %s" % (target, filename), 404)
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
if _verifyFileExists(target, filename):
if not target in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
return make_response("Unknown target: %s" % target, 400)
# prohibit deleting files that are currently in use
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename == filename and currentOrigin == target and (printer.is_printing() or printer.is_paused()):
make_response("Trying to delete file that is currently being printed: %s" % filename, 409)
if _isBusy(target, filename):
return make_response("Trying to delete a file that is currently in use: %s" % filename, 409)
if (target, filename) in fileManager.get_busy_files():
make_response("Trying to delete a file that is currently in use: %s" % filename, 409)
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and currentOrigin == target and filename == currentFilename:
printer.unselect_file()
# deselect the file if it's currently selected
if currentFilename is not None and filename == currentFilename:
printer.unselect_file()
# delete it
if target == FileDestinations.SDCARD:
printer.delete_sd_file(filename)
else:
fileManager.remove_file(target, filename)
# delete it
if target == FileDestinations.SDCARD:
printer.delete_sd_file(filename)
else:
fileManager.remove_file(target, filename)
elif _verifyFolderExists(target, filename):
if not target in [FileDestinations.LOCAL]:
return make_response("Unknown target: %s" % target, 400)
if _isBusy(target, filename):
return make_response("Trying to delete a folder that contains a file that is currently in use: %s" % filename, 409)
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
if currentFilename is not None and currentOrigin == target and fileManager.file_in_path(target, filename, currentFilename):
printer.unselect_file()
# delete it
fileManager.remove_folder(target, filename)
return NO_CONTENT
+24 -7
View File
@@ -63,6 +63,7 @@ def getSettings():
"temperatureGraph": s.getBoolean(["feature", "temperatureGraph"]),
"waitForStart": s.getBoolean(["feature", "waitForStartOnConnect"]),
"alwaysSendChecksum": s.getBoolean(["feature", "alwaysSendChecksum"]),
"neverSendChecksum": s.getBoolean(["feature", "neverSendChecksum"]),
"sdSupport": s.getBoolean(["feature", "sdSupport"]),
"sdAlwaysAvailable": s.getBoolean(["feature", "sdAlwaysAvailable"]),
"swallowOkAfterResend": s.getBoolean(["feature", "swallowOkAfterResend"]),
@@ -82,10 +83,14 @@ def getSettings():
"timeoutDetection": s.getFloat(["serial", "timeout", "detection"]),
"timeoutCommunication": s.getFloat(["serial", "timeout", "communication"]),
"timeoutTemperature": s.getFloat(["serial", "timeout", "temperature"]),
"timeoutTemperatureTargetSet": s.getFloat(["serial", "timeout", "temperatureTargetSet"]),
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
"log": s.getBoolean(["serial", "log"]),
"additionalPorts": s.get(["serial", "additionalPorts"]),
"longRunningCommands": s.get(["serial", "longRunningCommands"])
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
"longRunningCommands": s.get(["serial", "longRunningCommands"]),
"checksumRequiringCommands": s.get(["serial", "checksumRequiringCommands"]),
"helloCommand": s.get(["serial", "helloCommand"])
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -106,6 +111,7 @@ def getSettings():
"scripts": {
"gcode": {
"afterPrinterConnected": None,
"beforePrinterDisconnected": None,
"beforePrintStarted": None,
"afterPrintCancelled": None,
"afterPrintDone": None,
@@ -165,8 +171,6 @@ def getSettings():
@restricted_access
@admin_permission.require(403)
def setSettings():
logger = logging.getLogger(__name__)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
@@ -174,6 +178,13 @@ def setSettings():
data = request.json
except BadRequest:
return make_response("Malformed JSON body in request", 400)
_saveSettings(data)
return getSettings()
def _saveSettings(data):
logger = logging.getLogger(__name__)
s = settings()
if "api" in data.keys():
@@ -206,6 +217,7 @@ def setSettings():
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 "neverSendChecksum" in data["feature"].keys(): s.setBoolean(["feature", "neverSendChecksum"], data["feature"]["neverSendChecksum"])
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"])
@@ -223,9 +235,13 @@ def setSettings():
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 "timeoutTemperatureTargetSet" in data["serial"].keys(): s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutSdStatus" in data["serial"].keys(): s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
if "checksumRequiringCommands" in data["serial"] and isinstance(data["serial"]["checksumRequiringCommands"], (list, tuple)): s.set(["serial", "checksumRequiringCommands"], data["serial"]["checksumRequiringCommands"])
if "helloCommand" in data["serial"]: s.set(["serial", "helloCommand"], data["serial"]["helloCommand"])
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"].keys(): s.setBoolean(["serial", "log"], data["serial"]["log"])
@@ -287,7 +303,8 @@ def setSettings():
logger.exception("Could not save settings for plugin {name} ({version})".format(version=plugin._plugin_version, name=plugin._plugin_name))
if s.save():
eventManager().fire(Events.SETTINGS_UPDATED)
return getSettings()
payload = dict(
config_hash=s.config_hash,
effective_hash=s.effective_hash
)
eventManager().fire(Events.SETTINGS_UPDATED, payload=payload)
+7 -8
View File
@@ -127,17 +127,16 @@ def slicingPatchSlicerProfile(slicer, name):
if "description" in json_data:
description = json_data["description"]
saved_profile = slicingManager.save_profile(slicer, name, profile,
allow_overwrite=True,
overrides=data,
display_name=display_name,
description=description)
from octoprint.server.api import valid_boolean_trues
if "default" in json_data and json_data["default"] in valid_boolean_trues:
default_profiles = s().get(["slicing", "defaultProfiles"])
if not default_profiles:
default_profiles = dict()
default_profiles[slicer] = name
s().set(["slicing", "defaultProfiles"], default_profiles)
s().save(force=True)
slicingManager.set_default_profile(slicer, name, require_exists=False)
saved_profile = slicingManager.save_profile(slicer, name, profile,
allow_overwrite=True, overrides=data, display_name=display_name, description=description)
return jsonify(_getSlicingProfileData(slicer, name, saved_profile))
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
+185
View File
@@ -0,0 +1,185 @@
# coding=utf-8
from __future__ import absolute_import
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import collections
import logging
import sarge
from flask import request, make_response, jsonify, url_for
from flask.ext.babel import gettext
from octoprint.settings import settings as s
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import restricted_access, get_remote_address
@api.route("/system", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def performSystemAction():
logging.getLogger(__name__).warn("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/<action>".format(get_remote_address(request)))
data = request.values
if hasattr(request, "json") and request.json:
data = request.json
if not "action" in data:
return make_response("action for perform is not defined", 400)
return executeSystemCommand("custom", data["action"])
@api.route("/system/commands", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def retrieveSystemCommands():
return jsonify(core=_to_client_specs(_get_core_command_specs()),
custom=_to_client_specs(_get_custom_command_specs()))
@api.route("/system/commands/<string:source>", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def retrieveSystemCommandsForSource(source):
if source == "core":
specs = _get_core_command_specs()
elif source == "custom":
specs = _get_custom_command_specs()
else:
return make_response("Unknown system command source: {}".format(source), 400)
return jsonify(_to_client_specs(specs))
@api.route("/system/commands/<string:source>/<string:command>", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def executeSystemCommand(source, command):
logger = logging.getLogger(__name__)
if command == "divider":
return make_response("Dividers cannot be executed", 400)
command_spec = _get_command_spec(source, command)
if not command_spec:
return make_response("Command {}:{} not found".format(source, command), 404)
if not "command" in command_spec:
return make_response("Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500)
async = command_spec["async"] if "async" in command_spec else False
ignore = command_spec["ignore"] if "ignore" in command_spec else False
logger.info("Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
try:
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(command_spec["command"],
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True,
async=async)
if not async:
if not ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
error = "Command failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(returncode, stdout_text, stderr_text)
logger.warn(error)
return make_response(error, 500)
except Exception, e:
if not ignore:
error = "Command failed: {}".format(str(e))
logger.warn(error)
return make_response(error, 500)
return NO_CONTENT
def _to_client_specs(specs):
result = list()
for spec in specs.values():
if not "action" in spec or not "source" in spec:
continue
copied = dict((k, v) for k, v in spec.items() if k in ("source", "action", "name", "confirm"))
copied["resource"] = url_for(".executeSystemCommand",
source=spec["source"],
command=spec["action"],
_external=True)
result.append(copied)
return result
def _get_command_spec(source, action):
if source == "core":
return _get_core_command_spec(action)
elif source == "custom":
return _get_custom_command_spec(action)
else:
return None
def _get_core_command_specs():
commands = collections.OrderedDict(
shutdown=dict(
command=s().get(["server", "commands", "systemShutdownCommand"]),
name=gettext("Shutdown"),
confirm=gettext("You are about to shutdown the system.")),
reboot=dict(
command=s().get(["server", "commands", "systemRestartCommand"]),
name=gettext("Reboot"),
confirm=gettext("You are about to reboot the system.")),
restart=dict(
command=s().get(["server", "commands", "serverRestartCommand"]),
name="Restart OctoPrint",
confirm="You are about to restart the OctoPrint server.")
)
available_commands = dict()
for action, spec in commands.items():
if not spec["command"]:
continue
spec.update(dict(action=action, source="core", async=True, ignore=True))
available_commands[action] = spec
return available_commands
def _get_core_command_spec(action):
available_actions = _get_core_command_specs()
if not action in available_actions:
logging.getLogger(__name__).warn("Command for core action {} is not configured, you need to configure the command before it can be used".format(action))
return None
return available_actions[action]
def _get_custom_command_specs():
specs = collections.OrderedDict()
dividers = 0
for spec in s().get(["system", "actions"]):
if not "action" in spec:
continue
copied = dict(spec)
copied["source"] = "custom"
action = spec["action"]
if action == "divider":
dividers += 1
action = "divider_{}".format(dividers)
specs[action] = copied
return specs
def _get_custom_command_spec(action):
available_actions = _get_custom_command_specs()
if not action in available_actions:
return None
return available_actions[action]
+16 -12
View File
@@ -68,52 +68,56 @@ def deleteTimelapse(filename):
@api.route("/timelapse", methods=["POST"])
@restricted_access
def setTimelapseConfig():
if "type" in request.values:
data = request.values
if hasattr(request, "json") and request.json:
data = request.json
if "type" in data:
config = {
"type": request.values["type"],
"type": data["type"],
"postRoll": 0,
"fps": 25,
"options": {}
}
if "postRoll" in request.values:
if "postRoll" in data:
try:
postRoll = int(request.values["postRoll"])
postRoll = int(data["postRoll"])
except ValueError:
return make_response("Invalid value for postRoll: %r" % request.values["postRoll"], 400)
return make_response("Invalid value for postRoll: %r" % data["postRoll"], 400)
else:
if postRoll >= 0:
config["postRoll"] = postRoll
else:
return make_response("Invalid value for postRoll: %d" % postRoll, 400)
if "fps" in request.values:
if "fps" in data:
try:
fps = int(request.values["fps"])
fps = int(data["fps"])
except ValueError:
return make_response("Invalid value for fps: %r" % request.values["fps"], 400)
return make_response("Invalid value for fps: %r" % data["fps"], 400)
else:
if fps > 0:
config["fps"] = fps
else:
return make_response("Invalid value for fps: %d" % fps, 400)
if "interval" in request.values:
if "interval" in data:
config["options"] = {
"interval": 10
}
try:
interval = int(request.values["interval"])
interval = int(data["interval"])
except ValueError:
return make_response("Invalid value for interval: %r" % request.values["interval"])
return make_response("Invalid value for interval: %r" % data["interval"])
else:
if interval > 0:
config["options"]["interval"] = interval
else:
return make_response("Invalid value for interval: %d" % interval)
if admin_permission.can() and "save" in request.values and request.values["save"] in valid_boolean_trues:
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
octoprint.timelapse.configureTimelapse(config, True)
else:
octoprint.timelapse.configureTimelapse(config)
+10 -10
View File
@@ -23,7 +23,7 @@ from octoprint.server.util.flask import restricted_access
@restricted_access
@admin_permission.require(403)
def getUsers():
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
return jsonify({"users": userManager.getAllUsers()})
@@ -33,7 +33,7 @@ def getUsers():
@restricted_access
@admin_permission.require(403)
def addUser():
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if not "application/json" in request.headers["Content-Type"]:
@@ -62,7 +62,7 @@ def addUser():
@api.route("/users/<username>", methods=["GET"])
@restricted_access
def getUser(username):
if userManager is None:
if not userManager.enabled:
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()):
@@ -79,7 +79,7 @@ def getUser(username):
@restricted_access
@admin_permission.require(403)
def updateUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
user = userManager.findUser(username)
@@ -110,7 +110,7 @@ def updateUser(username):
@restricted_access
@admin_permission.require(http_exception=403)
def removeUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
try:
@@ -123,7 +123,7 @@ def removeUser(username):
@api.route("/users/<username>/password", methods=["PUT"])
@restricted_access
def changePasswordForUser(username):
if userManager is None:
if not userManager.enabled:
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()):
@@ -151,7 +151,7 @@ def changePasswordForUser(username):
@api.route("/users/<username>/settings", methods=["GET"])
@restricted_access
def getSettingsForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
@@ -165,7 +165,7 @@ def getSettingsForUser(username):
@api.route("/users/<username>/settings", methods=["PATCH"])
@restricted_access
def changeSettingsForUser(username):
if userManager is None:
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
@@ -185,7 +185,7 @@ def changeSettingsForUser(username):
@api.route("/users/<username>/apikey", methods=["DELETE"])
@restricted_access
def deleteApikeyForUser(username):
if userManager is None:
if not userManager.enabled:
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()):
@@ -201,7 +201,7 @@ def deleteApikeyForUser(username):
@api.route("/users/<username>/apikey", methods=["POST"])
@restricted_access
def generateApikeyForUser(username):
if userManager is None:
if not userManager.enabled:
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()):
+17 -3
View File
@@ -44,7 +44,7 @@ def apiKeyRequestHandler():
# ui api key => continue regular request processing
return
if not settings().get(["api", "enabled"]):
if not settings().getBoolean(["api", "enabled"]):
# api disabled => 401
return _flask.make_response("API disabled", 401)
@@ -116,11 +116,11 @@ def optionsAllowOrigin(request):
def get_user_for_apikey(apikey):
if settings().get(["api", "enabled"]) and apikey is not None:
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
if apikey == settings().get(["api", "key"]) or octoprint.server.appSessionManager.validate(apikey):
# master key or an app session key was used
return ApiUser()
elif octoprint.server.userManager is not None:
elif octoprint.server.userManager.enabled:
# user key might have been used
return octoprint.server.userManager.findUser(apikey=apikey)
return None
@@ -143,6 +143,20 @@ def get_api_key(request):
return None
def get_plugin_hash():
from octoprint.plugin import plugin_manager
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
template_plugins = map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin))
asset_plugins = map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.AssetPlugin))
ui_plugins = sorted(set(template_plugins + asset_plugins))
import hashlib
plugin_hash = hashlib.sha1()
plugin_hash.update(",".join(ui_plugins))
return plugin_hash.hexdigest()
#~~ reverse proxy compatible WSGI middleware
+237 -10
View File
@@ -14,6 +14,7 @@ import flask.ext.assets
import webassets.updater
import webassets.utils
import functools
import contextlib
import time
import uuid
import threading
@@ -221,7 +222,7 @@ def fix_webassets_filtertool():
#~~ passive login helper
def passive_login():
if octoprint.server.userManager is not None:
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.login_user(flask.ext.login.current_user)
else:
user = flask.ext.login.current_user
@@ -330,13 +331,14 @@ def cached(timeout=5 * 60, key=lambda: "view:%s" % flask.request.path, unless=No
return f(*args, **kwargs)
cache_key = key()
rv = _cache.get(cache_key)
# 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 for {path} from cache".format(path=flask.request.path))
return rv
if rv is not None and (not callable(refreshif) or not refreshif(rv)):
logger.debug("Serving entry for {path} from cache (key: {key})".format(path=flask.request.path, key=cache_key))
if not "X-From-Cache" in rv.headers:
rv.headers["X-From-Cache"] = "true"
return rv
# get value from wrapped function
logger.debug("No cache entry or refreshing cache for {path} (key: {key}), calling wrapped function".format(path=flask.request.path, key=cache_key))
@@ -377,6 +379,222 @@ def cache_check_response_headers(response):
return False
class PreemptiveCache(object):
def __init__(self, cachefile):
self.cachefile = cachefile
self._lock = threading.RLock()
self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
self._log_access = True
def record(self, data, unless=None):
if callable(unless) and unless():
return
entry_data = data
if callable(entry_data):
entry_data = entry_data()
if entry_data is not None:
from flask import request
self.add_data(request.path, entry_data)
@contextlib.contextmanager
def disable_access_logging(self):
with self._lock:
self._log_access = False
yield
self._log_access = True
def clean_all_data(self, cleanup_function):
assert callable(cleanup_function)
with self._lock:
all_data = self.get_all_data()
for root, entries in all_data.items():
old_count = len(entries)
entries = cleanup_function(root, entries)
if not entries:
del all_data[root]
self._logger.debug("Removed root {} from preemptive cache".format(root))
elif len(entries) < old_count:
all_data[root] = entries
self._logger.debug("Removed {} from preemptive cache for root {}".format(old_count - len(entries), root))
self.set_all_data(all_data)
return all_data
def get_all_data(self):
import yaml
cache_data = None
with self._lock:
try:
with open(self.cachefile, "r") as f:
cache_data = yaml.safe_load(f)
except IOError as e:
import errno
if e.errno != errno.ENOENT:
raise
except:
self._logger.exception("Error while reading {}".format(self.cachefile))
if cache_data is None:
cache_data = dict()
return cache_data
def get_data(self, root):
cache_data = self.get_all_data()
return cache_data.get(root, dict())
def set_all_data(self, data):
from octoprint.util import atomic_write
import yaml
with self._lock:
try:
with atomic_write(self.cachefile, "wb") as handle:
yaml.safe_dump(data, handle,default_flow_style=False, indent=" ", allow_unicode=True)
except:
self._logger.exception("Error while writing {}".format(self.cachefile))
def set_data(self, root, data):
with self._lock:
all_data = self.get_all_data()
all_data[root] = data
self.set_all_data(all_data)
def add_data(self, root, data):
from octoprint.util import dict_filter
def strip_ignored(d):
return dict_filter(d, lambda k, v: not k.startswith("_"))
def compare(a, b):
return set(strip_ignored(a).items()) == set(strip_ignored(b).items())
def split_matched_and_unmatched(entry, entries):
matched = []
unmatched = []
for e in entries:
if compare(e, entry):
matched.append(e)
else:
unmatched.append(e)
return matched, unmatched
with self._lock:
cache_data = self.get_all_data()
if not root in cache_data:
cache_data[root] = []
existing, other = split_matched_and_unmatched(data, cache_data[root])
def get_newest(entries):
result = None
for entry in entries:
if "_timestamp" in entry and (result is None or ("_timestamp" in entry and result["_timestamp"] < entry["_timestamp"])):
result = entry
return result
to_persist = get_newest(existing)
if not to_persist:
import copy
to_persist = copy.deepcopy(data)
to_persist["_timestamp"] = time.time()
to_persist["_count"] = 1
self._logger.info("Adding entry for {} and {!r}".format(root, to_persist))
elif self._log_access:
to_persist["_timestamp"] = time.time()
to_persist["_count"] = to_persist.get("_count", 0) + 1
self._logger.debug("Updating timestamp and counter for {} and {!r}".format(root, data))
else:
self._logger.debug("Not updating timestamp and counter for {} and {!r}, currently flagged as disabled".format(root, data))
self.set_data(root, [to_persist] + other)
def preemptively_cached(cache, data, unless=None):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
cache.record(data, unless=unless)
return f(*args, **kwargs)
return decorated_function
return decorator
def etagged(etag):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if isinstance(rv, flask.Response):
result = etag
if callable(result):
result = result(rv)
if result:
rv.set_etag(result)
return rv
return decorated_function
return decorator
def lastmodified(date):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
rv = f(*args, **kwargs)
if not "Last-Modified" in rv.headers:
result = date
if callable(result):
result = result(rv)
if not isinstance(result, basestring):
from werkzeug.http import http_date
result = http_date(result)
if result:
rv.headers["Last-Modified"] = result
return rv
return decorated_function
return decorator
def conditional(condition, met):
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
if callable(condition) and condition():
# condition has been met, return met-response
rv = met
if callable(met):
rv = met()
return rv
# condition hasn't been met, call decorated function
return f(*args, **kwargs)
return decorated_function
return decorator
def check_etag(etag):
return flask.request.method in ("GET", "HEAD") and \
flask.request.if_none_match and \
etag in flask.request.if_none_match
def check_lastmodified(lastmodified):
return flask.request.method in ("GET", "HEAD") and \
flask.request.if_modified_since and \
lastmodified >= flask.request.if_modified_since
def add_non_caching_response_headers(response):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
response.headers["Pragma"] = "no-cache"
@@ -430,7 +648,7 @@ def _get_flask_user_from_request(request):
from octoprint.settings import settings
apikey = octoprint.server.util.get_api_key(request)
if settings().get(["api", "enabled"]) and apikey is not None:
if settings().getBoolean(["api", "enabled"]) and apikey is not None:
user = octoprint.server.util.get_user_for_apikey(apikey)
else:
user = flask.ext.login.current_user
@@ -482,7 +700,7 @@ def restricted_access(func):
@functools.wraps(func)
def decorated_view(*args, **kwargs):
# if OctoPrint hasn't been set up yet, abort
if settings().getBoolean(["server", "firstRun"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
if settings().getBoolean(["server", "firstRun"]) and settings().getBoolean(["accessControl", "enabled"]) and (octoprint.server.userManager is None or not octoprint.server.userManager.hasBeenCustomized()):
return flask.make_response("OctoPrint isn't setup yet", 403)
apikey = octoprint.server.util.get_api_key(flask.request)
@@ -673,10 +891,16 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
less=[]
)
assets["js"] = [
'js/app/bindings/allowbindings.js',
'js/app/bindings/contextmenu.js',
'js/app/bindings/invisible.js',
'js/app/bindings/popover.js',
'js/app/bindings/qrcode.js',
'js/app/bindings/slimscrolledforeach.js',
'js/app/bindings/togglecontent.js',
'js/app/viewmodels/appearance.js',
'js/app/viewmodels/connection.js',
'js/app/viewmodels/control.js',
'js/app/viewmodels/firstrun.js',
'js/app/viewmodels/files.js',
'js/app/viewmodels/loginstate.js',
'js/app/viewmodels/navigation.js',
@@ -684,12 +908,15 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
'js/app/viewmodels/printerprofiles.js',
'js/app/viewmodels/settings.js',
'js/app/viewmodels/slicing.js',
'js/app/viewmodels/system.js',
'js/app/viewmodels/temperature.js',
'js/app/viewmodels/terminal.js',
'js/app/viewmodels/timelapse.js',
'js/app/viewmodels/users.js',
'js/app/viewmodels/log.js',
'js/app/viewmodels/usersettings.js'
'js/app/viewmodels/usersettings.js',
'js/app/viewmodels/wizard.js',
'js/app/viewmodels/about.js'
]
if enable_gcodeviewer:
assets["js"] += [
+11 -7
View File
@@ -13,6 +13,7 @@ import time
import octoprint.timelapse
import octoprint.server
from octoprint.events import Events
from octoprint.settings import settings
import octoprint.printer
@@ -58,14 +59,17 @@ class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.
plugin_hash = hashlib.md5()
plugin_hash.update(",".join(ui_plugins))
config_hash = settings().config_hash
# connected => update the API key, might be necessary if the client was left open while the server restarted
self._emit("connected", {
"apikey": octoprint.server.UI_API_KEY,
"version": octoprint.server.VERSION,
"display_version": octoprint.server.DISPLAY_VERSION,
"branch": octoprint.server.BRANCH,
"plugin_hash": plugin_hash.hexdigest()
})
self._emit("connected", dict(
apikey=octoprint.server.UI_API_KEY,
version=octoprint.server.VERSION,
display_version=octoprint.server.DISPLAY_VERSION,
branch=octoprint.server.BRANCH,
plugin_hash=plugin_hash.hexdigest(),
config_hash=config_hash
))
self._printer.register_callback(self)
self._fileManager.register_slicingprogress_callback(self)
+18 -1
View File
@@ -800,12 +800,16 @@ class LargeResponseHandler(tornado.web.StaticFileHandler):
self._access_validation(self.request)
if self._path_validation is not None:
self._path_validation(path)
if "cookie" in self.request.arguments:
self.set_cookie(self.request.arguments["cookie"][0], "true", path="/")
result = tornado.web.StaticFileHandler.get(self, path, include_body=include_body)
return result
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment")
self.set_header("Content-Disposition", "attachment; filename=%s" % os.path.basename(path))
if not self._allow_client_caching:
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
@@ -927,6 +931,19 @@ class UrlProxyHandler(tornado.web.RequestHandler):
return "%s%s" % (self._basename, extension)
class StaticDataHandler(tornado.web.RequestHandler):
def initialize(self, data="", content_type="text/plain"):
self.data = data
self.content_type = content_type
def get(self, *args, **kwargs):
self.set_status(200)
self.set_header("Content-Type", self.content_type)
self.write(self.data)
self.flush()
self.finish()
#~~ Factory method for creating Flask access validation wrappers from the Tornado request context
+445 -118
View File
@@ -6,6 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import os
import datetime
from collections import defaultdict
from flask import request, g, url_for, make_response, render_template, send_from_directory, redirect
@@ -13,7 +14,8 @@ from flask import request, g, url_for, make_response, render_template, send_from
import octoprint.plugin
from octoprint.server import app, userManager, pluginManager, gettext, \
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH
debug, LOCALES, VERSION, DISPLAY_VERSION, UI_API_KEY, BRANCH, preemptiveCache, \
NOT_MODIFIED
from octoprint.settings import settings
import re
@@ -23,24 +25,254 @@ from . import util
import logging
_logger = logging.getLogger(__name__)
_templates = None
_plugin_names = None
_plugin_vars = None
_valid_id_re = re.compile("[a-z_]+")
_valid_div_re = re.compile("[a-zA-Z_-]+")
@app.route("/")
@util.flask.cached(timeout=-1,
refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
key=lambda: "view:{}:{}".format(request.base_url, g.locale),
unless_response=util.flask.cache_check_response_headers)
def index():
global _templates, _plugin_names, _plugin_vars
# helper to check if wizards are active
def wizard_active(templates):
return templates is not None and bool(templates["wizard"]["order"])
# we force a refresh if the client forces one or if we have wizards cached
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates)
# if we need to refresh our template cache or it's not yet set, process it
if force_refresh or _templates is None or _plugin_names is None or _plugin_vars is None:
_templates, _plugin_names, _plugin_vars = _process_templates()
now = datetime.datetime.utcnow()
render_kwargs = _get_render_kwargs(_templates, _plugin_names, _plugin_vars, now)
def get_preemptively_cached_view(key, view, data=None, additional_request_data=None):
if (data is None and additional_request_data is None) or g.locale is None:
return view
d = dict(path=request.path,
base_url=request.base_url,
query_string="l10n={}".format(g.locale.language))
if key != "_default":
d["plugin"] = key
# add data if we have any
if data is not None:
try:
if callable(data):
data = data()
if data:
if "query_string" in data:
data["query_string"] = "l10n={}&{}".format(g.locale.language, data["query_string"])
d.update(data)
except:
_logger.exception("Error collecting data for preemptive cache from plugin {}".format(key))
# add additional request data if we have any
if callable(additional_request_data):
try:
ard = additional_request_data()
if ard:
d.update(dict(
_additional_request_data = ard
))
except:
_logger.exception("Error retrieving additional data for preemptive cache from plugin {}".format(key))
# finally decorate our view
return util.flask.preemptively_cached(cache=preemptiveCache,
data=d,
unless=lambda: request.url_root in settings().get(["server", "preemptiveCache", "exceptions"]))(view)
def get_cached_view(key, view, additional_key_data=None, additional_files=None, custom_files=None, custom_etag=None, custom_lastmodified=None):
def cache_key():
k = "ui:{}:{}:{}".format(key, request.base_url, g.locale.language if g.locale else "default")
if callable(additional_key_data):
try:
ak = additional_key_data()
if ak:
# we have some additional key components, let's attach them
if not isinstance(ak, (list, tuple)):
ak = [ak]
k = "{}:{}".format(k, ":".join(ak))
except:
_logger.exception("Error while trying to retrieve additional cache key parts for plugin {}".format(key))
return k
def check_etag_and_lastmodified():
files = collect_files()
lastmodified = compute_lastmodified(files)
lastmodified_ok = util.flask.check_lastmodified(lastmodified)
etag_ok = util.flask.check_etag(compute_etag(files, lastmodified))
return lastmodified_ok and etag_ok
def validate_cache(cached):
etag_different = compute_etag() != cached.get_etag()[0]
return force_refresh or etag_different
def collect_files():
if callable(custom_files):
try:
files = custom_files()
if files:
return files
except:
_logger.exception("Error while trying to retrieve tracked files for plugin {}".format(key))
templates = _get_all_templates()
assets = _get_all_assets()
translations = _get_all_translationfiles(g.locale.language if g.locale else "en",
"messages")
files = templates + assets + translations
if callable(additional_files):
try:
af = additional_files()
if af:
files += af
except:
_logger.exception("Error while trying to retrieve additional tracked files for plugin {}".format(key))
return sorted(set(files))
def compute_lastmodified(files=None):
if callable(custom_lastmodified):
try:
lastmodified = custom_lastmodified()
if lastmodified:
return lastmodified
except:
_logger.exception("Error while trying to retrieve custom LastModified value for plugin {}".format(key))
if files is None:
files = collect_files()
return _compute_date(files)
def compute_etag(files=None, lastmodified=None):
if callable(custom_etag):
try:
etag = custom_etag()
if etag:
return etag
except:
_logger.exception("Error while trying to retrieve custom ETag value for plugin {}".format(key))
if files is None:
files = collect_files()
if lastmodified is None:
lastmodified = compute_lastmodified(files)
if lastmodified and not isinstance(lastmodified, basestring):
from werkzeug.http import http_date
lastmodified = http_date(lastmodified)
import hashlib
hash = hashlib.sha1()
hash.update(octoprint.__version__)
hash.update(octoprint.server.UI_API_KEY)
hash.update(",".join(sorted(files)))
if lastmodified:
hash.update(lastmodified)
return hash.hexdigest()
decorated_view = view
decorated_view = util.flask.lastmodified(lambda _: compute_lastmodified())(decorated_view)
decorated_view = util.flask.etagged(lambda _: compute_etag())(decorated_view)
decorated_view = util.flask.cached(timeout=-1,
refreshif=validate_cache,
key=cache_key,
unless_response=util.flask.cache_check_response_headers)(decorated_view)
decorated_view = util.flask.conditional(check_etag_and_lastmodified, NOT_MODIFIED)(decorated_view)
return decorated_view
ui_plugins = pluginManager.get_implementations(octoprint.plugin.UiPlugin, sorting_context="UiPlugin.on_ui_render")
for plugin in ui_plugins:
if plugin.will_handle_ui(request):
# plugin claims responsibility, let it render the UI
cached = get_cached_view(plugin._identifier,
plugin.on_ui_render,
additional_key_data=plugin.get_ui_additional_key_data_for_cache,
additional_files=plugin.get_ui_additional_tracked_files,
custom_files=plugin.get_ui_custom_tracked_files,
custom_etag=plugin.get_ui_custom_etag,
custom_lastmodified=plugin.get_ui_custom_lastmodified)
preemptively_cached = get_preemptively_cached_view(plugin._identifier,
cached,
plugin.get_ui_data_for_preemptive_caching,
plugin.get_ui_additional_request_data_for_preemptive_caching)
response = preemptively_cached(now, request, render_kwargs)
if response is not None:
break
else:
wizard = wizard_active(_templates)
enable_accesscontrol = userManager.enabled
render_kwargs.update(dict(
webcamStream=settings().get(["webcam", "stream"]),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
enableAccessControl=enable_accesscontrol,
enableSdSupport=settings().get(["feature", "sdSupport"]),
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
wizard=wizard,
now=now,
))
# no plugin took an interest, we'll use the default UI
def make_default_ui():
r = make_response(render_template("index.jinja2", **render_kwargs))
if wizard:
# if we have active wizard dialogs, set non caching headers
r = util.flask.add_non_caching_response_headers(r)
return r
cached = get_cached_view("_default",
make_default_ui)
preemptively_cached = get_preemptively_cached_view("_default",
cached,
dict(),
dict())
response = preemptively_cached()
return response
def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
#~~ a bunch of settings
first_run = settings().getBoolean(["server", "firstRun"])
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
#~~ prepare full set of template vars for rendering
render_kwargs = dict(
debug=debug,
firstRun=first_run,
version=dict(number=VERSION, display=DISPLAY_VERSION, branch=BRANCH),
uiApiKey=UI_API_KEY,
templates=templates,
pluginNames=plugin_names,
locales=locales,
)
render_kwargs.update(plugin_vars)
return render_kwargs
def _process_templates():
enable_accesscontrol = userManager.enabled
first_run = settings().getBoolean(["server", "firstRun"])
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
enable_systemmenu = settings().get(["system"]) is not None and settings().get(["system", "actions"]) is not None
preferred_stylesheet = settings().get(["devel", "stylesheet"])
locales = dict((l.language, dict(language=l.language, display=l.display_name, english=l.english_name)) for l in LOCALES)
##~~ prepare templates
@@ -53,6 +285,8 @@ def index():
tab=dict(div=lambda x: "tab_plugin_" + x, template=lambda x: x + "_tab.jinja2", to_entry=lambda data: (data["name"], data)),
settings=dict(div=lambda x: "settings_plugin_" + x, template=lambda x: x + "_settings.jinja2", to_entry=lambda data: (data["name"], data)),
usersettings=dict(div=lambda x: "usersettings_plugin_" + x, template=lambda x: x + "_usersettings.jinja2", to_entry=lambda data: (data["name"], data)),
wizard=dict(div=lambda x: "wizard_plugin_" + x, template=lambda x: x + "_wizard.jinja2", to_entry=lambda data: (data["name"], data)),
about=dict(div=lambda x: "about_plugin_" + x, template=lambda x: x + "_about.jinja2", to_entry=lambda data: (data["name"], data)),
generic=dict(template=lambda x: x + ".jinja2", to_entry=lambda data: data)
)
@@ -63,6 +297,8 @@ def index():
tab=dict(add="append", key="name"),
settings=dict(add="custom_append", key="name", custom_add_entries=lambda missing: dict(section_plugins=(gettext("Plugins"), None)), custom_add_order=lambda missing: ["section_plugins"] + missing),
usersettings=dict(add="append", key="name"),
wizard=dict(add="append", key="name", key_extractor=lambda d, k: "0:{}".format(d[0]) if "mandatory" in d[1] and d[1]["mandatory"] else "1:{}".format(d[0])),
about=dict(add="append", key="name"),
generic=dict(add="append", key=None)
)
@@ -149,7 +385,7 @@ def index():
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)),
webcam=(gettext("Webcam & Timelapse"), 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),
@@ -170,19 +406,52 @@ def index():
interface=(gettext("Interface"), dict(template="dialogs/usersettings/interface.jinja2", _div="usersettings_interface", custom_bindings=False)),
)
# wizard
if first_run:
def custom_insert_order(existing, missing):
if "firstrunstart" in missing:
missing.remove("firstrunstart")
if "firstrunend" in missing:
missing.remove("firstrunend")
return ["firstrunstart"] + existing + missing + ["firstrunend"]
template_sorting["wizard"].update(dict(add="custom_insert", custom_insert_entries=lambda missing: dict(), custom_insert_order=custom_insert_order))
templates["wizard"]["entries"] = dict(
firstrunstart=(gettext("Start"), dict(template="dialogs/wizard/firstrun_start.jinja2", _div="wizard_firstrun_start")),
firstrunend=(gettext("Finish"), dict(template="dialogs/wizard/firstrun_end.jinja2", _div="wizard_firstrun_end")),
)
# about dialog
templates["about"]["entries"] = dict(
about=(gettext("About OctoPrint"), dict(template="dialogs/about/about.jinja2", _div="about_about", custom_bindings=False)),
license=(gettext("OctoPrint License"), dict(template="dialogs/about/license.jinja2", _div="about_license", custom_bindings=False)),
thirdparty=(gettext("Third Party Licenses"), dict(template="dialogs/about/thirdparty.jinja2", _div="about_thirdparty", custom_bindings=False)),
authors=(gettext("Authors"), dict(template="dialogs/about/authors.jinja2", _div="about_authors", custom_bindings=False)),
changelog=(gettext("Changelog"), dict(template="dialogs/about/changelog.jinja2", _div="about_changelog", custom_bindings=False))
)
# extract data from template plugins
template_plugins = pluginManager.get_implementations(octoprint.plugin.TemplatePlugin)
plugin_vars = dict()
plugin_names = set()
seen_wizards = settings().get(["server", "seenWizards"]) if not first_run else dict()
for implementation in template_plugins:
name = implementation._identifier
plugin_names.add(name)
wizard_required = False
wizard_ignored = False
try:
vars = implementation.get_template_vars()
configs = implementation.get_template_configs()
if isinstance(implementation, octoprint.plugin.WizardPlugin):
wizard_required = implementation.is_wizard_required()
wizard_ignored = octoprint.plugin.WizardPlugin.is_wizard_ignored(seen_wizards, implementation)
except:
_logger.exception("Error while retrieving template data for plugin {}, ignoring it".format(name))
continue
@@ -197,6 +466,9 @@ def index():
includes = _process_template_configs(name, implementation, configs, template_rules)
if not wizard_required or wizard_ignored:
includes["wizard"] = list()
for t in template_types:
for include in includes[t]:
if t == "navbar" or t == "generic":
@@ -234,18 +506,20 @@ def index():
if len(missing_in_order) == 0:
continue
# finally add anything that's not included in our order yet
sorted_missing = list(missing_in_order)
if template_sorting[t]["key"] is not None:
# default extractor: works with entries that are dicts and entries that are 2-tuples with the
# entry data at index 1
def extractor(item, key):
if isinstance(item, dict) and key in item:
return item[key]
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
return item[1][key]
# works with entries that are dicts and entries that are 2-tuples with the
# entry data at index 1
def config_extractor(item, key, default_value=None):
if isinstance(item, dict) and key in item:
return item[key] if key in item else default_value
elif isinstance(item, tuple) and len(item) > 1 and isinstance(item[1], dict) and key in item[1]:
return item[1][key] if key in item[1] else default_value
return None
return default_value
# finally add anything that's not included in our order yet
if template_sorting[t]["key"] is not None:
# we'll use our config extractor as default key extractor
extractor = config_extractor
# if template type provides custom extractor, make sure its exceptions are handled
if "key_extractor" in template_sorting[t] and callable(template_sorting[t]["key_extractor"]):
@@ -260,7 +534,20 @@ def index():
extractor = create_safe_extractor(template_sorting[t]["key_extractor"])
sort_key = template_sorting[t]["key"]
sorted_missing = sorted(missing_in_order, key=lambda x: extractor(templates[t]["entries"][x], sort_key))
def key_func(x):
config = templates[t]["entries"][x]
entry_order = config_extractor(config, "order", default_value=None)
return entry_order is None, entry_order, extractor(config, sort_key)
sorted_missing = sorted(missing_in_order, key=key_func)
else:
def key_func(x):
config = templates[t]["entries"][x]
entry_order = config_extractor(config, "order", default_value=None)
return entry_order is None, entry_order
sorted_missing = sorted(missing_in_order, key=key_func)
if template_sorting[t]["add"] == "prepend":
templates[t]["order"] = sorted_missing + templates[t]["order"]
@@ -272,43 +559,11 @@ def index():
elif template_sorting[t]["add"] == "custom_append" and "custom_add_entries" in template_sorting[t] and "custom_add_order" in template_sorting[t]:
templates[t]["entries"].update(template_sorting[t]["custom_add_entries"](sorted_missing))
templates[t]["order"] += template_sorting[t]["custom_add_order"](sorted_missing)
elif template_sorting[t]["add"] == "custom_insert" and "custom_insert_entries" in template_sorting[t] and "custom_insert_order" in template_sorting[t]:
templates[t]["entries"].update(template_sorting[t]["custom_insert_entries"](sorted_missing))
templates[t]["order"] = template_sorting[t]["custom_insert_order"](templates[t]["order"], sorted_missing)
#~~ prepare full set of template vars for rendering
first_run = settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized())
render_kwargs = dict(
webcamStream=settings().get(["webcam", "stream"]),
enableTemperatureGraph=settings().get(["feature", "temperatureGraph"]),
enableAccessControl=userManager is not None,
enableSdSupport=settings().get(["feature", "sdSupport"]),
firstRun=first_run,
debug=debug,
version=VERSION,
display_version=DISPLAY_VERSION,
branch=BRANCH,
gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]),
gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]),
uiApiKey=UI_API_KEY,
templates=templates,
pluginNames=plugin_names,
locales=locales
)
render_kwargs.update(plugin_vars)
#~~ render!
import datetime
response = make_response(render_template(
"index.jinja2",
**render_kwargs
))
response.headers["Last-Modified"] = datetime.datetime.now()
if first_run:
response = util.flask.add_non_caching_response_headers(response)
return response
return templates, plugin_names, plugin_vars
def _process_template_configs(name, implementation, configs, rules):
@@ -354,6 +609,7 @@ def _process_template_configs(name, implementation, configs, rules):
return includes
def _process_template_config(name, implementation, rule, config=None, counter=1):
if "mandatory" in rule:
for mandatory in rule["mandatory"]:
@@ -396,78 +652,23 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
return data
@app.route("/robots.txt")
@util.flask.cached(timeout=-1)
def robotsTxt():
return send_from_directory(app.static_folder, "robots.txt")
@app.route("/i18n/<string:locale>/<string:domain>.js")
@util.flask.cached(timeout=-1,
refreshif=lambda: util.flask.cache_check_headers() or "_refresh" in request.values,
key=lambda: "view:{}:{}".format(request.base_url, g.locale))
@util.flask.conditional(lambda: _check_etag_and_lastmodified_for_i18n(), NOT_MODIFIED)
@util.flask.etagged(lambda _: _compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
@util.flask.lastmodified(lambda _: _compute_date_for_i18n(request.view_args["locale"], request.view_args["domain"]))
def localeJs(locale, domain):
messages = dict()
plural_expr = None
if locale != "en":
from flask import _request_ctx_stack
from babel.messages.pofile import read_po
def messages_from_po(base_path, locale, domain):
path = os.path.join(base_path, locale)
if not os.path.isdir(path):
return None, None
path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals()))
if not os.path.isfile(path):
return None, None
messages = dict()
with file(path) as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
message_id = message.id
if isinstance(message_id, (list, tuple)):
message_id = message_id[0]
messages[message_id] = message.string
return messages, catalog.plural_expr
user_base_path = os.path.join(settings().getBaseFolder("translations"))
user_plugin_path = os.path.join(user_base_path, "_plugins")
# plugin translations
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')]
for dirname in dirs:
if not os.path.isdir(dirname):
continue
plugin_messages, _ = messages_from_po(dirname, locale, domain)
if plugin_messages is not None:
messages = octoprint.util.dict_merge(messages, plugin_messages)
_logger.debug("Using translation folder {dirname} for locale {locale} of plugin {name}".format(**locals()))
break
else:
_logger.debug("No translations for locale {locale} for plugin {name}".format(**locals()))
# core translations
ctx = _request_ctx_stack.top
base_path = os.path.join(ctx.app.root_path, "translations")
dirs = [user_base_path, base_path]
for dirname in dirs:
core_messages, plural_expr = messages_from_po(dirname, locale, domain)
if core_messages is not None:
messages = octoprint.util.dict_merge(messages, core_messages)
_logger.debug("Using translation folder {dirname} for locale {locale} of core translations".format(**locals()))
break
else:
_logger.debug("No core translations for locale {locale}".format(**locals()))
messages, plural_expr = _get_translations(locale, domain)
catalog = dict(
messages=messages,
@@ -485,3 +686,129 @@ def plugin_assets(name, filename):
return redirect(url_for("plugin." + name + ".static", filename=filename))
def _compute_etag_for_i18n(locale, domain, files=None, lastmodified=None):
if files is None:
files = _get_all_translationfiles(locale, domain)
if lastmodified is None:
lastmodified = _compute_date(files)
if lastmodified and not isinstance(lastmodified, basestring):
from werkzeug.http import http_date
lastmodified = http_date(lastmodified)
import hashlib
hash = hashlib.sha1()
hash.update(",".join(sorted(files)))
if lastmodified:
hash.update(lastmodified)
return hash.hexdigest()
def _compute_date_for_i18n(locale, domain):
return _compute_date(_get_all_translationfiles(locale, domain))
def _compute_date(files):
from datetime import datetime
timestamps = map(lambda path: os.stat(path).st_mtime, files)
max_timestamp = max(*timestamps) if timestamps else None
if max_timestamp:
# we set the micros to 0 since microseconds are not speced for HTTP
max_timestamp = datetime.fromtimestamp(max_timestamp).replace(microsecond=0)
return max_timestamp
def _check_etag_and_lastmodified_for_i18n():
locale = request.view_args["locale"]
domain = request.view_args["domain"]
etag_ok = util.flask.check_etag(_compute_etag_for_i18n(request.view_args["locale"], request.view_args["domain"]))
lastmodified = _compute_date_for_i18n(locale, domain)
lastmodified_ok = lastmodified is None or util.flask.check_lastmodified(lastmodified)
return etag_ok and lastmodified_ok
def _get_all_templates():
from octoprint.util.jinja import get_all_template_paths
return get_all_template_paths(app.jinja_loader)
def _get_all_assets():
from octoprint.util.jinja import get_all_asset_paths
return get_all_asset_paths(app.jinja_env.assets_environment)
def _get_all_translationfiles(locale, domain):
from flask import _request_ctx_stack
def get_po_path(basedir, locale, domain):
path = os.path.join(basedir, locale)
if not os.path.isdir(path):
return None
path = os.path.join(path, "LC_MESSAGES", "{domain}.po".format(**locals()))
if not os.path.isfile(path):
return None
return path
po_files = []
user_base_path = os.path.join(settings().getBaseFolder("translations"))
user_plugin_path = os.path.join(user_base_path, "_plugins")
# plugin translations
plugins = octoprint.plugin.plugin_manager().enabled_plugins
for name, plugin in plugins.items():
dirs = [os.path.join(user_plugin_path, name), os.path.join(plugin.location, 'translations')]
for dirname in dirs:
if not os.path.isdir(dirname):
continue
po_file = get_po_path(dirname, locale, domain)
if po_file:
po_files.append(po_file)
break
# core translations
ctx = _request_ctx_stack.top
base_path = os.path.join(ctx.app.root_path, "translations")
dirs = [user_base_path, base_path]
for dirname in dirs:
po_file = get_po_path(dirname, locale, domain)
if po_file:
po_files.append(po_file)
break
return po_files
def _get_translations(locale, domain):
from babel.messages.pofile import read_po
from octoprint.util import dict_merge
messages = dict()
plural_expr = None
def messages_from_po(path, locale, domain):
messages = dict()
with file(path) as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
message_id = message.id
if isinstance(message_id, (list, tuple)):
message_id = message_id[0]
messages[message_id] = message.string
return messages, catalog.plural_expr
po_files = _get_all_translationfiles(locale, domain)
for po_file in po_files:
po_messages, plural_expr = messages_from_po(po_file, locale, domain)
if po_messages is not None:
messages = dict_merge(messages, po_messages)
return messages, plural_expr
+34 -4
View File
@@ -82,15 +82,20 @@ default_settings = {
"connection": 10,
"communication": 30,
"temperature": 5,
"temperatureTargetSet": 2,
"sdStatus": 1
},
"additionalPorts": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32"]
"additionalBaudrates": [],
"longRunningCommands": ["G4", "G28", "G29", "G30", "G32", "M400", "M226"],
"checksumRequiringCommands": ["M110"],
"helloCommand": "M110 N0",
},
"server": {
"host": "0.0.0.0",
"port": 5000,
"firstRun": True,
"seenWizards": {},
"secretKey": None,
"reverseProxy": {
"prefixHeader": "X-Script-Name",
@@ -114,6 +119,10 @@ default_settings = {
"diskspace": {
"warning": 500 * 1024 * 1024, # 500 MB
"critical": 200 * 1024 * 1024, # 200 MB
},
"preemptiveCache": {
"exceptions": [],
"until": 7
}
},
"webcam": {
@@ -145,6 +154,7 @@ default_settings = {
"temperatureGraph": True,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"neverSendChecksum": False,
"sendChecksumWithUnknownCommands": False,
"unknownCommandsNeedAck": False,
"sdSupport": True,
@@ -156,7 +166,8 @@ default_settings = {
"keyboardControl": True,
"pollWatched": False,
"ignoreIdenticalResends": False,
"identicalResendsCountdown": 7
"identicalResendsCountdown": 7,
"supportFAsCommand": False
},
"folder": {
"uploads": None,
@@ -204,6 +215,8 @@ default_settings = {
"section_octoprint", "server", "folders", "appearance", "logs", "plugin_pluginmanager", "plugin_softwareupdate"
],
"usersettings": ["access", "interface"],
"wizard": ["access"],
"about": ["about", "license", "thirdparty", "plugin_pluginmanager", "authors", "changelog"],
"generic": []
},
"disabled": {
@@ -263,7 +276,8 @@ default_settings = {
"devel": {
"stylesheet": "css",
"cache": {
"enabled": True
"enabled": True,
"preemptive": True
},
"webassets": {
"minify": False,
@@ -296,7 +310,9 @@ default_settings = {
"commandBuffer": 4,
"sendWait": True,
"waitInterval": 1.0,
"supportM112": True
"supportM112": True,
"echoOnM117": True,
"supportF": False
}
}
}
@@ -563,6 +579,20 @@ class Settings(object):
import yaml
return yaml.safe_dump(self.effective)
@property
def effective_hash(self):
import hashlib
hash = hashlib.md5()
hash.update(repr(self.effective))
return hash.hexdigest()
@property
def config_hash(self):
import hashlib
hash = hashlib.md5()
hash.update(repr(self._config))
return hash.hexdigest()
#~~ load and save
def load(self, migrate=False):
+53 -3
View File
@@ -40,14 +40,16 @@ class SlicingProfile(object):
data (object): Profile data, actual structure depends on individual slicer implementation.
display_name (str): Displayable name for this slicing profile.
description (str): Description of this slicing profile.
default (bool): Whether this is the default slicing profile for the slicer.
"""
def __init__(self, slicer, name, data, display_name=None, description=None):
def __init__(self, slicer, name, data, display_name=None, description=None, default=False):
self.slicer = slicer
self.name = name
self.data = data
self.display_name = display_name
self.description = description
self.default = default
class TemporaryProfile(object):
@@ -450,6 +452,50 @@ class SlicingManager(object):
return
os.remove(path)
def set_default_profile(self, slicer, name, require_configured=False,
require_exists=True):
"""
Sets the given profile as default profile for the slicer.
Arguments:
slicer (str): Identifier of the slicer for which to set the default
profile.
name (str): Identifier of the profile to set as default.
require_configured (bool): Whether the slicer needs to be configured
for the action to succeed. Defaults to false. Will raise a
SlicerNotConfigured error if true and the slicer has not been
configured yet.
require_exists (bool): Whether the profile is required to exist in
order to be set as default. Defaults to true. Will raise a
UnknownProfile error if true and the profile is unknown.
Raises:
~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer``
is unknown
~octoprint.slicing.exceptions.SlicerNotConfigured: The slicer ``slicer``
has not yet been configured and ``require_configured`` was true.
~octoprint.slicing.exceptions.UnknownProfile: The profile ``name``
was unknown for slicer ``slicer`` and ``require_exists`` was
true.
"""
if not slicer in self.registered_slicers:
raise UnknownSlicer(slicer)
if require_configured and not slicer in self.configured_slicers:
raise SlicerNotConfigured(slicer)
if not name:
raise ValueError("name must be set")
if require_exists and not name in self.all_profiles(slicer, require_configured=require_configured):
raise UnknownProfile(slicer, name)
default_profiles = settings().get(["slicing", "defaultProfiles"])
if not default_profiles:
default_profiles = dict()
default_profiles[slicer] = name
settings().set(["slicing", "defaultProfiles"], default_profiles)
settings().save(force=True)
def all_profiles(self, slicer, require_configured=False):
"""
Retrieves all profiles for slicer ``slicer``.
@@ -464,7 +510,7 @@ class SlicingManager(object):
exception will be raised.
Returns:
list of SlicingProfile: A list of all :class:`SlicingProfile` instances available for the slicer ``slicer``.
dict of SlicingProfile: A dict of all :class:`SlicingProfile` instances available for the slicer ``slicer``, mapped by the identifier.
Raises:
~octoprint.slicing.exceptions.UnknownSlicer: The slicer ``slicer`` is unknown.
@@ -560,7 +606,11 @@ class SlicingManager(object):
return sanitized_name
def _load_profile_from_path(self, slicer, path, require_configured=False):
return self.get_slicer(slicer, require_configured=require_configured).get_slicer_profile(path)
profile = self.get_slicer(slicer, require_configured=require_configured).get_slicer_profile(path)
default_profiles = settings().get(["slicing", "defaultProfiles"])
if default_profiles and slicer in default_profiles:
profile.default = default_profiles[slicer] == profile.name
return profile
def _save_profile_to_path(self, slicer, path, profile, allow_overwrite=True, overrides=None, require_configured=False):
self.get_slicer(slicer, require_configured=require_configured).save_slicer_profile(path, profile, allow_overwrite=allow_overwrite, overrides=overrides)
+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,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
View File
Whitespace-only changes.
File diff suppressed because it is too large. Load diff
+227
View File
@@ -0,0 +1,227 @@
<html>
<head>
<title>OctoPrint is still starting</title>
<style>
body {
margin: 0;
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333333;
background-color: #ffffff;
}
#startup-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
display: block;
}
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.wrapper .outer {
display: table;
width: 100%;
height: 100%;
}
.wrapper .outer .inner {
display: table-cell;
vertical-align: middle;
padding: 20px;
}
.wrapper .outer .inner .content {
text-align: center;
}
.green {
color: #169300;
}
.red {
color: #990000;
}
#message {
line-height: 1.3;
}
.pulsate3 {
-webkit-animation: pulsate 3s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.5;
}
.pulsate1 {
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.5;
}
@-webkit-keyframes pulsate {
0% {
opacity: 0.5;
}
50% {
opacity: 1.0;
}
100% {
opacity: 0.5;
}
}
</style>
<script>
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
function ping(url, timeout, callback) {
var img = new Image();
var calledBack = false;
var urlToUse = url;
var postfix = "_=" + Date.now();
if (url.indexOf("?") > -1) {
urlToUse += "&" + postfix;
} else {
urlToUse += "?" + postfix;
}
console.log("Pinging " + url);
img.onload = function() {
callback("load");
calledBack = true;
};
img.onerror = function() {
if (!calledBack) {
callback("error");
calledBack = true;
}
};
img.src = urlToUse;
setTimeout(function() {
if (!calledBack) {
callback("timeout");
calledBack = true;
}
}, timeout);
}
window.onload = function() {
var intervals = [1, 1, 2, 3, 5, 8];
var timeout = 1500;
var baseUrl = window.location.href;
if (baseUrl.indexOf("#") > -1) {
baseUrl = baseUrl.substring(0, baseUrl.indexOf("#"));
}
if (baseUrl.indexOf("/static") > -1) {
baseUrl = baseUrl.substring(0, baseUrl.indexOf("/static"));
}
if (baseUrl[baseUrl.length - 1] != "/") {
baseUrl += "/";
}
var serverOnlineUrl = baseUrl + "online.gif";
var backendOnlineUrl = baseUrl + "intermediary.gif";
var serverTimeout;
var message = window.document.getElementById("message");
var serverIsOnline = false;
var serverOnlineCallback = function(result) {
if (result == "load") {
// our online.gif loaded, so the server is up, let's reload
serverIsOnline = true;
message.className = "pulsate1 green";
message.innerText = "OctoPrint server online, reloading page...";
window.location = baseUrl;
} else {
// online.gif still not available, let's look at
var interval = 15;
if (intervals.length) {
interval = intervals.shift();
}
serverTimeout = setTimeout(function() {
ping(serverOnlineUrl, timeout, serverOnlineCallback);
}, interval * 1000)
}
};
var backendOfflineCounter = 0;
var backendOnlineCallback = function(result) {
if (serverIsOnline) {
return;
}
if (result == "load") {
setTimeout(function() {
ping(backendOnlineUrl, timeout, backendOnlineCallback);
}, 1000);
return;
}
backendOfflineCounter++;
if (backendOfflineCounter > 10) {
if (serverTimeout) {
window.clearTimeout(serverTimeout);
}
message.className = "red";
message.innerHTML = "Looks like something went wrong during startup, the server is gone again. You should check <code>octoprint.log</code>.";
} else {
setTimeout(function() {
ping(backendOnlineUrl, timeout, backendOnlineCallback);
}, 1000);
}
};
ping(backendOnlineUrl, timeout, backendOnlineCallback);
ping(serverOnlineUrl, timeout, serverOnlineCallback);
}
</script>
</head>
<body>
<div id="startup-overlay">
<div class="background"></div>
<div class="wrapper">
<div class="outer">
<div class="inner">
<div class="content">
<h1 id="message" class="pulsate3">OctoPrint is still starting up, please wait...</h1>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,6 @@
ko.bindingHandlers.allowBindings = {
init: function (elem, valueAccessor) {
return { controlsDescendantBindings: !valueAccessor() };
}
};
ko.virtualElements.allowedBindings.allowBindings = true;
@@ -0,0 +1,12 @@
ko.bindingHandlers.contextMenu = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
$(element).contextMenu(val);
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
$(element).contextMenu(val);
}
};
@@ -0,0 +1,8 @@
ko.bindingHandlers.invisible = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
if (!valueAccessor()) return;
ko.bindingHandlers.style.update(element, function() {
return { visibility: 'hidden' };
})
}
};
@@ -0,0 +1,16 @@
ko.bindingHandlers.popover = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
var options = {
title: val.title,
animation: val.animation,
placement: val.placement,
trigger: val.trigger,
delay: val.delay,
content: val.content,
html: val.html
};
$(element).popover(options);
}
};
@@ -0,0 +1,24 @@
ko.bindingHandlers.qrcode = {
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var val = ko.utils.unwrapObservable(valueAccessor());
var defaultOptions = {
text: "",
size: 200,
fill: "#000",
background: null,
label: "",
fontname: "sans",
fontcolor: "#000",
radius: 0,
ecLevel: "L"
};
var options = {};
_.each(defaultOptions, function(value, key) {
options[key] = ko.utils.unwrapObservable(val[key]) || value;
});
$(element).empty().qrcode(options);
}
};
@@ -0,0 +1,17 @@
ko.bindingHandlers.slimScrolledForeach = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers.foreach.init(element, valueAccessor(), allBindings, viewModel, bindingContext);
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
setTimeout(function() {
if (element.nodeName == "#comment") {
// foreach is bound to a virtual element
$(element.parentElement).slimScroll({scrollBy: 0});
} else {
$(element).slimScroll({scrollBy: 0});
}
}, 10);
return ko.bindingHandlers.foreach.update(element, valueAccessor(), allBindings, viewModel, bindingContext);
}
};
ko.virtualElements.allowedBindings.slimScrolledForeach = true;
@@ -0,0 +1,28 @@
ko.bindingHandlers.toggleContent = {
init: function(element, valueAccessor) {
var $elm = $(element),
options = $.extend({
class: null,
container: null,
parent: null,
onComplete: function() {
$(document).trigger("slideCompleted");
}
}, valueAccessor());
$elm.on("click", function(e) {
e.preventDefault();
if(options.class) {
$elm.children('[class^="icon-"]').toggleClass(options.class);
}
if(options.container) {
if(options.parent) {
$elm.parents(options.parent).find(options.container).stop().slideToggle('fast', options.onComplete);
} else {
$(options.container).stop().slideToggle('fast', options.onComplete);
}
}
});
}
};
+249
View File
@@ -0,0 +1,249 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define("OctoPrint", ["jquery", "lodash"], factory);
} else {
global.OctoPrint = factory(window.$, window._);
}
})(window || this, function($, _) {
var OctoPrint = {};
var noCache = function(opts) {
opts = opts || {};
var params = $.extend({}, opts);
params.headers = $.extend({}, params.headers || {});
params.headers["Cache-Control"] = "no-cache";
return params;
};
var contentTypeJson = function(opts) {
opts = opts || {};
var params = $.extend({}, opts);
params.contentType = "application/json; charset=UTF-8";
return params;
};
OctoPrint.options = {
"baseurl": undefined,
"apikey": undefined
};
OctoPrint.plugins = {};
OctoPrint.getBaseUrl = function() {
var url = OctoPrint.options.baseurl;
if (!_.endsWith(url, "/")) {
url = url + "/";
}
return url;
};
OctoPrint.getRequestHeaders = function(additional) {
additional = additional || {};
var headers = $.extend({}, additional);
headers["X-Api-Key"] = OctoPrint.options.apikey;
return headers;
};
OctoPrint.ajax = function(method, url, opts) {
opts = opts || {};
method = opts.method || method || "GET";
url = opts.url || url || "";
var urlToCall = url;
if (!_.startsWith(url, "http://") && !_.startsWith(url, "https://")) {
urlToCall = OctoPrint.getBaseUrl() + url;
}
var headers = OctoPrint.getRequestHeaders(opts.headers);
var params = $.extend({}, opts);
params.type = method;
params.headers = headers;
params.dataType = params.dataType || "json";
return $.ajax(urlToCall, params);
};
OctoPrint.ajaxWithData = function(method, url, data, opts) {
opts = opts || {};
var params = $.extend({}, opts);
params.data = data;
return OctoPrint.ajax(method, url, params);
};
OctoPrint.get = function(url, opts) {
return OctoPrint.ajax("GET", url, opts);
};
OctoPrint.post = function(url, data, opts) {
return OctoPrint.ajaxWithData("POST", url, data, noCache(opts));
};
OctoPrint.postJson = function(url, data, opts) {
return OctoPrint.post(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.put = function(url, data, opts) {
return OctoPrint.ajaxWithData("PUT", url, data, noCache(opts));
};
OctoPrint.putJson = function(url, data, opts) {
return OctoPrint.put(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.patch = function(url, data, opts) {
return OctoPrint.ajaxWithData("PATCH", url, data, noCache(opts));
};
OctoPrint.patchJson = function(url, data, opts) {
return OctoPrint.patch(url, JSON.stringify(data), contentTypeJson(opts));
};
OctoPrint.delete = function(url, opts) {
return OctoPrint.ajax("DELETE", url, opts);
};
OctoPrint.download = function(url, opts) {
var params = $.extend({}, opts || {});
params.dataType = "text";
return OctoPrint.get(url, params);
};
OctoPrint.upload = function(url, file, filename, additional) {
additional = additional || {};
var fileData;
if (file instanceof jQuery) {
fileData = file[0].files[0];
} else if (typeof file == "string") {
fileData = $(file)[0].files[0];
} else {
fileData = file;
}
filename = filename || fileData.name;
var form = new FormData();
form.append("file", fileData, filename);
_.each(additional, function(value, key) {
form.append(key, value);
});
var deferred = $.Deferred();
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4) {
deferred.notify({loaded: filesize, total: filesize});
var success = request.status >= 200 && request.status < 300
|| request.status === 304;
var error, json, statusText;
try {
json = JSON.parse(request.response);
statusText = "success";
} catch (e) {
success = false;
error = e;
statusText = "parsererror";
}
if (success) {
deferred.resolve([json, statusText, request]);
} else {
if (!statusText) {
statusText = request.statusText;
}
deferred.reject([request, statusText, error]);
}
}
};
request.ontimeout = function() {
deferred.reject([request, "timeout", "Timeout"]);
};
request.upload.addEventListener("loadstart", function(e) {
deferred.notify({loaded: e.loaded, total: e.total});
});
request.upload.addEventListener("progress", function(e) {
deferred.notify({loaded: e.loaded, total: e.total});
});
request.upload.addEventListener("loadend", function(e) {
deferred.notify({loaded: e.loaded, total: e.total});
});
var headers = OctoPrint.getRequestHeaders();
request.open("POST", OctoPrint.getBaseUrl() + url);
_.each(headers, function(value, key) {
request.setRequestHeader(key, value);
});
request.send(form);
return deferred.promise();
};
OctoPrint.issueCommand = function(url, command, payload, opts) {
payload = payload || {};
var data = $.extend({}, payload);
data.command = command;
return OctoPrint.postJson(url, data, opts);
};
OctoPrint.getSimpleApiUrl = function(plugin) {
return "api/plugin/" + plugin;
};
OctoPrint.simpleApiGet = function(plugin, opts) {
return OctoPrint.get(OctoPrint.getSimpleApiUrl(plugin), opts);
};
OctoPrint.simpleApiCommand = function(plugin, command, payload, opts) {
return OctoPrint.issueCommand(OctoPrint.getSimpleApiUrl(plugin), command, payload, opts);
};
OctoPrint.getBlueprintUrl = function(plugin) {
return "plugin/" + plugin + "/";
};
OctoPrint.createRejectedDeferred = function() {
var deferred = $.Deferred();
deferred.reject(arguments);
return deferred;
};
OctoPrint.createCustomException = function(name) {
var constructor;
if (_.isFunction(name)) {
constructor = name;
} else {
constructor = function(message) {
this.name = name;
this.message = message;
this.stack = (new Error()).stack;
};
}
constructor.prototype = Object.create(Error.prototype);
constructor.prototype.constructor = constructor;
return constructor;
};
OctoPrint.InvalidArgumentError = OctoPrint.createCustomException("InvalidArgumentError");
return OctoPrint;
});
@@ -0,0 +1,29 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
} else {
factory(window.OctoPrint);
}
})(window || this, function(OctoPrint) {
var loginUrl = "api/login";
var logoutUrl = "api/logout";
OctoPrint.browser = {
login: function(username, password, remember, opts) {
var data = {
user: username,
pass: password,
remember: !!remember
};
return OctoPrint.postJson(loginUrl, data, opts);
},
passiveLogin: function(opts) {
return OctoPrint.postJson(loginUrl, {passive: true}, opts);
},
logout: function(opts) {
return OctoPrint.postJson(logoutUrl, {}, opts);
}
};
});
@@ -0,0 +1,27 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrint"], factory);
} else {
factory(window.OctoPrint);
}
})(window || this, function(OctoPrint) {
var url = "api/connection";
OctoPrint.connection = {
getSettings: function(opts) {
return OctoPrint.get(url, opts);
},
connect: function(data, opts) {
return OctoPrint.issueCommand(url, "connect", data || {}, opts);
},
disconnect: function(opts) {
return OctoPrint.issueCommand(url, "disconnect", {}, opts);
},
fakeAck: function(opts) {
return OctoPrint.issueCommand(url, "fake_ack", {}, opts);
}
}
});
Loaded 100 of 216 files, more files were not shown because too many files have changed in this diff. Show more